【发布时间】:2016-10-25 21:53:32
【问题描述】:
我尝试将std::enable_if 与未使用且未命名的类型参数一起使用,以免扭曲return 类型。但是,以下代码无法编译。
#include <iostream>
template <typename T, typename = std::enable_if_t<!std::is_integral<T>::value>>
T foo() { std::cout << "non-integral" << std::endl; return T(); }
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
T foo() { std::cout << "integral" << std::endl; return T(); }
int main() {
foo<float>();
foo<int>();
}
编译器说:
7:3: error: redefinition of 'template<class T, class> T foo()'
4:3: note: 'template<class T, class> T foo()' previously declared here
In function 'int main()':
11:12: error: no matching function for call to 'foo()'
11:12: note: candidate is:
4:3: note: template<class T, class> T foo()
4:3: note: template argument deduction/substitution failed:
这里有什么问题?我如何更改代码才能编译? “发现现代 C++”教科书明确鼓励使用带有匿名类型参数的 std::enable_if。
编辑:我知道如果我将std::enable_if 放入返回类型中它会起作用。但是,我的目的是获取更多详细信息,如果我将它与匿名类型参数一起使用,它为什么不起作用。正如我所说,我的教科书鼓励使用匿名类型参数的变体,所以我想知道为什么我的代码无法编译。
【问题讨论】:
-
您是否尝试过将
std::enable_if放入返回类型中?
标签: c++ c++11 templates sfinae enable-if