In C++11, it is easy to SFINAE on whether or not an expression is valid. As an example, imagine checking if something is streamable:
template <typename T>
auto print_if_possible(std::ostream& os, const T& x)
-> decltype(os << x, void());
print_if_possible
will only participate in overload resolution if os << x
is a well-formed expression.
I need to do the same in C++03, and I figured out that sizeof
could help (as I needed an unevaluated context for an expression). This is what I came up with:
template <int> struct sfinaer { };
template <typename T>
void print_if_possible(std::ostream& os, const T& x,
sfinaer<sizeof(os << x)>* = NULL);
It seems that both the latest versions of g++ and clang++ accept the sizeof
version with -std=c++03 -Wall -Wextra
.
Is the code guaranteed to work as intended in C++03?
Is it correct to conclude that any usage of C++11 expression SFINAE can be backported to C++03 using
sfinaer
andsizeof
?
, 0
insidesizeof
? Do you need it in this particular example? – Floriesfinaer
is a nice name. – Botticelli, 0
insizeof
. – Florie<expression>.operator,(0)
is invalid. – Strapping