问题
When deriving a class from a template base class, one is forced to use the syntax this->member
, or using Base::member
to get access to a member of the base class. The same would happen if the base class is a generic template parameter and one is sure that some members exists.
Would it be possible to write a macro that "import" all members of the base class that I know (or assume) to be existent?
Simple example:
struct A {
int x = 0;
};
struct B {
int x = 0;
int y = 1;
};
template <class T>
struct C {
int x = 0;
T z = 0;
};
template <class BaseClass>
struct Derived : BaseClass {
using BaseClass::x;
void setx1() { x = 1; }
};
template <class T>
struct Derived_from_C : C<T> {
using C<T>::x;
void setx1() { x = 1; }
};
int main()
{
Derived<A> a;
a.setx1();
Derived<B> b;
b.setx1();
Derived_from_C<double> c;
c.setx1();
return 0;
}
In defining struct Derived
I assume that the template parameter BaseClass
contains a member x
, but to use it in the member setx1
I have to manually declare a using
. The same happens for Derived_from _C
where the base class is a template class. But if the base class contains many members that I would like to use, it becomes tedious and error-prone to add a using
for each member.
It it possible to write a macro that does this semi-automatically? Something like
#define USING(class, __VA_ARGS__)
such that
USING(BaseClass, x, y, z)
expands to
using BaseClass::x;
using BaseClass::y;
using BaseClass::z;
回答1:
Based on Marvin's solution to the question Is it possible to iterate over arguments in variadic macros here is a solution
#define FE_1(CLASS, X) using CLASS::X
#define FE_2(CLASS, X, ...) using CLASS::X;FE_1(CLASS, __VA_ARGS__)
#define FE_3(CLASS, X, ...) using CLASS::X;FE_2(CLASS, __VA_ARGS__)
#define FE_4(CLASS, X, ...) using CLASS::X;FE_3(CLASS, __VA_ARGS__)
#define FE_5(CLASS, X, ...) using CLASS::X;FE_4(CLASS, __VA_ARGS__)
#define FE_6(CLASS, X, ...) using CLASS::X;FE_5(CLASS, __VA_ARGS__)
#define FE_7(CLASS, X, ...) using CLASS::X;FE_6(CLASS, __VA_ARGS__)
#define FE_8(CLASS, X, ...) using CLASS::X;FE_7(CLASS, __VA_ARGS__)
#define FE_9(CLASS, X, ...) using CLASS::X;FE_8(CLASS, __VA_ARGS__)
#define FE_10(CLASS, X, ...) using CLASS::X;FE_9(CLASS, __VA_ARGS__)
#define FE_11(CLASS, X, ...) using CLASS::X;FE_10(CLASS, __VA_ARGS__)
#define FE_12(CLASS, X, ...) using CLASS::X;FE_11(CLASS, __VA_ARGS__)
//... repeat as needed
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,NAME,...) NAME
#define FOR_EACH_USING(class,...) \
GET_MACRO(__VA_ARGS__,FE_12,FE_11,FE_10,FE_9,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1,)(class,__VA_ARGS__)
来源:https://stackoverflow.com/questions/56323134/c-macro-to-import-all-names-of-base-template-class