Here's a general idea of how my class is defined as ( it performs other operations than what is mentioned below)
struct Funktor
{
Funktor(int val):m_val(val){}
bool operator()(int arg1, int arg2) { return m_val==arg1*arg2; }
int m_val;
};
And now I have a vector of the above objects, and I am trying to call operator() using for_each, is there a way to do this? I know it can be done using bind2nd and mem_func_ref but when there's only one argument but for two arguments I haven't found a way.
int main()
{
std::vector<Funktor> funktors;
funktors.push_back(Funktor(10));
funktors.push_back(Funktor(20));
funktors.push_back(Funktor(30));
int arg1 = 5, arg2 = 6;
//instead of the for loop below I want to use for_each
for(std::vector<Funktor>::iterator itr = funktors.begin(); funktors.end() != itr; ++itr)
{
(*itr)(arg1,arg2);
}
}
Thanks for any help. Best.
CV
C++03 Solution (without boost):
Write another functor as:
struct TwoArgFunctor
{
int arg1, arg2;
TwoArgFunctor(int a, int b) :arg1(a), arg2(b) {}
template<typename Functor>
bool operator()(Functor fun)
{
return fun(arg1, arg2); //here you invoke the actual functor!
}
};
Then use it as:
std::for_each(funktors.begin(),funktors.end(), TwoArgFunctor(arg1,arg2));
C++11 Solution:
std::for_each(funktors.begin(),funktors.end(),
[&] (Funktor f) -> bool { return f(arg1,arg2); });
Related
trying to compile the following code I get this compile error, what can I do?
ISO C++ forbids taking the address of
an unqualified or parenthesized
non-static member function to form a
pointer to member function.
class MyClass {
int * arr;
// other member variables
MyClass() { arr = new int[someSize]; }
doCompare( const int & i1, const int & i2 ) { // use some member variables }
doSort() { std::sort(arr,arr+someSize, &doCompare); }
};
doCompare must be static. If doCompare needs data from MyClass you could turn MyClass into a comparison functor by changing:
doCompare( const int & i1, const int & i2 ) { // use some member variables }
into
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
and calling:
doSort() { std::sort(arr, arr+someSize, *this); }
Also, isn't doSort missing a return value?
I think it should be possible to use std::mem_fun and some sort of binding to turn the member function into a free function, but the exact syntax evades me at the moment.
EDIT: Doh, std::sort takes the function by value which may be a problem. To get around this wrap the function inside the class:
class MyClass {
struct Less {
Less(const MyClass& c) : myClass(c) {}
bool operator () ( const int & i1, const int & i2 ) {// use 'myClass'}
MyClass& myClass;
};
doSort() { std::sort(arr, arr+someSize, Less(*this)); }
}
As Andreas Brinck says, doCompare must be static (+1). If you HAVE TO have a state in your comparator function (using the other members of the class) then you'd better use a functor instead of a function (and that will be faster):
class MyClass{
// ...
struct doCompare
{
doCompare( const MyClass& info ) : m_info(info) { } // only if you really need the object state
const MyClass& m_info;
bool operator()( const int & i1, const int & i2 )
{
// comparison code using m_info
}
};
doSort()
{ std::sort( arr, arr+someSize, doCompare(*this) ); }
};
Using a functor is always better, just longer to type (that can be unconvenient but oh well...)
I think you can also use std::bind with the member function but I'm not sure how and that wouldn't be easy to read anyway.
UPDATE 2014: Today we have access to c++11 compilers so you could use a lambda instead, the code would be shorter but have the exact same semantic.
The solution proposed by Rob is now valid C++11 (no need for Boost):
void doSort()
{
using namespace std::placeholders;
std::sort(arr, arr+someSize, std::bind(&MyClass::doCompare, this, _1, _2));
}
Indeed, as mentioned by Klaim, lambdas are an option, a bit more verbose (you have to "repeat" that the arguments are ints):
void doSort()
{
std::sort(arr, arr+someSize, [this](int l, int r) {return doCompare(l, r); });
}
C++14 supports auto here:
void doSort()
{
std::sort(arr, arr+someSize, [this](auto l, auto r) {return doCompare(l, r); });
}
but still, you declared that arguments are passed by copy.
Then the question is "which one is the most efficient". That question was treated by Travis Gockel: Lambda vs Bind. His benchmark program gives on my computer (OS X i7)
Clang 3.5 GCC 4.9
lambda 1001 7000
bind 3716166405 2530142000
bound lambda 2438421993 1700834000
boost bind 2925777511 2529615000
boost bound lambda 2420710412 1683458000
where lambda is a lambda used directly, and lambda bound is a lambda stored in a std::function.
So it appears that lambdas are a better option, which is not too much of a surprise since the compiler is provided with higher level information from which it can make profit.
You can use boost::bind:
void doSort() {
std::sort(arr,arr+someSize, boost::bind(&MyClass::doCompare, this, _1, _2));
}
There is a way to do what you want, but you need to use a small adaptor. As the STL doesn't write it for you, can can write it yourself:
template <class Base, class T>
struct adaptor_t
{
typedef bool (Base::*method_t)(const T& t1, const T& t2));
adaptor_t(Base* b, method_t m)
: base(b), method(m)
{}
adaptor_t(const adaptor_t& copy) : base(copy.base), method(copy.method) {}
bool operator()(const T& t1, const T& t2) const {
return (base->*method)(t1, t2);
}
Base *base;
method_t method;
}
template <class Base, class T>
adaptor_t<Base,T> adapt_method(Base* b, typename adaptor_t<Base,T>::method_t m)
{ return adaptor_t<Base,T>(b,m); }
Then, you can use it:
doSort() { std::sort(arr,arr+someSize, adapt_method(this, &doCompare)); }
The third argument in the calling of std::sort() is not compatible to the function pointer needed by std::sort(). See my answer to another question for a detailed explanation for why a member function signature is different from a regular function signature.
just make your helper function, static which you are going to pass inside the sort function.
for e.g
struct Item
{
int val;
int id;
};
//Compare function for our Item struct
static bool compare(Item a, Item b)
{
return b.val>a.val;
}
Now you can pass this inside your sort function
A very simple way to effectively use a member function is to use operator<. That is, if you have a function called compare, you can call it from operator<. Here is a working example:
class Qaz
{
public:
Qaz(int aX): x(aX) { }
bool operator<(const Qaz& aOther) const
{
return compare(*this,aOther);
}
static bool compare(const Qaz& aP,const Qaz& aQ)
{
return aP.x < aQ.x;
}
int x;
};
Then you don't even need to give the function name to std::sort:
std::vector<Qaz> q;
q.emplace_back(8);
q.emplace_back(1);
q.emplace_back(4);
q.emplace_back(7);
q.emplace_back(6);
q.emplace_back(0);
q.emplace_back(3);
std::sort(q.begin(),q.end());
Updating Graham Asher answer, as you don't need the compare but can use the less operator directly.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Qaz {
public:
Qaz(int aX): x(aX) { }
bool operator<(const Qaz& aOther) const {
return x < aOther.x;
}
int x;
};
int main() {
std::vector<Qaz> q;
q.emplace_back(8);
q.emplace_back(1);
q.emplace_back(4);
q.emplace_back(7);
q.emplace_back(6);
q.emplace_back(0);
q.emplace_back(3);
std::sort(q.begin(),q.end());
for (auto& num : q)
std::cout << num.x << "\n";
char c;
std::cin >> c;
return 0;
}
I have many defined functions as follows, all return an int
int fn1(int x) {
return x;
}
int fn2(std::string x, int y, std::string z) {
// process string x and z
int x1 = process(x);
int z1 = process(z);
return x1 + y + z1;
}
// ... and many more similar functions
For some reasons, I need to implement a wrapper to call the above functions by function names,
int wrapper(std::string fn_name, some_struct_t data, std::vector<std::string> field_names) {
a_fn_ptr_type fn_ptr = nullptr; // <q1>: is this a right way to do?
// by fn_name, decide which fn to call
if (fn_name == "fn1") {
fn_ptr = &fn1;
}
if (fn_name == "fn2") {
fn_ptr = &fn2;
}
...
// given field_names, get the field from data, pass them to fn_ptr as args
for (auto field_name: field_names) {
std::any value = get_from_data(data, field_name, field_type); // field_type will be updated by this call, so that we know the value type.
// <q2>: but how to pass each value as arg to fn_ptr here?
}
}
The above code demonstrate what I want to achieve, and I have 2 questions (as pointed by <q1> and <q2>).
I'm not sure if the code is the right way to go, hope to get some advice from people, thanks!
Inspired by the comments:
A wrapper that takes some_struct_t data, std::vector<std::string> field_names. Assuming a
template <typename T>
T get_from_data(some_struct_t, std::string);
You have a function type
using func_t = std::function<int(const some_struct_t &, const std::vector<std::string>&)>;
which you can instantiate from functions via
template <typename... Args, size_t... Is>
auto wrap_impl(int(*func)(Args...), std::index_sequence<Is...>)
{
return [func](const some_struct_t & data, const std::vector<std::string>& field_names)
{ return func(get_from_data<Args>(data, field_names.at(Is))...); };
}
template <typename... Args>
func_t wrap(int(*func)(Args...))
{
return wrap_impl(func, std::index_sequence_for<Args...>{});
}
and then you can have a
std::map<std::string, func_t> functions;
Can I use C++ template classes to differentiate object types? Or what should I use?
Eg. I have a class Synonym and it can be of type Statement, Procedure, etc for example. I have functions that accepts these synonyms and evaluates them depending on its type. So I was thinking it will be nice if I can do something like:
enum Types { Statement, Procedure, Variable, ... };
template <typename Types>
class Synonym { ... }
void evaluate(Synonym<Statement> s, Synonym<Variable> v) { do something }
^ so that I can do this ... instead of checking the type in function like:
void evaluate(Synonym s, Synonym v) {
assert(s.type == Statement);
assert(v.type == Variable);
// also would like to eliminate things like: (if possible)
switch(s.type) {
case XXX: doSomething ...
case YYY: doAnotherThing ...
}
}
You could create a function template and then specialize on that template
template<typename Type>
void evaluate (Type t) {}
template<>
void evaluate<Statement>( Statement s)
{}
This way, when you pass a Statement it will pick that overload, and you can do different behaviors depending on type.
I think using a variant and visitor pattern would be suited. Have a look at Boost.Variant here: http://www.boost.org/doc/libs/1_51_0/doc/html/variant.html, the last example (also below but expanded) shows a visitor implementation. There are also other variant and visitor implementations. std::any and loki are also options. I personally like loki but that is probably just because I'm a huge fan of Alexandrescu.
#include "boost/variant.hpp"
#include <iostream>
class ToLengthVisitor : public boost::static_visitor<int>
{
public:
int operator()(int i) const
{
return i;
}
int operator()(const std::string & str) const
{
return str.length();
}
int operator()(const char * str) const
{
const char * temp = str;
while(*temp != '\0') temp++;
return temp-str;
}
};
int main()
{
typedef boost::variant< int, std::string, const char * > MyVariant;
MyVariant u(std::string("hello world"));
std::cout << u; // output: hello world
MyVariant cu(boost::get<std::string>(u).c_str());
int result = boost::apply_visitor( ToLengthVisitor(), u );
std::cout << result; // output: 11 (i.e., length of "hello world")
result = boost::apply_visitor( ToLengthVisitor(), cu );
std::cout << result; // output: 11 (i.e., length of "hello world")
}
trying to compile the following code I get this compile error, what can I do?
ISO C++ forbids taking the address of
an unqualified or parenthesized
non-static member function to form a
pointer to member function.
class MyClass {
int * arr;
// other member variables
MyClass() { arr = new int[someSize]; }
doCompare( const int & i1, const int & i2 ) { // use some member variables }
doSort() { std::sort(arr,arr+someSize, &doCompare); }
};
doCompare must be static. If doCompare needs data from MyClass you could turn MyClass into a comparison functor by changing:
doCompare( const int & i1, const int & i2 ) { // use some member variables }
into
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
and calling:
doSort() { std::sort(arr, arr+someSize, *this); }
Also, isn't doSort missing a return value?
I think it should be possible to use std::mem_fun and some sort of binding to turn the member function into a free function, but the exact syntax evades me at the moment.
EDIT: Doh, std::sort takes the function by value which may be a problem. To get around this wrap the function inside the class:
class MyClass {
struct Less {
Less(const MyClass& c) : myClass(c) {}
bool operator () ( const int & i1, const int & i2 ) {// use 'myClass'}
MyClass& myClass;
};
doSort() { std::sort(arr, arr+someSize, Less(*this)); }
}
As Andreas Brinck says, doCompare must be static (+1). If you HAVE TO have a state in your comparator function (using the other members of the class) then you'd better use a functor instead of a function (and that will be faster):
class MyClass{
// ...
struct doCompare
{
doCompare( const MyClass& info ) : m_info(info) { } // only if you really need the object state
const MyClass& m_info;
bool operator()( const int & i1, const int & i2 )
{
// comparison code using m_info
}
};
doSort()
{ std::sort( arr, arr+someSize, doCompare(*this) ); }
};
Using a functor is always better, just longer to type (that can be unconvenient but oh well...)
I think you can also use std::bind with the member function but I'm not sure how and that wouldn't be easy to read anyway.
UPDATE 2014: Today we have access to c++11 compilers so you could use a lambda instead, the code would be shorter but have the exact same semantic.
The solution proposed by Rob is now valid C++11 (no need for Boost):
void doSort()
{
using namespace std::placeholders;
std::sort(arr, arr+someSize, std::bind(&MyClass::doCompare, this, _1, _2));
}
Indeed, as mentioned by Klaim, lambdas are an option, a bit more verbose (you have to "repeat" that the arguments are ints):
void doSort()
{
std::sort(arr, arr+someSize, [this](int l, int r) {return doCompare(l, r); });
}
C++14 supports auto here:
void doSort()
{
std::sort(arr, arr+someSize, [this](auto l, auto r) {return doCompare(l, r); });
}
but still, you declared that arguments are passed by copy.
Then the question is "which one is the most efficient". That question was treated by Travis Gockel: Lambda vs Bind. His benchmark program gives on my computer (OS X i7)
Clang 3.5 GCC 4.9
lambda 1001 7000
bind 3716166405 2530142000
bound lambda 2438421993 1700834000
boost bind 2925777511 2529615000
boost bound lambda 2420710412 1683458000
where lambda is a lambda used directly, and lambda bound is a lambda stored in a std::function.
So it appears that lambdas are a better option, which is not too much of a surprise since the compiler is provided with higher level information from which it can make profit.
You can use boost::bind:
void doSort() {
std::sort(arr,arr+someSize, boost::bind(&MyClass::doCompare, this, _1, _2));
}
There is a way to do what you want, but you need to use a small adaptor. As the STL doesn't write it for you, can can write it yourself:
template <class Base, class T>
struct adaptor_t
{
typedef bool (Base::*method_t)(const T& t1, const T& t2));
adaptor_t(Base* b, method_t m)
: base(b), method(m)
{}
adaptor_t(const adaptor_t& copy) : base(copy.base), method(copy.method) {}
bool operator()(const T& t1, const T& t2) const {
return (base->*method)(t1, t2);
}
Base *base;
method_t method;
}
template <class Base, class T>
adaptor_t<Base,T> adapt_method(Base* b, typename adaptor_t<Base,T>::method_t m)
{ return adaptor_t<Base,T>(b,m); }
Then, you can use it:
doSort() { std::sort(arr,arr+someSize, adapt_method(this, &doCompare)); }
The third argument in the calling of std::sort() is not compatible to the function pointer needed by std::sort(). See my answer to another question for a detailed explanation for why a member function signature is different from a regular function signature.
just make your helper function, static which you are going to pass inside the sort function.
for e.g
struct Item
{
int val;
int id;
};
//Compare function for our Item struct
static bool compare(Item a, Item b)
{
return b.val>a.val;
}
Now you can pass this inside your sort function
A very simple way to effectively use a member function is to use operator<. That is, if you have a function called compare, you can call it from operator<. Here is a working example:
class Qaz
{
public:
Qaz(int aX): x(aX) { }
bool operator<(const Qaz& aOther) const
{
return compare(*this,aOther);
}
static bool compare(const Qaz& aP,const Qaz& aQ)
{
return aP.x < aQ.x;
}
int x;
};
Then you don't even need to give the function name to std::sort:
std::vector<Qaz> q;
q.emplace_back(8);
q.emplace_back(1);
q.emplace_back(4);
q.emplace_back(7);
q.emplace_back(6);
q.emplace_back(0);
q.emplace_back(3);
std::sort(q.begin(),q.end());
Updating Graham Asher answer, as you don't need the compare but can use the less operator directly.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Qaz {
public:
Qaz(int aX): x(aX) { }
bool operator<(const Qaz& aOther) const {
return x < aOther.x;
}
int x;
};
int main() {
std::vector<Qaz> q;
q.emplace_back(8);
q.emplace_back(1);
q.emplace_back(4);
q.emplace_back(7);
q.emplace_back(6);
q.emplace_back(0);
q.emplace_back(3);
std::sort(q.begin(),q.end());
for (auto& num : q)
std::cout << num.x << "\n";
char c;
std::cin >> c;
return 0;
}
Lets say I have hierarchy like this (This is just a test program. Please do not point anything related to memory leaks, destructor is not virtual etc):
class I
{
public:
virtual void fun(int n, int n1) = 0;
};
class A : public I
{
public:
void fun(int n, int n1)
{
std::cout<<"A::fun():" <<n<<" and n1:" <<n1<<"\n";
}
};
class B : public I
{
public:
void fun(int n, int n1)
{
std::cout<<"B::fun():" <<n<<" and n1:" <<n1<<"\n";
}
};
int main()
{
std::vector<I*> a;
a.push_back(new A);
a.push_back(new B);
//I want to use std::for_each to call function fun with two arguments.
}
How do I call fun() method which takes two arguments using the std::for_each ? I think I have to use std::mem_fun probably with std::bind2nd but am not able to figure out how to do this. Any clue how to achieve this? I am not using boost.
You could create your own functor like this:
class Apply
{
private:
int arg1, arg2;
public:
Apply(int n, int n1)
: arg1(n), arg2(n1)
{}
void operator() (I* pI) const
{
pI->fun(arg1, arg2);
}
};
int main ()
{
// ...
std::for_each(a.begin(), a.end(), Apply(n, n1));
}
or use boost::bind like this:
std::for_each(
a.begin(),
a.end(),
boost::bind(&I::fun, _1, n, n1));
You can't do this with the std binders. You can of course write your own functor.
struct TwoArguments
{
int one;
int two;
TwoArguments( int one, int two ) : one(one),two(two){
}
void operator()( I* i ) const {
i->fun( one, two );
}
};
Another way to do this would be to use templates. (Please tell me if it's a bad practice though!)
template<int N, int N1>
void Apply(I* i)
{
i->fun(N, N1);
}
std::for_each(a.begin(), a.end(), Apply<firstParam, secondParam>);
That would be good if you don't intend to call it with a lot of different parameters since it would generate code for every combination you made.