【问题标题】:Passing a function object to a constructor [duplicate]将函数对象传递给构造函数[重复]
【发布时间】:2015-08-04 13:17:39
【问题描述】:

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

编辑:我的问题的原因,“最令人头疼的解析”,解决方案描述得很好:见this question and answer,整个标签,甚至@987654323 @。不过,在提问之前我无法确定问题所在,并且会留下这个问题,因为它可能对其他人有帮助。

我做了什么:

在一个头文件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
$ 

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

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()...

【问题讨论】:

  • 有时值得用 clang 编译代码,因为它提供了更好的错误消息。在这种情况下,clang 会显示警告:parentheses were disambiguated as a function declaration [-Wvexing-parse]。这解释了其他编译​​错误。
  • 编译器认为f是一个函数声明。如果您可以访问 C++11,请使用为处理此类情况而设计的统一初始化语法doer&lt;int, std::multiplies&lt;int&gt;&gt; f{std::multiplies&lt;int&gt;()};
  • @legends2k 谢谢你,看起来最有说服力,尽管至少有两种其他的写法,显然。不确定这是否应该被视为“重复”,因为另一个问题的标题对我来说并不太有用......
  • 好吧,如果不合适,您可以编辑该问题的标题。然而,大多数令人烦恼的解析出现在不同的地方、不同的上下文中,因此拥有一个通用名称也不会因为 你不知道你不知道什么而导致丢失。问题:)
  • @legends2k 不,我想我无法编辑链接的问题,它是在不同的上下文中提出的。我会保持原样,无论如何尝试重新提出问题都是一个失败的原因。

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


【解决方案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>()};

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2012-07-09
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多