【发布时间】:2013-03-03 21:18:30
【问题描述】:
我已经多次使用 SFINAE 成语,并且习惯将 std::enable_if<> 放在模板参数中,而不是返回类型中。但是,我遇到了一些它不起作用的琐碎案例,我不知道为什么。首先,这是我的主要内容:
int main()
{
foo(5);
foo(3.4);
}
这是触发错误的foo 的实现:
template<typename T,
typename = typename std::enable_if<std::is_integral<T>::value>::type>
auto foo(T)
-> void
{
std::cout << "I'm an integer!\n";
}
template<typename T,
typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
auto foo(T)
-> void
{
std::cout << "I'm a floating point number!\n";
}
这里有一段据说可以正常工作的等效代码:
template<typename T>
auto foo(T)
-> typename std::enable_if<std::is_integral<T>::value>::type
{
std::cout << "I'm an integrer!\n";
}
template<typename T>
auto foo(T)
-> typename std::enable_if<std::is_floating_point<T>::value>::type
{
std::cout << "I'm a floating point number!\n";
}
我的问题是:为什么foo 的第一个实现会触发该错误,而第二个不会触发它?
main.cpp:14:6: error: redefinition of 'template<class T, class> void foo(T)' auto foo(T) ^ main.cpp:6:6: note: 'template<class T, class> void foo(T)' previously declared here auto foo(T) ^ main.cpp: In function 'int main()': main.cpp:23:12: error: no matching function for call to 'foo(double)' foo(3.4); ^ main.cpp:6:6: note: candidate: template<class T, class> void foo(T) auto foo(T) ^ main.cpp:6:6: note: template argument deduction/substitution failed: main.cpp:5:10: error: no type named 'type' in 'struct std::enable_if<false, void>' typename = typename std::enable_if<std::is_integral<T>::value>::type> ^
编辑:
【问题讨论】:
-
附加信息:与 VS 2012 年 11 月 CTP 相同。
标签: c++ templates c++11 sfinae