c++ - Checking whether a function (not a method) exists in c++11 via templates -
so sfinae , c++11, possible implement 2 different template functions based on whether 1 of template parameters can substituted.
for example
struct boo{ void saysomething(){ cout << "boo!" << endl; } }; template<class x> void makeitdosomething(decltype(&x::saysomething), x x){ x.saysomething(); } template<class x> void makeitsaysomething(int whatever, x x){ cout << "it can't anything!" << endl; } int main(){ makeitsaysomething(3); makeitsaysomething(boo()); }
or along line.
my question is.. how 1 same thing, non-member functions?
in particular i'm trying check if there's such thing an:
operator<<(std::ostream& os, x& whateverclass);
that exists. possible test it?
edit: question different : is possible write template check function's existence? in i'm trying see whether function exists, not method
i find void_t
trick preferable traditional sfinae method shown in other answer.
template<class...> using void_t = void; // in c++17 working paper! // gcc <= 4.9 workaround: // template<class...> struct voider { using type = void; }; // template<class... t> using void_t = typename voider<t...>::type; template<class, class = void> struct is_ostreamable : std::false_type {}; template<class t> struct is_ostreamable<t, void_t<decltype(std::declval<std::ostream&>() << std::declval<t>())>> : std::true_type {};
the partial specialization selected if , if expression well-formed.
demo. note &
in std::declval<std::ostream&>()
important, because otherwise std::declval<std::ostream>()
rvalue , you'll ostream
's catchall rvalue stream insertion operator, , report streamable.
the above code checks operator<<
can accept t
rvalue . if want check 1 accepts lvalue t
, use std::declval<t&>()
.
Comments
Post a Comment