【问题标题】:c++ metaprogram, member type test?c++元程序,成员类型测试?
【发布时间】:2021-12-17 16:15:35
【问题描述】:

我尝试编写一个模板元函数来测试“T是一个类型有一个成员类型,名为type”。

代码如下:


#include <iostream>
#include <type_traits>

template <typename T, typename E = void>
struct has_type;
// branch 1
template <typename T, typename E>
struct has_type : std::false_type {};
// branch 2
template <typename T>
struct has_type<
    T, std::enable_if_t<std::is_same_v<typename T::type, typename T::type>, T>
> : std::true_type {};


struct with_type {using type = void;};
struct without_type {};

int main()
{
    std::cout<< has_type< with_type >::value <<std::endl;
    std::cout<< has_type< without_type >::value <<std::endl;
    return 0;
}

我想,编译器会首先尝试使用分支 2,如果类型T 有成员类型type,我们得到std::true_type。 或者找不到T::type,然后SFINAE并使用分支1,我们得到std::false_type

但是两个输出都是false

有什么我理解错了吗?

【问题讨论】:

    标签: c++ templates metaprogramming


    【解决方案1】:

    分支1,即主模板,第二个模板参数默认值为void;要使分支 2,即要选择的特化,当条件满足时,第二个模板参数应该产生类型 void 而不是 T

    // branch 2
    template <typename T>
    struct has_type<
        T, std::enable_if_t<std::is_same_v<typename T::type, typename T::type>, void>
    //                                                                          ^^^^
    > : std::true_type {};
    

    或者只是

    template <typename T>
    struct has_type<
        T, std::void_t<typename T::type>
    > : std::true_type {};
    

    LIVE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      相关资源
      最近更新 更多