mardi 4 août 2015

Passing a function object to a constructor [duplicate]

This question already has an answer here:

What I am trying to achieve is to make a functor that can take different functors as arguments. What I managed to do is:

In a header file functor.hpp:

#ifndef FUNCTOR_HPP
#define FUNCTOR_HPP

#include <functional>

template <typename T, typename BinOp = typename std::plus<T>>
struct doer {
    BinOp op;
    doer(BinOp o = std::plus<T>()) : op(o) {}
    T operator()(const T& a, const T& b) const
    { return op(a, b); }
};

#endif // FUNCTOR_HPP

With this header, I can write a program functor.cpp like this:

#include <iostream>
#include "functor.hpp"

int main()
{
    doer<int> f;
    std::cout << f(3, 7) << std::endl;
}

and I can compile and run it to get, as expected:

$ make functor
g++ -std=c++14 -pedantic -Wall    functor.cpp   -o functor
$ ./functor
10
$ 

I am struggling to find a way to instantiate my doer with a different operator (not std::plus<T>).

doer<int, std::multiplies<int>> f2(std::multiplies<int>());

This compiles without a problem, but I have not been able to figure out a way to call f2(3, 7), to get the product 21. For example, if I add another line to the program:

int r = f2(3, 7);

and try to compile, I get:

$ make functor
g++ -std=c++14 -pedantic -Wall    functor.cpp   -o functor
functor.cpp: In function ‘int main()’:
functor.cpp:10:20: error: invalid conversion from ‘int’ to ‘std::multiplies<int> (*)()’ [-fpermissive]
     int r = f2(3, 7);
                    ^
functor.cpp:10:20: error: too many arguments to function ‘doer<int, std::multiplies<int> > f2(std::multiplies<int> (*)())’
functor.cpp:9:37: note: declared here
     doer<int, std::multiplies<int>> f2(std::multiplies<int>());
                                     ^
functor.cpp:10:20: error: cannot convert ‘doer<int, std::multiplies<int> >’ to ‘int’ in initialization
     int r = f2(3, 7);
                    ^

What is going on? Seems almost like f2(3, 7) somehow is not calling the overloaded operator()...

Aucun commentaire:

Enregistrer un commentaire