简体   繁体   English

std :: void_t和嵌套的非类型成员

[英]std::void_t and nested non type members

I have the following code where I get unexpected result (second static_assert fails): 我在以下代码中得到了意外的结果(第二个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);

When I use T::config instead of T::config::num_items code works as expected. 当我使用T::config而不是T::config::num_items代码将按预期工作。

If I use decltype around num_items then it works. 如果我在num_items周围使用decltype ,那么它将起作用。

Am I correct to assume that void_t only works with types? 我是否可以正确地假设void_t仅适用于类型?

Is there a nicer way to do what I want? 有没有更好的方法来做我想要的?
If somebody is confused by this(and think: just throw a decltype ) - I find decltype hard to read in real code when there are long names and deep nesting so if there is a nicer way to do this with void_t or any other template code I would like to know. 如果有人对此感到困惑(并认为:仅仅抛出一个decltype )-我发现在长名称和深层嵌套的情况下,很难在真实代码中读取decltype ,因此,如果有更好的方法可以使用void_t或任何其他模板代码来执行此操作我想知道。

Is there a nicer way to do what I want? 有没有更好的方法来做我想要的?

Nice and nicer are subjective. 好和好是主观的。

By example, I find very nice your decltype() solution. 通过示例,我发现您的decltype()解决方案非常好。

Anyway... a possible alternative is define a substitute for std::void_t that works with value types 无论如何...一个可能的替代方法是定义可与值类型一起使用的std::void_t的替代品

Something as

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

and write 和写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM