Given:
class Hokey
{
public:
explicit C(int i): i_(i) { }
template<typename T>
T& render(T& t) { t = static_cast<T>(i_); return t; }
private:
unsigned i_;
};
If I try:
Hokey h(1);
string s;
h.render(s);
Codepad gives me an error on the static cast:
t.cpp: In member function 'T& Hokey::render(T&) [with T = std::string]':
t.cpp:21: instantiated from here
Line 11: error: no matching function for call to 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(unsigned int&)'
It seems like it should say that there is no Hokey::render to match.
Of course, if I supply a valid overload, everything works.
But given the code below, you uncomment the line, codepad chokes again:
string& render(string& s) const {
ostringstream out;
out << i_;
// s = out.str();
return s;
}
Doesn’t SFINAE say that – in the first case – the problem within render should not be the error, rather the absence of a render that works should be the error?
It’s only not an error during overload resolution. In other words, it puts off giving you an error until it’s sure the call definitely isn’t going to work. After that, it’s an error.
It should also be noted that overload resolution (and therefore SFINAE) only looks at the function signature, not the definition. So this will always fail:
There are no errors for either template substitution — for the function signatures — so both functions are okay to call, even though we know the first one will fail and the second won’t. So this gives you an ambiguous function call error.
You can explicitly enable or disable functions with
boost::enable_if(orstd::enable_ifin C++0x, equivalent toboost::enable_if_c). For example, you might fix the previous example with: