【发布时间】:2020-02-20 05:26:24
【问题描述】:
我正在尝试编写一个调用函数,它可以采用不同模板类型的可选参数。
#include <iostream>
#include <string>
void f_int(int x){std::cout << "f_int\n";}
void f_double(double x){std::cout << "f_double\n";}
void f_void(void){std::cout << "f_void\n";}
template<typename T>
void caller(void (*fun)(T), T arg)
{
(*fun)(arg);
}
int main()
{
caller(f_int, 3);
caller(f_double, 2.1);
caller(f_void); // compilation error
caller(f_void, void); // compilation error
void* p;
caller(f_void, *p); // compilation error
}
在编写这段代码时,我希望T 可以是void 类型。是真的吗?如果是,为什么上面的代码不起作用? void 是有效类型还是只有 void* 是有效类型?
【问题讨论】:
-
f_void有零个函数参数,*fun给定void (*fun)(T)有一个函数参数,所以它们永远不会匹配。将(void)作为函数参数列表的意思与()相同只是支持C 习惯的一个特例,不适用于后来确定为void的模板依赖类型。
标签: c++ function compiler-errors void