I'm learning SFINAE and this is my first attempt to print "YES" only for those types you can output with std::ostream
(forget about std::operator<<(std::ostream &, T)
for now...):
template <typename T>
void f(const T &) { std::cout << "NO" << std::endl; }
template <typename T, int SFINAE = sizeof(static_cast<std::ostream &(std::ostream::*)(T)>(
&std::ostream::operator<<))>
void f(const T &) { std::cout << "YES" << std::endl; }
Though they seem to work with f(std::vector<int>())
(yielding "NO,") the compiler complains f(0)
is ambiguous: http://ideone.com/VljXFh
prog.cpp:16:5: error: call of overloaded 'f(int)' is ambiguous
f(0);
^
prog.cpp:6:6: note: candidate: void f(const T&) [with T = int]
void f(const T &) { std::cout << "NO" << std::endl; }
^
prog.cpp:10:6: note: candidate: void f(const T&) [with T = int; int SFINAE = 8]
void f(const T &) { std::cout << "YES" << std::endl; }
^
How can I fix my code? Is the "YES" version not more specific than the "NO" version which is completely generic?
Clarification
All of f(0)
, f(0.)
and f(true)
fail with the same "ambiguous" error. I'm looking for a solution that is applicable to all types accepted by std::ostream::operator<<
. Ideally it shouldn't rely on defining a helper type that "taints" the namespace.
struct overload_priority_high : overload_priority_low {};
which is more readable thanint
vschar
orlong
. – Windsail