Decltype (auto),尾随返回type和sfinae:可以混合使用吗?

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

本文关键字:混合 sfinae auto type 返回 Decltype      更新时间:2023-10-16

考虑以下代码:

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

推导返回类型,并使用decltype(auto)作为尾返回类型。
下面的代码是稍微修改过的版本(实际上是):

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);
}

如果你参加考试,这个函数:

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

问题是:是否有可能使用尾部返回类型来执行sfinae,并且仍然推导出返回类型?
我指的是像下面这样的代码(当然,这不起作用):

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

注意:我不是在寻找涉及模板参数的替代方法,我知道它们,我只是想知道如果这个是一个可行的解决方案。

decltype(auto)是一个不可分割的结构(几乎就像decltype_auto一样是一个关键字)。除此之外,auto不能用作decltype(x)内部的独立实体,因为这会阻止x成为有效的表达式。

您可以为函数添加另一个类型为void(*)()的参数,并为其指定一个尾随返回类型的lambda作为默认参数,以便SFINAE可以通过lambda:

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

不是答案,而是使用void_t的可能解决方法。

至少和你想做的一样DRY:

template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;

struct S { static int f() { return 3; } };
struct P { static int p() { return 4; } };
struct T {};
template<typename U, void_t<decltype(U::f())>* = nullptr >
auto f(int) -> decltype(auto)
{
    // do whatever you want here
    std::cout << "f1n";
    return U::f();
}
template<typename U, void_t<decltype(U::p())>* = nullptr >
auto f(int) -> decltype(auto)
{
    // do whatever you want here
    std::cout << "f3n";
    return U::p();
}
template<typename>
auto f(char) -> decltype(auto) {
    std::cout << "f2n";
    // do whatever you want here
}
int main() {
    std::cout << f<S>(0) << 'n';
    std::cout << f<P>(0) << 'n';
    f<T>(0);
}