Is there a way to use SFINAE to determine if a template function call will end due to the types provided?

I have a template class that I use to provide a method that will use boost::lexical_cast to cast its std::string parameters to the type specified in the template, only if lexical conversion is possible. Currently, to check if this is possible, I just check if operator>> exists for the type in question. Here is a contrived example that basically illustrates what I'm doing:

 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 } }; 

So far, this works fine for my code: all types that cannot be lexically cast end with the first version, and all the rest with the second, at least for the types in which my code uses this. My concern is that I basically make the assumption that until the target type is InputStreamable, lexical_cast fails. the additional documentation for lexical_cast describes some other requirements that I probably should check, rather than create complex enable-if mpl::and_ and use mpl::and_ to combine a bunch of these conditions, I was wondering: is there a way to use SFINAE to just check , will this lexical_cast call fail for the specified types and match the custom pattern only if it does not fail?

I only ever saw examples to check for the existence of a function or operator, but I never checked if the call would result in a templated function with the given error type.

+4
source share
1 answer

I'm afraid not. Since lexical_cast is defined for all T, SFINAE will not help you. The fact that the body of lexical_cast () cannot compile for certain types does not cause a change of replacement. The best you can do is try to predict the conditions that will cause loss of body, as you already did.

+1
source

Source: https://habr.com/ru/post/1390570/


All Articles