c++ - 我的模板类的 ctor 将可调用对象作为参数,但不能从中初始化?
问题描述
我被要求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;
}
* 该程序适用于整数操作数的二元运算符。我认为使我的类模板是通用的,可以处理不同类型的操作数int, double, std::string...
所以我在以下帮助下自己尝试了这个decltype
:
template <typename T>
struct BinOp
{
BinOp() = default;
BinOp(T f) : fn(f){}
std::function<T> fn;
using arg_type = decltype(fn(0, 0));
arg_type operator()(arg_type a, arg_type b){return fn(a, b);}
};
int main()
{
std::map<std::string, BinOp<int(int, int)>> calc;
calc["+"] = BinOp<int(int, int)>([](int x, int y){return x + y;});
calc["*"] = BinOp<int(int, int)>([](int x, int y){return x * y;});
calc["-"] = BinOp<int(int, int)>([](int x, int y){return x - y;});
calc["/"] = BinOp<int(int, int)>([](int x, int y){return x / y;});
calc["%"] = BinOp<int(int, int)>([](int x, int y){return x % y;});
for(const auto& e : calc)
std::cout << 10 << " " << e.first << " " << 12 <<
" = " << e.second(10, 12) << endl;
//BinOp<std::string(std::string, std::string)> bstr = [](string s1, string s2){return s1 + s2;}; // it doesn't work?
BinOp<std::string(std::string, std::string)> bstr;
bstr.fn = [](string s1, string s2){return s1 + s2;}; // works fine!
std::cout << bstr("Hello ", "Wold!") << std::endl;
std::cout << "\nDone!\n";
}
那么为什么我不能
bstr
从 Lambda 表达式初始化,尽管类BinOp
有一个可以调用的构造函数呢?但是分配到bstr
很好:bstr = [](){}...
//有效!任何提示或建议,评论家都非常感谢。谢谢你。
解决方案
您可以在此处使用直接初始化BinOp
直接构造一个:
BinOp<std::string(std::string, std::string)> bstr {[](string s1, string s2){return s1 + s2;}};
您的原始代码无法编译的原因可能是因为您要求编译器执行两次转换,而它不会这样做。
推荐阅读
- ios - 在 IOS 中为 AI 设置相机分辨率
- javascript - 使用 javascript 将数据发送到服务器远程服务器
- excel - 如果第一个 MATCH 公式在 excel 中返回 null,如何从另一个 MATCH 公式中选择一个值
- python - Flask, Python 3.9.6: 错误 gevent.exceptions.InvalidSwitchError: Invalid switch into Event.wait(): ()
- python - 如何在pygame中停止时间等待输入?
- python - 如何使特定字符串在 try-except 块中工作?
- heroku - 你如何部署到 Heroku 上?
- r - 从R中的列中选择数据的问题
- sqlalchemy - sqlalchemy 中的 synchronize_session 是什么意思?
- laravel - 如何在为所有上层兄弟姐妹提供一定奖励的同时缩短以下代码或重构它?