Skip to main content
 首页 » 编程设计

c++之我可以将enable_if替换为decltype吗

2024年06月03日36bonelee

understanding decltype with 2 arguments之后我想知道,我可以用它来代替 enable_if ?例如:

template <typename T> 
decltype(T(), declval<bool>()) isConstructable() { return true; } 

成功,isConstructable<int>并失败 isConstructable<istream>在 Visual Studio 2015 上:http://rextester.com/YQI94257但在 gcc I have to do :

template <typename T> 
enable_if_t<decltype(T(), true_type())::value, bool> isConstructable() { return true; } 

应该decltype版本有效,还是我只是在利用非标准的 Microsoftianisim?

请您参考如下方法:

std::declval<bool>()的类型是 bool&& ,不是bool 。这就是警告的来源 - true需要通过引用返回。

像这样的东西应该在没有警告的情况下编译:

bool ok() { return true; } 
 
template <typename T> 
decltype(T(), ok()) is_constructable() { return true; } 
 
int main() { 
    cout << is_constructable<int>() << endl; 
}