skypjack skypjack - 28 days ago 7
C++ Question

decltype(auto), trailing return type and sfinae: can we mix them?

Consider the following code:

auto f() -> decltype(auto) { /* do whatever you want here */ }
int main() { f(); }


The return type is deduced and
decltype(auto)
is used as trailing return type.

The code below is a slightly modified (actually, sfinae'd) version:

struct S { static void f() {} };
struct T {};

template<typename U>
auto f(int) -> decltype(U::f(), void()) {
// do whatever you want here
}

template<typename>
auto f(char) -> decltype(auto) {
// do whatever you want here
}

int main() {
f<S>(0);
f<T>(0);
}


If you take in exam this function:

template<typename U>
auto f(int) -> decltype(U::f(), void()) {
// do whatever you want here
}


The question is: is it possible to use the trailing return type to do sfinae and still have the return type deduced?

I mean something like the code below (that doesn't work, of course):

template<typename U>
auto f(int) -> decltype(U::f(), auto) {
// do whatever you want here
}





Note: I'm not looking for alternative approaches involving template parameters, I know them and I'm just curious to know if this is a viable solution.

Answer

decltype(auto) is an inseparable construct (almost as if it were a keyword like decltype_auto). Other than that, auto cannot be used as a standalone entity inside decltype(x), because that would prevent x from being a valid expression.

Comments