gpt4 book ai didi

c++ - 多级嵌套模板。我如何让它工作?

转载 作者:行者123 更新时间:2023-11-28 06:58:22 25 4
gpt4 key购买 nike

我正在做一些模板元编程,我遇到了这样的情况,首先我有几个类:-

template <typename Q>
struct Object {
public:
Q data;
};

template <typename P>
class CircleObject : public Object<const typename P::Circle> {
};

template <typename P>
class SquareObject : public Object<const typename P::Circle> {
};

template <typename P>
class Storage {
public:
typedef CircleObject<P> MyCircle;
typedef SquareObject<P> MySquare;
};

现在,我正在尝试定义这些对象的一些特征:-

template <typename P>
struct CircleTraits<Storage<P> > {
template <typename otype>
struct IsCircle {
static const bool VALUE = false;
};
};

template <typename P>
struct CircleTraits<Storage<P> >::IsCircle<Storage<P>::MyCirlce> {
static const bool VALUE = true;
};

但是,这是不正确的(编译错误)。我尝试了一种反复试验的方法,将类型名称和模板参数放在各处,但没有对模板特化的深刻理解,我无法真正解决这个问题。有人可以帮忙吗?

我希望在以后的功能中实现的是:-

typedef Storage<RedObjects> RedStorage;

template <typename SpecializedStorage>
class Processor {
typedef CircleTraits<typename SpecializedStorage> MyCircleTraits;

template <typename ObjectType>
void foo(ObjectType& data);
};

template <typename SpecializedStorage>
template <typename ObjectType>
void foo(ObjectType& data) {
if (MyCircleTraits::template IsCircle<ObjectType>::VALUE) {
// do something about the damn circles
}
}

最佳答案

我认为你不能那样做,你可能应该使用 SFINAE 来解决这样的问题:

//C++11 version
template<typename T>
struct IsCircle
{
private:
template<typename Z>
constexpr static bool _is(typename Z::MyCirlce*) //if Z dont have `MyCirlce` then this function is removed
{
return true;
}
template<typename Z>
constexpr static bool _is(...) //fallback function
{
return false;
}
public:
static const bool VALUE = _is<T>(nullptr);
};

//C++98 version
template<typename T>
struct IsCircle
{
private:
struct a { char a; }; //size ~1
struct b { char a[8]; }; //size ~8
template<typename Z>
static b _is(typename Z::MyCirlce*);
template<typename Z>
static a _is(...);
public:
static const bool VALUE = sizeof(_is<T>(0)) == sizeof(b);
};

关于c++ - 多级嵌套模板。我如何让它工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com