C ++模板比int

编程入门 行业动态 更新时间:2024-10-28 15:25:39
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

更多推荐

本文发布于:2023-07-14 20:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107172.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!