C ++模板比int-> unsigned转换好吗?(C++ template better than a int->unsigned conversion?)
我有两个功能,如下所示
template<typename T> unsigned int myFunction(T myelement) { myelement->func(); return 2; } void myFunction(unsigned int myelement) { }我正在使用以下代码
myFunction(2);visual studio 2012抱怨说“int has not - > func()”。 为什么不使用unsigned int版本?
I have two functions like the following
template<typename T> unsigned int myFunction(T myelement) { myelement->func(); return 2; } void myFunction(unsigned int myelement) { }and I'm using the following code
myFunction(2);visual studio 2012 is complaining that "int hasn't ->func()". Why isn't it using the unsigned int version?
最满意答案
您误读了错误消息。 编译器不使用该函数,它实例化它以确定它是否是候选者。 您需要为不合适的类型禁用实例化:
template<typename T> typename std::enable_if<!std::is_fundamental<T>::value, unsigned int >::type myFunction( T myelement ) { // ... }实例
You are misreading the error message. The compiler doesn't use the function, it is instantiating it to figure out if it is a candidate. You need to disable the instantiation for non-suitable types:
template<typename T> typename std::enable_if<!std::is_fundamental<T>::value, unsigned int >::type myFunction( T myelement ) { // ... }Live example
更多推荐
发布评论