[英]How to std::enable_if only if a certain template has a specialization for a given class
我有以下模板:
namespace std {
template<typename Enum>
typename std::enable_if<std::is_enum<Enum>::value, std::ostream&>::type
operator<<(std::ostream& strm, Enum e)
{
return strm << helper_of<Enum>::to_string(e);
}
}
在比较霍比特人时,这有助于Google测试显示人类可读的诊断信息:
template <typename T> struct enumclass {}; // generic template
template <typename T>
using helper_of = typename enumclass<T>::helper; // more mnemonic
namespace MiddleEarth {
enum class Hobbit { Bilbo, Frodo, Sam };
struct HobbitHelper{
std::string to_string(Hobbit H);
Hobbit from_string(std::string const& s); // Hobbit-forming
};
template <> struct enumclass<Hobbit> {
using helper = HobbitHelper; // links Hobbit to its helper
}
}
enable_if
可以防止将此模板化的operator<<
应用于任何旧类(没有enable_if的朴素版本对于已经具有流运算符的类是不明确的,例如std::string
)。
但是,如果存在一个不专门枚举enumclass
的枚举,
enum class Wizard { Gandalf, Radagast, Saruman };
const Wizard g = Wizard::Gandalf, s = Wizard::Saruman;
那么以下内容无法编译
EXPECT_EQ(g, s);
error: no type named 'helper' in 'aws::enumclass<Wizard>'
因为编译器尝试将模板化的operator<<
应用于向导。
是否有可能构建一个enable_if
将仅适用该运营商<<如果有一个专业化enumclass<Enum>
? 然后,Google-test将回退以显示Wizard的原始字节并进行编译。
如果失败,是否可以构造一个enable_if
,它仅允许某个命名空间(例如MiddleEarth)中的类型? 如果向导不在MiddleEarth命名空间中,则可以解决此问题。 MiddleEarth中的所有枚举都应该具有枚举类的enumclass
。
您可以仅将helper_of
替换项移动到模板规范本身中:
template <typename Enum,
typename Helper = helper_of<Enum>>
std::ostream& operator<<(std::ostream& strm, Enum e)
{
return strm << Helper::to_string(e);
}
这样,如果helper_of
替换失败(即enumclass
不适用于给定的Enum
),则整个重载将由于SFINAE而抛出,而不是硬编译错误-因为现在我们处于即时上下文中替代本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.