首页 > 解决方案 > 为什么将`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 以来,第二个答案中提出了另一个问题,并已在此问题链接中解决

标签: c++visual-c++

解决方案


它失败了,因为它是cosmsvc 中的重载函数。这意味着至少有 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");   
}

推荐阅读