【发布时间】:2018-04-09 06:41:00
【问题描述】:
在这段代码中:
#include <iostream>
#include <cstdlib>
#include <type_traits>
#include <ios>
using std::enable_if;
using std::is_same;
using std::boolalpha;
using std::cout;
using std::endl;
template <typename T>
struct S {
S(): t(static_cast<T>(NULL)) { }
// void type() {
// cout << boolalpha;
// cout << is_same<T,int>::value << endl;
// }
template <typename enable_if<is_same<T,int>::value,T>::type>
void type() {
cout << boolalpha << true << endl;
}
T t;
};
int main(){
S<int> s;
s.type();
return(0);
}
我成功编译并输出了作为非模板函数实现的方法type();但是,对于使用 std::enable_if 实现为模板函数的相同方法,我收到以下编译错误:
so_main.cpp:23:11: error: no matching member function for call to 'type'
s.type();
~~^~~~
so_main.cpp:15:73: note: candidate template ignored: couldn't infer template argument ''
template<typename enable_if<is_same<T,int>::value,T>::type>void type(){cout << boolalpha << true << endl;}
^
1 error generated.
我的理解是这两种情况下实现的逻辑是相似的。
当方法是非模板时,T 的类型被证实为int。但是,当std::enable_if用于启用相同条件的模板功能(即T为int)时,代码无法编译。
【问题讨论】:
-
为什么这个问题被否决了?因为一开始的租金?否则,这是一个完全有效且措辞恰当的问题;很多人对 SFINAE 的这种特殊性有疑问。
-
@@SU3 不幸和可悲的是,本论坛某些成员的行为存在很多任意行为,正如这篇帖子的否决票所证明的那样,没有任何解释