将函数存入std::vector在Linux正常,Windows VS2017编译失败求助
解决MSVC下std::vector存储sin/cos/tan的重载歧义问题
我之前也碰到过一模一样的坑!这本质是MSVC和GCC对<cmath>库中数学函数的重载处理逻辑差异导致的:
在Linux的GCC环境下,编译器会默认帮你匹配到double(double)版本的sin/cos/tan,所以直接把函数名丢进vector没问题;但Windows的MSVC里,这些函数有多个重载(比如对应float、double、long double的版本),编译器没法自动判断你要选哪一个,就会抛出无法确定重载函数的预期实例的错误。
下面给你两种简单靠谱的修改方案,都能跨平台正常运行:
方案1:显式强制类型转换
把函数名转换成明确的函数指针类型,直接告诉编译器要选哪个重载:
#include <vector> #include <cmath> #include <functional> #include <iostream> typedef std::function<double(double)> AFunc; std::vector<AFunc> funcs = { static_cast<double(*)(double)>(sin), static_cast<double(*)(double)>(cos), static_cast<double(*)(double)>(tan), [](double x) { return x*x; }, }; int main() { std::cout << funcs[0](2) << std::endl; std::cout << funcs[1](2) << std::endl; std::cout << funcs[2](2) << std::endl; std::cout << funcs[3](2) << std::endl; }
方案2:用lambda包裹函数调用
这种方式可读性更好,lambda会自动推导成符合AFunc类型的可调用对象,代码风格也和你后面的自定义lambda统一:
#include <vector> #include <cmath> #include <functional> #include <iostream> typedef std::function<double(double)> AFunc; std::vector<AFunc> funcs = { [](double x) { return sin(x); }, [](double x) { return cos(x); }, [](double x) { return tan(x); }, [](double x) { return x*x; }, }; int main() { std::cout << funcs[0](2) << std::endl; std::cout << funcs[1](2) << std::endl; std::cout << funcs[2](2) << std::endl; std::cout << funcs[3](2) << std::endl; }
两种方案都能在MSVC 2017和GCC下正常编译运行,我个人更推荐方案2,代码看起来更整洁,也避免了繁琐的类型转换。
内容的提问来源于stack exchange,提问作者lgwest
相关产品推荐
相关产品推荐

