我注意到在 OuterClass 上手动指定 typedef 代价太大,有时会导致令人尴尬的错误。 所以我决定在 OuterClass 上制作一个复制粘贴友好的 typedef。 这是我得到的:
#include <type_traits>
struct A{
typedef A NextOuterClass;
typedef A SelfClass;
struct B{
typedef NextOuterClass OuterClass;
typedef B NextOuterClass;
typedef B SelfClass;
struct C{
typedef NextOuterClass OuterClass;
typedef C NextOuterClass;
typedef C SelfClass;
};
};
};
#define CHECK(OWNER,TYPE)\
static_assert(\
std::is_same<OWNER::TYPE::OuterClass,OWNER>::value,\
#OWNER"::"#TYPE" - not ok"\
);
CHECK(A,B);
CHECK(A::B,C);
#undef CHECK
int main(){return 0;}
它工作得很好,但并不总是:
#include <type_traits>
struct I{
typedef I NextOuterClass;
typedef I SelfClass;
};
struct D{
typedef D NextOuterClass;
typedef D SelfClass;
struct E:public I{
typedef NextOuterClass OuterClass; // NextOuterClass == I::NextOuterClass
typedef E NextOuterClass;
typedef E SelfClass;
typedef I ParentClass;
};
};
#define CHECK(OWNER,TYPE)\
static_assert(\
std::is_same<OWNER::TYPE::OuterClass,OWNER>::value,\
#OWNER"::"#TYPE" - not ok"\
);
CHECK(D,E); // D::E - not ok
#undef CHECK
int main(){return 0;}
如果我删除“typedef I NextOuterClass;”,那么它会起作用,但这是一个错误的决定,因为类“I”也可能有子类:
#include <type_traits>
struct I{
typedef I NextOuterClass;
typedef I SelfClass;
struct G{
typedef NextOuterClass OuterClass;
typedef G NextOuterClass;
typedef G SelfClass;
};
};
struct D{
typedef D NextOuterClass;
typedef D SelfClass;
struct E:public I{
typedef NextOuterClass OuterClass; // NextOuterClass == I::NextOuterClass
typedef E NextOuterClass;
typedef E SelfClass;
typedef I ParentClass;
};
};
#define CHECK(OWNER,TYPE)\
static_assert(\
std::is_same<OWNER::TYPE::OuterClass,OWNER>::value,\
#OWNER"::"#TYPE" - not ok"\
);
CHECK(I,G);
CHECK(D,E); // D::E - not ok
#undef CHECK
int main(){return 0;}
我已经尝试利用“private”和“template”的特性,但仍然没有达到预期的行为。
在 C++11 或 C++14 中有什么可靠的方法可以找到 OuterClass?
如果这里有这样的东西就好了:
std::get_outer_class<T>::type
std::is_nested_class<T>::value
最佳答案
您的示例格式不正确:
3.3.7/1 The following rules describe the scope of names declared in classes.
- The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies, brace-or-equal-initializers of non-static data members, and default arguments in that class (including such things in nested classes).
- A name
N
used in a classS
shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.- If reordering member declarations in a class yields an alternate valid program under (1) and (2), the program is ill-formed, no diagnostic is required.
您的方法依赖于名称 NextOuterClass
在嵌套类定义的不同点引用不同的东西。这正是 (2) 所禁止的。
关于c++ - 如何在 C++11 中为 OuterClass 制作复制粘贴友好的 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20215531/