I have a lot of functors that I am passing to a function to do some testing work. My goal is to do these with std::bind and not use lambdas. But the very simple cases seem hard to do with bind. My first question was here.
Now I want to know if there is a pass through delayed function call that I can create with bind. Something like: auto foo = std::bind( std::placeholders::_1 ) Such that foo( 13 ) will return 13.
This is the same answer given on the linked question:
So there is a way to accomplish this using std::integral_constant:
const int thirteen = 13;
auto refWrap = bind( &std::integral_constant< int, thirteen >::operator int, std::integral_constant< int, thirteen >() );
This does solve the question, but for all intents and purposes is inferior to the lambda:
const int thirteen = 13;
auto refWrap = [=](){ return thirteen; };
Related
hello guys i am new to maps in C++ i am having a question regarding copying a particular type map to another map of same kind the details are shown below
I initially declared a map like this
map<string,int> objmap,obj_porcess ;
for(int i = 0; i < 10; i++) {
objmap ["process"+to_string(i)]=i+10//some processing the to_string is just in case but i have strings with names for all 10 values
}
like
objmap["process_today"]=1;
objmap["process_yesterday"]=-1;
objmap["process_tommorow"]=2;
now i want to define some thing like this just my key word should be added with the process and remaining all can be same for all the keys from obj_process
obj_process["today"]=objmap["process_today"] ;
instead of defining all 10 can i have a simple code cause in here i took an example of 10 but i have like 200 set of different strings in the key of map
i already asked a qn for exact opposite one this was my previous qn now when i try its vice versa i got an issue hope i find some help
If you can initialize both at the same time, the solution is straightforward:
const std::vector<std::string> days = {"today", "yesterday", /*...*/};
for(const auto& d : days)
{
objmap["process_" + d] = foo();
obj_process[d] = foo();
}
If you cannot, you should be able to iterate over objmap and get rid of the "process_" prefix with some basic string manipulation:
constexpr auto prefix_length = 8; // length of "process_"
for (const auto& p : objmap)
{
const auto& key = p.first;
const auto& processed_key = key.substr(prefix_length);
obj_process[processed_key] = objmap[key];
}
I am looking at the lambda generators from https://stackoverflow.com/a/12735970 and https://stackoverflow.com/a/12639820.
I would like to adapt these to a template version and I'm wondering what I should return to signal that the generator has reached its end.
Consider
template<typename T>
std::function<T()> my_template_vector_generator(std::vector<T> &v) {
int idx = 0;
return [=,&v]() mutable {
return v[idx++];
};
}
The [=,&v] addition is mine and I hope it's correct. For now, it lets me change the vector outside as expected. Please comment on this if you have a bad feeling about it...
For reference, this works (REQUIRE is from catch):
std::vector<double> v({1.0, 2.0, 3.0});
auto vec_gen = my_template_vector_generator(v);
REQUIRE( vec_gen() == 1 );
REQUIRE( vec_gen() == 2 );
v[2] = 5.0;
REQUIRE( vec_gen() == 5.0 );
That vector version obviously requires knowledge of v.size() at the call site. I'd like to go without that by returning something that indicates the generator is empty.
Brainstorming, I can think of the following:
return pair<T, bool> and indicate false once there are no more values.
return iterators to the container values and iterate for (auto it=gen(); it!=gen.end(); it=gen()) {cout << *it << endl;}
wrapping the generator in a class and implementing an empty() method. Not entirely sure how that would work, however.
Does either of these versions feel good to you? Do you have another idea?
I'd particularly be interested in implications when mapping such a generator or combining them recursively (see this C++14 blog post for inspiration).
Update:
After hearing the optional suggestions, I implemented something based on unique_ptr.
template<typename T>
std::function<std::unique_ptr<T>()> my_pointer_template_vector_generator(std::vector<T> &v) {
int idx = 0;
return [=,&v]() mutable {
if (idx < v.size()) {
return std::unique_ptr<T>(new T(v[idx++]));
} else {
return std::unique_ptr<T>();
}
};
}
This seems to work, consider the following passing test.
TEST_CASE("Pointer generator terminates as expected") {
std::vector<double> v({1.0, 2.0, 3.0});
int k = 0;
auto gen = my_pointer_template_vector_generator(v);
while(auto val = gen()) {
REQUIRE( *val == v[k++] );
}
REQUIRE( v.size() == k );
}
I have some concerns about creating lots of new T. I suppose I could also return pointers into the vector and nullptr otherwise. That should work in the same way. What do you think about this?
As soon as it looks like just study example i could suggest to add exception as end of collection. But do not use it in real code.
As far as i have seen function pointers do not exist in MQL4.
As a workaround i use:
// included for both caller as callee side
class Callback{
public: virtual void callback(){ return; }
}
Then in the source where a callback is passed from:
class mycb : Callback{
public: virtual void callback(){
// call to whatever function needs to be called back in this source
}mcbi;
now mcbi can be passed as follows:
afunction(){
fie_to_receive_callback((Callback *)mycbi);
}
and the receiver can callback as:
fie_to_receive_callback(mycb *mcbi){
mcbi.callback(); // call the callback function
}
is there a simpler way to pass a function callback in mql4 ?
Actually there is a way, using function pointers in MQL4.
Here is an example:
typedef int(*MyFuncType)(int,int);
int addition (int a, int b)
{ return (a+b); }
int subtraction (int a, int b)
{ return (a-b); }
int operation (int x, int y, MyFuncType myfunc)
{
int g;
g = myfunc(x,y);
return (g);
}
int OnInit()
{
int m,n;
m = operation (7, 5, addition);
n = operation (20, m, subtraction);
Print(n);
return(INIT_FAILED); //just to close the expert
}
No. Fortunately there is not. ( . . . . . . . however MQL4 language syntax creeps * )
MQL4 Runtime Execution Engine ( MT4 ) has rather fragile process/thread handling and adding more ( and smarter ) constructs ( beyond rudimentary { OnTimer() | OnTick() | OnCalculate() } event-bound callbacks ) constitutes rather a threat to the already unguaranteed RealTime Execution of the main MT4-duties. While "New"-MQL4.56789 may provide hacks into doing so, there might be safer rather an off-loading strategy to go distributed and let MT4-legacy handlers receive "pre-baked" results from external processing Cluster, rather than trying to hang more and more and more flittering gadgets on a-years-old-poor-Xmas-tree.
To realise how brute this danger-avoidance is, just notice that original OnTimer() used 1 second resolution ( yes 1.000.000.000 ns steps in the world, where stream-providers label events in nano-seconds ... )
* ): Yes, since "new"-MQL4 introduction, there were many stealth-mode changes in the original MQL4-language. After each update it is more than recommendable to review "new"-Help file, as there might be both new options & nasty surprises. Maintaining an MQL4 Code-Base with more than a few hundreds man*years, this is indeed a very devastating experience.
(this is a contrived example)
I want to compute std::is_any of empty() on a std::vector<std::vector>.
I can do it with lambda expressions:
std::any_of(vecs.begin(), vecs.end(),
[](std::vector<T> const &v) { return v.empty(); });
that lambda looks needlessly ugly to me. Is there a way to use std::bind in this situation instead?
I know you asked for std::bind, but you can do the same thing with std::mem_fn with very little hassle:
std::any_of(begin(vecs), end(vecs), std::mem_fn(&std::vector<T>::empty));
(still not as clean as the lambda though, in my opinion.)
Challenge accepted:
std::any_of(vecs.begin(), vecs.end(),
std::bind(&std::vector<T>::empty, std::placeholders::_1));
The following uses std::mem_fn instead of std::bind, tested with GCC-4.9:
std::any_of(vecs.begin(), vecs.end(), std::mem_fn(&std::vector<T>::empty));
I suggest that this could be enough but would we use uglier syntax anyway
bool is_empt(vector<int>& p){
return p.empty();
}
int main (){
// placeholders and bind function TRY
vector<vector<int>> v ;
v.resize(5);
auto fn = std::bind(is_empt , placeholders::_1);
if (std::any_of(all(v) , [fn] (std::vector<int> &v1) {return fn(v1);}))
cout << "True\n";
return 0;
}
I understand that the idiomatic way to create an enum in GO is as follows:
type topicStatus int
const (
registered topicStatus = iota
active
inactive
pending-removal
removed
)
but if I have another "enum" that wants to "reuse" a name, I get an error:
type hotelVisit int
const (
registered hotelVisit = iota
checked-in
checked-out
)
Here, if I try this, I cannot differentiate between topicStatus.registered and hotelVisit.registered as "registered" was previously used - is there a way to "namespace" the "enum" names?
Polluting the namespace with numerous common word lower case identifiers that are likely to cause naming conflicts isn't something I'd consider idiomatic Go. Same goes for creating packages just to hold a handful of constant declarations.
I'd probably do something like this:
type topicStatus int
const (
tsRegistered topicStatus = iota
tsActive
tsInactive
tsPendingRemoval
tsRemoved
)
type hotelVisit int
const (
hvRegistered hotelVisit = iota
hvCheckedIn
hvCheckedOut
)
Now you can declare and initialize with ts := tsPendingRemoval. Clear and concise with little risk of naming conflicts.
One workaround is to use an anonymous struct to define a namespace.
type TopicStatusType int
const (
registered topicStatus = iota
active
...
)
var TopicStatus = struct{
Registered TopicStatusType
Active TopicStatusType
...
}{
Registered: registered,
Active: active,
...
}
Create a new package for each of the enums you want to define. This means creating a sub-directory with a go file the has "package topicStatus" with the const definition inside (sub-directory name is the same as the package name).
Remember all the constants defined must be upper case so they are exportable.
Do the same for "hotelVisit" and whatever you need.
Your program will import these packages and then use them as needed: hotelVisit.Registered, topicStatus.Registered.
You can do like this:
var JobRunPhaseConstants = struct {
QUEUE_PRE_EXEC int
JOB_PRE_EXEC int
JOB_RUN int
JOB_POST_EXEC int
QUEUE_POST_EXEC int
}{
QUEUE_PRE_EXEC: 1,
JOB_PRE_EXEC: 2,
JOB_RUN: 3,
JOB_POST_EXEC: 4,
QUEUE_POST_EXEC: 5,
}
// usage example
var a = JobRunPhaseConstants.JOB_RUN