我有一个模板类,我使用它来提供一个方法,该方法将用于boost::lexical_cast
将其std::string
参数转换为模板中指定的类型,前提是可以进行词法转换。目前要检查是否有可能,我只是检查是否operator>>
为所讨论的类型定义了。这是一个人为的例子,基本上说明了我在做什么:
template <typename ArgType, class Enable = void>
MyHelperClass
{
void Foo (ArgType arg&, std::string strArg) { } // not castable; do nothing
};
template <typename ArgType>
MyHelperClass<ArgType, boost::enable_if<boost::has_right_shift<std::istream, ArgType> >::type>
{
void Foo (ArgType arg&, std::string strArg) {
arg = boost::lexical_cast<ArgType>(strArg); // cast string arg to ArgType
}
};
到目前为止,这适用于我的代码:所有无法通过词法转换的类型都以第一个版本结束,所有其他类型以第二个版本结束,至少对于我的代码使用它的类型。我担心的是,我基本上是在假设只要目标类型是 InputStreamable ,那么 lexical_cast 就不会失败。lexical_cast的boost 文档概述了一些其他要求,我可能也应该检查这些要求,而不是创建一个复杂的enable-if
并用来mpl::and_
将这些条件串在一起,我想知道:有没有办法使用 SFINAE 直接测试对于给定的类型,该调用是否lexical_cast
会失败,并且仅当它不会失败时才匹配专用模板?
我只见过测试函数或运算符是否存在的示例,但从未测试过调用具有给定类型的模板化函数是否会产生错误。