c++ - 为什么将`printf`作为模板函数参数传递成功但`cos`失败(msvc 19)?
问题描述
我在链接上玩了一点在线 c++ 编译器。但是下面的代码片段在使用 msvc v19.latest 编译时失败了。
#include <iostream>
#include <cmath>
#include <cstdio>
template<class F, class...L>
void test(F f, L...args) {
std::cout<< "res = " << f(args...) << '\n';
}
int main()
{
test(cos, 0.1); #1
test(printf, "%s", "aaa"); #2
}
怎么可能2号线没问题,1号线通不过呢?
MSVC 对以下代码很满意,但这次轮到 GCC 拒绝它了。MSVC 的 iostream 文件包括 cmath 头和 GCC #undefs cos :)
#include <stdio.h>
#include <math.h>
//#include <iostream>
template<class F, class...L>
void test(F f, L...args) {
f(args...);
}
int main()
{
test(cos, 0.1);
test(printf, "%s", "aaa");
}
自 c++20 以来,第二个答案中提出了另一个问题,并已在此问题链接中解决
解决方案
它失败了,因为它是cos
msvc 中的重载函数。这意味着至少有 3 个不同的版本cos
:
float cos(float arg);
double cos(double arg);
long double cos(long double arg);
编译器无法猜测您正在尝试使用哪个,但您可以通过使用static_cast
如下方式帮助它:
int main()
{
test(static_cast<double(*)(double)>(cos), 0.1);
test(printf, "%s", "aaa");
}
推荐阅读
- python - Python 的 gc 在没有显式调用 gc.disable() 的情况下被禁用
- python - 根据上一个日期将“NaT”替换为下一个日期
- pycharm - PyCharm测试右键运行:builtins.tuple AttributeError 对象没有属性
- sql - 如何将 WHERE 子句应用于 RECORD REPEATED
- node.js - 使正则表达式出现的数组不起作用
- c# - 如何让 WinForms RichTextBox 正确绘制线条而不必突出显示它们?
- sqlite - SQLite3; 如何处理事务提交或回滚中的失败?
- swift - SwiftUI 导航栏颜色
- python - 查找第一个非空和非空字符串值
- python - mpi4py - 获取 2 CPU 服务器上的处理器编号