![](/img/trans.png)
[英]Pointer to member function or to static function in template context
[英]Static member function pointer as template argument
使用静态成员函数指针作为模板参数时,最新的VC ++编译器(2012年11月CTP)出现此编译错误:
error C2027: use of undefined type 'wrapper<int (int,int),int A::f1(int,int)>'
但是当使用自由功能时,一切正常。 我在g ++中查找了一些类似的错误( 作为g ++的模板参数,指向静态成员函数的指针“无效” ),但在那里明确指出该参数无效。 静态函数有何不同?
我将函数强制转换为void(*)(void)
因为诸如<typename T_Ret, typename... T_Args, T_Ret(*)(T_Args...)>
构造由于其他一些相关的原因而无法编译。
struct A
{
static int f1(int a, int b)
{
return a + b;
}
};
int f2(int a, int b)
{
return a + b;
}
template <typename Sig, void(*fnc)(void)>
struct wrapper;
template <void(*fnc)(void), typename T_Ret, typename... T_Args>
struct wrapper<T_Ret (T_Args...), fnc>
{
static bool apply()
{
// get some ints here
int a = 1;
int b = 2;
typedef T_Ret (fnc_ptr*)(T_Args...);
int res = ( (fnc_ptr)fnc )(a, b);
// do smth with result
res;
return true; // or false
}
};
int main()
{
bool res;
res = wrapper<decltype(A::f1), (void(*)(void))A::f1>::apply(); // error
res = wrapper<decltype(f2), (void(*)(void))f2>::apply(); // compiles ok
return 0;
}
编辑:好的,我将问题范围缩小到decltype。 当我显式地编写类型时,一切正常:
res = wrapper<int(int, int), (void(*)(void))A::f1>::apply(); // compiles ok
编辑:看来这是一个编译器错误: http : //channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/STLCCSeries6#c634886322325940618
解决方法:
将decltype(A::f1)
更改为decltype(&A::f1)
,将其输出从int(int, int)
更改为int (__cdecl *)(int,int)
。 并改变
template <void(*fnc)(void), typename T_Ret, typename... T_Args>
struct wrapper<T_Ret (T_Args...), fnc>
至
template <void(*fnc)(void), typename T_Ret, typename... T_Args>
struct wrapper<T_Ret (*)(T_Args...), fnc>
工作代码:
struct A
{
static int f1(int a, int b)
{
return a + b;
}
};
template <typename Sig, void(*fnc)(void)>
struct wrapper;
template <void(*fnc)(void), typename T_Ret, typename... T_Args>
struct wrapper<T_Ret (*)(T_Args...), fnc>
{
static bool apply()
{
// get some ints here
int a = 1;
int b = 2;
typedef T_Ret (*fnc_ptr)(T_Args...);
int res = ( (fnc_ptr)fnc )(a, b);
// do smth with result
res;
return true; // or false
}
};
int main()
{
bool res;
res = wrapper<decltype(&A::f1), (void(*)(void))A::f1>::apply();
return 0;
}
你可以尝试像这样 :
#include <iostream>
using namespace std;
struct A
{
static int f1(int a, int b)
{
return a + b;
}
};
int f2(int a, int b)
{
return a + b;
}
template <typename T, T X>
struct wrapper
{
template <typename... Args>
static bool value(Args... blargs)
{
return X(blargs...) == 3;
}
};
int main()
{
bool res;
res = wrapper<decltype(&A::f1), &A::f1>::value(1,2);
cout << res << endl;
return 0;
}
但是说真的,这要容易得多:
#include <iostream>
using namespace std;
int main()
{
bool res;
res = A::f1(a, b) == 3;
cout << res << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.