a (somewhat) outdated article explores ways use decltype
along sfinae detect if type supports operators, such ==
or <
.
here's example code detect if class supports <
operator:
template <class t> struct supports_less_than { static auto less_than_test(const t* t) -> decltype(*t < *t, char(0)) { } static std::array<char, 2> less_than_test(...) { } static const bool value = (sizeof(less_than_test((t*)0)) == 1); }; int main() { std::cout << std::boolalpha << supports_less_than<std::string>::value << endl; }
this outputs true
, since of course std::string
supports <
operator. however, if try use class doesn't support <
operator, compiler error:
error: no match ‘operator<’ in ‘* t < * t’
so sfinae not working here. tried on gcc 4.4 , gcc 4.6, , both exhibited same behavior. so, possible use sfinae in manner detect whether type supports expressions?
you need make less_than_test function template, since sfinae stands substitution failure not error , there's no template function can fail selection in code.
template <class t> struct supports_less_than { template <class u> static auto less_than_test(const u* u) -> decltype(*u < *u, char(0)) { } static std::array<char, 2> less_than_test(...) { } static const bool value = (sizeof(less_than_test((t*)0)) == 1); }; int main() { std::cout << std::boolalpha << supports_less_than<std::string>::value << endl; }
Comments
Post a Comment