我遇到了以下问题(下面的代码):
template<class T>
void printname(const T& t){std::cout<<t<<std::endl;}
template<class T>
void applyfunc(const T& t, void (*f)(const T& )){(*f)(t);}
int main(){
const int a=1;
applyfunc(a,printname);
getchar();
return 0;
}
我的问题是它使用 vc++8(VS2005) 和 GCC、CLang(在 Ubuntu 12.04 上)编译 但无法使用 vc++ 2008 express 进行编译。
这似乎是合法的代码,但我真的不明白为什么。
如果有人能解释一下,我将不胜感激。
假设它是合法的,有没有什么方法可以用仿函数做类似的事情?
最佳答案
我假设您打算将 func
用于 printname
(反之亦然)。
就其值(value)而言,我相信这段代码是合法的,而且 VS2008(还有 VS2010;我现在手边没有 VS2012)拒绝它的事实看起来像是一个编译器错误。
回复:与仿函数类似的东西 - 看看这是否适合你:
#include <iostream>
struct printname {
template<class T>
void operator()(const T& t) { std::cout<<t<<std::endl; }
};
template<class T, class F>
void applyfunc(const T& t, F f) { f(t); }
int main(){
const int a=1;
applyfunc(a, printname());
return 0;
}
关于c++ - 模板函数参数中的自动模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17684944/