c++ - Achieving an SFINAE-like effect in an if-else block -
i able write like
template <typename t> void foo() { // ... if (is_nice<t>::value) { bar_which_is_defined_only_for_nice_types<t>(); } }
however, when try compile (g++ 4.9.3, no optimization) complaint bar_which_is_defined_only_for_nice_types
. how can achieve desired effect without resorting 2 definitions of foo()
?
you can tag dispatch based on is_nice<t>
#include <type_traits> template<typename t> struct is_nice : std::false_type {}; template<> struct is_nice<int> : std::true_type {}; template<typename t> void do_nice_things(std::true_type) { bar_which_is_defined_only_for_nice_types<t>(); } template<typename t> void do_nice_things(std::false_type) { } template <typename t> void foo() { do_nice_things<t>(is_nice<t>{}); }
Comments
Post a Comment