使用函数指针的类型作为模板参数
问题描述:
我正在尝试编写一个模板,它将函数指针的类型作为templateargument和相应的函数指针作为函数参数获取,因此作为一个简单的示例,我正在执行此操作:使用函数指针的类型作为模板参数
int myfunc(int a)
{ return a; }
template<typename T, typename Func> struct Test
{
typedef typeof(myfunc) Fun;
static T MyFunc(T val, Func f)
{
return f(val);
}
};
int main(void)
{
std::cout<<Test<int, typeof(myfunc)>::MyFunc(5, myfunc)<<std::endl;
}
但是,这段代码立即崩溃。如果我将f的类型更改为Fun
,它可以很好地工作。 那么我做错了什么,我该如何得到这个工作?
我在windows vista下使用mingw,如果行为是编译器依赖的情况。
答
你并不真的需要Test
类这种情况下,为什么要和这里使用typeof
功能?
template< typename T, typename fT >
T TestMyFunc(T t, fT f) {
return f(t);
};
就行了,用函数指针的类型没有摆弄:
std::cout << TestMyFunc(5,myfunc) << std::endl;
模板参数是为函数自动推导!
答
typeof
是无效的C++,但如果我用这些涉及他们的两行,那么你的代码工作正常或者Fun
或Func
在MyFunc
定义。
typedef int (*Fun)(int);
和
std::cout<<Test<int, int(*)(int)>::MyFunc(5, myfunc)<<std::endl;
+0
我也怀疑'typeof'函数... – xtofl 2009-12-19 20:51:08
typeof不是C++的一部分,所以甚至没有在我的编译器上编译 – 2009-12-19 20:42:32
在这里完美编译和运行。 – 2009-12-19 20:44:21
'typeof'是GCC的扩展。我假设它在MSVC上不可用。 – ZoogieZork 2009-12-19 20:54:55