我想用不同类型的T
调用pushArg()
方法。
下面是相关的代码片段:
//test.hpp
struct Demo {int a};
typedef int (*CALL_CFunction)(struct Demo* );
classs Ctx
{
/*push bool */
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr,
typename std::enable_if<std::is_same<T, bool>::value>::type* = nullptr>
int pushArg(T& val)
{
std::std << "push bool" <<std::endl;
return 0;
}
/*push lua_CFunction*/
template <typename T,
typename std::enable_if<std::is_pointer<T>::value>::type* = nullptr,
typename std::enable_if<std::is_same<CALL_CFunction, T>::value>::type* = nullptr>
int pushArg(T& val)
{
std::cout << "push function" << std::endl;
return 0;
}
}
调用pushArg()
的函数
int foo(Struct Demo *) {return 0;}
Ctx ctx;
ctx.pushArg(foo);
以下是错误消息:
test.cpp:36:22: error: no matching function for call to ‘ctx::pushArg(int (&)(lua_State*))’
pCtx->pushArg(foo);
^
In file included from test.cpp:1:0:
test.hpp:131:9: note: candidate: template<class T, typename std::enable_if<std::is_integral<_Tp>::value>::type* <anonymous>, typename std::enable_if<std::is_same<T, bool>::value>::type* <anonymous> > int ctx::pushLuaArg(T&)
int pushLuaArg(T& val)
^
test.hpp:131:9: note: template argument deduction/substitution failed:
test.hpp:129:76: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr,
^
发布于 2020-12-15 10:57:07
pushArg
的参数val
被声明为按引用传递,然后给定ctx.pushArg(foo);
,函数到指针的衰减不会发生,而T
被推导为函数类型,即int (Demo*)
。对于第二个过载,std::is_pointer<T>::value
和std::is_same<CALL_CFunction, T>::value
都会产生false
。
对于std::is_pointer
,您可以使用std::is_function
,但它似乎是多余的。仅仅是std::is_same
就足够了。(如果std::is_same<CALL_CFunction, T*>::value
提供true
,那么std::is_function<T>::value
也将是true
。)例如。
template <typename T,
typename std::enable_if<std::is_same<CALL_CFunction, T*>::value>::type* = nullptr>
// ^
int pushArg(T& val)
https://stackoverflow.com/questions/65299314
复制相似问题