c++ - 如何使用 enable_if<>::type 返回类型制作函数原型(prototype)?

标签 c++ templates c++11 sfinae enable-if

下面我有 3 个原型(prototype)。我希望第一个(注释掉)可以工作,但那是唯一一个 工作的(请参阅代码中的注释以了解错误)。更令我惊讶的是,即使两者都存在,以下两项中的任何一项都有效。

/////////////////////////////////////////////////
// Prototypes:
/////////////////////////////////////////////////
//  Causes "ambiguous call to overloaded function" at the call site when when one or both  
//  of the below prototypes is also present. Otherwise causes unresolves external
//template<typename T> void func(); 

//  Okay, can have this one AND/OR the below declaration
template<typename T> typename std::enable_if<std::is_integral<T>::value, void>::type func();

//  Also okay, can have this one AND/OR the above declaration
template<typename T> typename std::enable_if<std::is_integral<T>::value, void>::type func();


int main()
{
    func<int>();
}


/////////////////////////////////////////////////
// Definitions:
/////////////////////////////////////////////////
template<typename T> typename std::enable_if<std::is_integral<T>::value, void>::type func() {}

template<typename T> typename std::enable_if<!std::is_integral<T>::value, void>::type func() {}

哪个是正确的原型(prototype),为什么第一个不起作用?我正在使用 VS2010 和 VS2012

最佳答案

第一个导致错误,因为它声明了一个不同的函数模板。简而言之,它是不同的,因为所有 enable_if 都是其签名的一部分,而不仅仅是它解析为的最终类型。

您永远不会为第一个模板声明提供定义,这就是为什么如果您不将其他模板声明放入其中,您会收到“ Unresolved external ”错误。

如果你把其他人放进去,现在你有其他人之一加上这个作为候选者,两者都是可行的,而不是有序的。这就是您收到“模糊调用”错误的原因。

正确的方法是声明您定义的内容,即您现在没有注释的内容。

关于c++ - 如何使用 enable_if<>::type 返回类型制作函数原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11532681/

相关文章:

c++ - 从 long long 到 float 的隐式转换会产生意外结果

c++ - 使用模板元编程计算阶乘

c++ - Variadic 模板错误 -- MSVS2013 编译,clang-3.5 不编译

c++ - 模板别名-问题(C++之旅)

c++ - 从源构建 mongodb 时出错

c++ - 使用 QNetworkReply 如何发布文件然后从服务器接收转换后的文件?

c++ - Google测试-生成用于模板类实例化的值

c++ - 从依赖基类访问类型

c++ - 如何让 std::thread 停止?

c++ - 为什么不能将 cout 与用户定义的转换一起使用到 std::string?