我想尝试一个简单的例子来了解如何使用std::enable_if.在我读完这个答案之后,我认为想出一个简单的例子应该不会太难.我想用来std::enable_if在两个成员函数之间进行选择,并且只允许使用其中一个成员函数.
不幸的是,下面的代码不能用gcc 4.7进行编译,经过数小时和数小时的尝试后我会问你们我的错误是什么.
#include <utility>
#include <iostream>
template< class T >
class Y {
public:
template < typename = typename std::enable_if< true >::type >
T foo() {
return 10;
}
template < typename = typename std::enable_if< false >::type >
T foo() {
return 10;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
gcc报告以下问题:
% LANG=C make CXXFLAGS="-std=c++0x" enable_if
g++ -std=c++0x enable_if.cpp -o enable_if
enable_if.cpp:12:65: error: `type' in …Run Code Online (Sandbox Code Playgroud) 有机会使用enable_if类型转换运算符吗?看起来很棘手,因为返回类型和参数列表都是隐式的.
我正在尝试operator T()使用SFINAE 重载以在T基本类型时返回副本,并在T类时使用const引用.
在double下面的示例中使用a 时,我无法std::is_class删除第二个重载(with ).
也就是说,我得到的错误是:
error: no type named ‘type’ in ‘struct std::enable_if<false, const double&>’
operator typename std::enable_if< std::is_class<T>::value, const T&>::type () const
^
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
#include <iostream>
#include <type_traits>
template<typename T>
struct Foo
{
operator typename std::enable_if<!std::is_class<T>::value, T >::type () const
{
return _val;
}
operator typename std::enable_if< std::is_class<T>::value, const T&>::type () const
{
return _val;
}
T _val;
};
int main()
{
Foo<double> f1;
f1._val = 0.3; …Run Code Online (Sandbox Code Playgroud) 我有一个类,它包装一个枚举并为其提供字符串转换。现在我引入了模板参数 \'fastStringConvert\',它控制如何使用 SFINAE 进行转换(可在此处找到:how can I use std::enable_if in a conversion operator?)。代码在 MSVC 下编译,但在 GCC 和 Clang 下失败。
\n\nerror: no type named \xe2\x80\x98type\xe2\x80\x99 in \xe2\x80\x98struct std::enable_if<false, void>\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n\n可能是什么问题以及我应该如何更改代码?
\n\n下面或此处代码的相关部分:http://rextester.com/SYC74124
\n\n#include <map>\n#include <string>\n#include <type_traits>\n\ntemplate <\n class SubClass, \n typename EnumType, \n bool fastStringConvert = true\n>\nclass SmartEnum\n{\npublic:\n template <\n typename SFINAEPostponer = EnumType,\n typename = typename std::enable_if<fastStringConvert, void>::type\n >\n explicit operator const std::string&() const \n {\n auto name = SubClass::names().find((int)value);\n if (name != SubClass::names().end())\n {\n …Run Code Online (Sandbox Code Playgroud)