说我有一个X1
类,该类派生自Y
和另一个类X2
。 Y
和X2
具有特定的特征Z_trait
。
现在,我有一个模板函数,我想检查参数是否具有特定的特征。
这就是我所拥有的:
#include<type_traits>
template <typename T>
struct Y {};
struct X1 : Y<int> {};
struct X2 {};
struct Z_trait {};
template <typename Container>
struct has_trait;
template <>
struct has_trait<X2>
{
typedef Z_trait type;
};
template <typename T>
struct has_trait<Y<T>>
{
typedef Z_trait type;
};
template <typename Container>
void fn(Container& container)
{
static_assert(std::is_same<typename has_trait<Container>::type, Z_trait>::value
, "must have Z_trait");
Container* x = &container;
++x;
}
int main()
{
X1 x1;
X2 x2;
Y<char> y;
fn(x1);
fn(x2);
fn(y);
return 0;
}
演示
我想要它,以便
has_trait
将提供所有三种类型的Z_trait
。我该怎么做?是否有一种遍历所有基类的方法,还是有一些更简单的方法来测试特征?注意,我没有使用using模板。原因是VS2013不完全支持此功能。
哦,仅供引用,我不想更改
X1
,X2
或Y
的实现。 最佳答案
您还想将has_trait<>
专门用于后代,而不仅仅是基础:
#include<type_traits>
struct Y {};
struct X1 : Y {};
struct X2 {};
struct Z_trait {};
template <typename Container, typename = void>
struct has_trait;
template <typename T>
struct has_trait<T, typename std::enable_if< std::is_base_of<X2, T>::value >::type >
{
typedef Z_trait type;
};
template <typename T>
struct has_trait<T, typename std::enable_if< std::is_base_of<Y, T>::value >::type >
{
typedef Z_trait type;
};
template <typename Container>
void fn(Container& container)
{
static_assert(std::is_same<typename has_trait<Container>::type, Z_trait>::value
, "must have Z_trait");
Container* x = &container;
++x;
}
int main()
{
X1 x1;
X2 x2;
Y y;
fn(x1);
fn(x2);
fn(y);
return 0;
}
另外,您可能考虑使用
static constexpr const bool has_z_trait = true;
或static bool hasTrait(const ZTrait&) { return true; }
,它使静态断言更加简单。关于c++ - 是否可以遍历某个类以查看某个类或其任何基础是否具有特定特征?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38362987/