简体   繁体   English

C ++模板比int-> unsigned转换更好?

[英]C++ template better than a int->unsigned conversion?

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()". visual studio 2012抱怨说“int has not - > func()”。 Why isn't it using the unsigned int version? 为什么不使用unsigned int版本?

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 实例

Try coding 尝试编码

myFunction(2U);

or 要么

myFunction((unsigned)2);

The literal 2 is of int (not unsigned int ) type. 文字2int (非unsigned int )类型。 And int is not a class or a type having ->func() 并且int不是具有->func()的类或类型

And perhaps specialize the template for unsigned instead of defining a myFunction(unsigned int) 也许专门unsigned 模板而不是定义myFunction(unsigned int)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM