多个级别的嵌套模板.我如何让它工作
Several levels of nested templates. How do I get this to work?
我正在做一些模板元编程,我有这样的情况,首先我有几个类,比如:-
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);
};
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- C++嵌套的 If 语句中,它无法按预期工作
- 嵌套的__try ..__除外,这是如何工作的
- 嵌套静态循环由于无法捕获 constexpr 而无法工作
- 嵌套的If-else语句可能无法正常工作
- CPP:超载的嵌套操作员无法正常工作
- c++中的文件读取:for和while嵌套循环没有按预期工作:串行
- 嵌套,用于在java中不按预期工作
- 嵌套 for 循环 (C++) 无法正常工作
- C++ 嵌套模板类的工作原理
- 嵌套结构的值初始化无法正常工作
- 嵌套名称空间是如何工作的
- 这个嵌套的for循环是如何工作的
- 如何有if, else嵌套树继续工作,通过其余的else if的....
- 嵌套类对象的工作
- c++ #include,嵌套include是如何工作的
- 多个级别的嵌套模板.我如何让它工作