导致错误的构造函数中的C++类型特征

C++ Type traits in constructor causing error

本文关键字:C++ 类型 特征 构造函数 错误      更新时间:2023-10-16

可能重复:
我必须将“模板”以及“typename;关键词?

我想要一个接受单个参数的构造函数,并且只有当该参数的类型具有成员类型::t时才启用该构造函数,该成员类型必须是其他类型的子类型。我使用了类型特征,代码看起来像这样:

#include <type_traits>
struct Y{};
struct X{
    //Only allow if T has a type member T::t which is a subtype of Y
    template <typename T>
    X(T* t, std::enable_if<std::is_base_of<Y, typename T::t>::value, int>::type e = 0){}
};

然而,g++抱怨如下:

test/test.cpp:8:75: error: ‘std::enable_if<std::is_base_of<Y, typename T::t>::value, int>::type’ is not a type

我做错了什么?

您必须向std::enable_if<...>::type添加一个typename才能解决此问题。。。