dimanche 5 avril 2015

decltype(auto) in member function ignores invalid body, decltype(expr) fails

I have a simple templated wrapper struct with a member function calling .error() on an object of its template type.



template <typename T>
struct Wrapper {
T t;
decltype(auto) f() {
return t.error(); // calls .error()
}
};


If I instantiate this with a type that doesn't have an error() member function, it's fine as long as I don't call it. This is the behavior I want.



Wrapper<int> w; // no problem here
// w.error(); // uncommented causes compilation failure


If I use what I thought was the semantic equivalent with a trailing return type, it errors on the variable declaration



template <typename T>
struct Wrapper {
T t;
auto f() -> decltype(t.error()) {
return t.error();
}
};

Wrapper<int> w; // error here


I'll accept that the two are not semantically equivalent, but is there anyway to get the behavior of the former using a trailing return type (C++11 only) without specializing the whole class with some kind of HasError tmp trickery?


Aucun commentaire:

Enregistrer un commentaire