Difference between decltype (…, void()) and void_t

2019-06-21 18:21发布

问题:

Last time I'm founding many answers regarding SFINAE which suggest using void_t helper.

But I don't seem to understand what's so special about it in regard to:

decltype (..., void()).

Consider the example:

template <typename...>
using void_t = void;

template <typename T, typename = void>
struct has_foo : std::false_type {};

template <typename T>
struct has_foo <T, decltype (T().foo(), void())> : std::true_type {};

template <typename T, typename = void>
struct has_bar : std::false_type {};

template <typename T>
struct has_bar <T, void_t <decltype (T().bar())> > : std::true_type {};

class MyClass1
{
public:
    int foo() { return 3; }
};

class MyClass2
{
public:
    double bar() { return 5.4; }
};

int main() {

    std::cout << has_foo<MyClass1>::value << std::endl;
    std::cout << has_foo<MyClass2>::value << std::endl;
    std::cout << has_bar<MyClass1>::value << std::endl;
    std::cout << has_bar<MyClass2>::value << std::endl;

    return 0;
}

The output is as expected for both traits, which makes me think that both implementations are the same. Am I missing something?

回答1:

It's a more expressive, less cumbersome way of saying the same thing.

That's it.



标签: c++ sfinae