将函数对象传递给构造函数

时间:2015-08-04 13:17:40

标签: c++ c++11 constructor functor most-vexing-parse

我想要实现的是制作一个可以将不同仿函数作为参数的仿函数。

编辑:我的问题的原因,最令人烦恼的解析"以及解决方案都有详细描述:请参阅this question and answer,整个{{3标签,甚至是。不过,在询问之前我无法确定问题,并会留下这个问题,因为它可能对其他人有所帮助。

我做了什么:

在标头文件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

使用此标题,我可以像这样编写程序functor.cpp

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

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

我可以按预期编译并运行它来获取:

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

我正在努力寻找一种方法来使用不同的运算符(而不是doer)来实例化std::plus<T>

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

这编译没有问题,但我无法找到一种方法来调用f2(3, 7)来获取产品21.例如,如果我在程序中添加另一行:

int r = f2(3, 7);

并尝试编译,我得到:

$ 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);
                    ^

发生了什么事?看起来几乎就像f2(3, 7)某种方式不会调用重载的operator() ...

1 个答案:

答案 0 :(得分:1)

最令人烦恼的解析。试试这个:

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

或者这个:

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

或者这个:

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