【问题标题】:std::void_t and nested non type membersstd::void_t 和嵌套的非类型成员
【发布时间】:2018-08-28 21:34:37
【问题描述】:

我有以下代码,但我得到了意外的结果(第二个 static_assert 失败):

#include <type_traits>

template <typename T, typename = void>
struct is_bananas : std::false_type {};
template <typename T>
struct is_bananas<T, std::void_t<typename T::config::num_items>>
    : std::true_type {};

struct Config{
    static constexpr int num_items=42;
};

struct Bananas{
    using config = Config;
};

static_assert(is_bananas<int>::value == false);
static_assert(is_bananas<Bananas>::value == true);

当我使用 T::config 而不是 T::config::num_items 时,代码按预期工作。

如果我在num_items 周围使用decltype,那么它可以工作。

我认为void_t 仅适用于类型是否正确?

有没有更好的方法来做我想做的事?
如果有人对此感到困惑(并认为:只需抛出decltype) - 我发现decltype 很难在实际代码中阅读,因为有长名称和深层嵌套,所以如果有更好的方法来使用@987654330 @ 或我想知道的任何其他模板代码。

【问题讨论】:

  • “我认为 void_t 仅适用于类型是否正确?” - 是的

标签: c++ templates c++17 template-meta-programming sfinae


【解决方案1】:

有没有更好的方法来做我想做的事?

Nice 和 nicer 是主观的。

例如,我发现您的decltype() 解决方案非常好。

无论如何...一个可能的替代方法是定义一个可用于值类型的 std::void_t 的替代品

某事

template <auto...>
using value_void_t = void;

然后写

template <typename T>
struct is_bananas<T, value_void_t<T::config::num_items>>
   : std::true_type {};

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多