【问题标题】:Difference between decltype (..., void()) and void_tdecltype (..., void()) 和 void_t 之间的区别
【发布时间】:2016-03-14 11:55:29
【问题描述】:

上次我找到了很多关于 SFINAE 的答案,建议使用 void_t 助手。

但我似乎不明白它有什么特别之处:

decltype (..., void()).

考虑这个例子:

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

这两个特征的输出都符合预期,这让我认为这两个实现是相同的。我错过了什么吗?

【问题讨论】:

    标签: c++ sfinae


    【解决方案1】:

    这是一种表达能力更强、更简洁的表达方式。

    就是这样。

    【讨论】:

    • 我看到的唯一区别是使用 void_t,在使用 decltype + 逗号运算符技巧的地方,他总是得到 void,你可以得到任何你想要的类型——在你的例子中,你只是选择了 void。否则它是一样的。
    • @TareqA.Siraj:是的。
    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 2011-02-10
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多