C++ 我的模板类';s ctor将可调用对象作为参数,但无法从中初始化?

C++ 我的模板类';s ctor将可调用对象作为参数,但无法从中初始化?,c++,std-function,C++,Std Function,我被要求通过仅用于二进制运算符的函数表,使用std::function实现一个桌面计算器。所以我有这个代码: #include <functional> #include <iostream> #include <string> int main() { std::map<std::string, std::function<int(int, int)>> binOp; binOp["+"] = [](int a, i

我被要求通过仅用于二进制运算符的函数表,使用
std::function
实现一个桌面计算器。所以我有这个代码:

#include <functional>
#include <iostream>
#include <string>

int main()
{
    std::map<std::string, std::function<int(int, int)>> binOp;
    binOp["+"] = [](int a, int b){return a + b;};
    binOp["*"] = [](int a, int b){return a * b;};

    binOp["-"] = [](int a, int b){return a - b;};

    binOp["/"] = [](int a, int b){return a / b;};

    binOp["%"] = [](int a, int b){return a % b;};

    for(const auto& p : binOp)
        std::cout << 9 << " " << p.first << " " << 8 << " = " << p.second(9, 8) << std::endl;

}
  • 那么为什么我不能从Lambda表达式初始化
    bstr
    ,尽管类
    BinOp
    有一个接受可调用的构造函数呢?但是分配给
    bstr
    很好:
    bstr=[](){}…
    //有效

  • 任何提示或建议,评论家都将受到高度赞赏。多谢各位


您可以在此处使用直接初始化来直接构造
BinOp

BinOp<std::string(std::string, std::string)> bstr {[](string s1, string s2){return s1 + s2;}};
BinOp bstr{[](字符串s1,字符串s2){返回s1+s2;};

原始代码无法编译的原因很可能是因为您要求编译器执行两次转换,但它无法执行。

您可以在此处使用直接初始化来直接构造
BinOp

BinOp<std::string(std::string, std::string)> bstr {[](string s1, string s2){return s1 + s2;}};
BinOp bstr{[](字符串s1,字符串s2){返回s1+s2;};

原始代码无法编译的原因很可能是因为您要求编译器执行两次转换,但它无法执行。

在显示的代码中没有接受可调用的
BinOp
构造函数。代码也不分配给
bstr
,而是分配给
bstr.fn
。你的文章与你的代码不匹配。@IgorTandetnik:对不起。我会编辑它。我应该这样做:
BinOp(函数f):fn(f){}
BinOp bstr{[](字符串s1,字符串s2){返回s1+s2;}有效。@Maestro可能是因为您要求编译器以这种方式进行两次转换,但它不会这样做。”。但我不确定。在显示的代码中没有接受可调用的
BinOp
构造函数。代码也不分配给
bstr
,而是分配给
bstr.fn
。你的文章与你的代码不匹配。@IgorTandetnik:对不起。我会编辑它。我应该这样做:
BinOp(函数f):fn(f){}
BinOp bstr{[](字符串s1,字符串s2){返回s1+s2;}有效。@Maestro可能是因为您要求编译器以这种方式进行两次转换,但它不会这样做。”。但我不确定。谢谢你,真的很有用!(关于我在
BinOp
上的尝试或建议,你没有给出一些提示)。对我来说似乎没问题。这取决于你打算用它做什么。非常感谢。我只会尝试去理解和运用我学到的任何东西。谢谢你,这真的很有用!(关于我在
BinOp
上的尝试或建议,你没有给出一些提示)。对我来说似乎没问题。这取决于你打算用它做什么。非常感谢。我只会尝试去理解和运用我学到的任何东西。