我有一个模板类 A
,我会知道 T
取决于调用它的类。
例如,有 10 个类将使用类 A,这 10 个类中的一个名为 file1
。
我可以编写类 file1
中所示的代码吗?
class D;
template<typename T>
class A
{
protected:
int a;
int b;
static T *ptr;
public:
static void set_a(int aa){ a = aa; }
static D *create()
{ return new T(); }
};
我可以做类似下面的事情吗
class file1
{
#define T file1
A<T>
#undef
.....other data member vs member function
}
class file2
{
#define T file2
A<T>
#undef
.....other data member vs member function
}
原始代码如下:
anotherMacro1 在哪里
#define anotherMacro1(method)\
public:\
static return_type functionname(passingtype *ptr1, passingtype *ptr2)\
{\
return ((T *)ptr1)->method(ptr2);\
}
============================================= =======================
A也是一个宏
喜欢
#define A \
protected:\
int a;\
int b;\
static T *ptr;\
public:\
static void set_a(int aa){ a = aa; }\
static D *create()\
{ return new T(); }
============================================= ===============================
class file1_orginal
{
#define T file1_orginal
A()
anotherMacro1(passingValue);
anotherMacro2(passingValue);
#endif
.....other data member vs member function
}
首先我想去掉A中的宏,所以我用类A来替换宏A。
最佳答案
严格来说,是的,您可以这样做。实际上,我不确定我是否在以下方面看到了任何值(value):
#define T file1
A<T>
#undef T
对比:
A<file1>
但是,您确实降低了整个内容的可读性。重点是什么?这似乎是寻找问题的解决方案。我无法想象这是解决方案的问题。
好的,鉴于您的示例宏,我建议逐步重构模板。在宏中使用“ protected ”可见性是有问题的,但我们会保留它。我将从这个开始:
template<class CRTP> //Curiously Recurring Template Pattern
class A {
protected:
int a;
int b;
static CRTP *ptr;
public:
void set_a(int aa){ a = aa; }
static D *create() { return new CRTP(); } //D is a base class?
};
然后:
class file1 : public A<file1> {
#define T file1
anotherMacro1(passingValue);
anotherMacro2(passingValue);
#undef T
...
};
这使用了 curiously recurring template pattern从 A 中嵌入成员。我从来没有在基类中用 protected 成员尝试过这个,但我似乎记得 protected 成员是继承的,并作为 protected 成员继承以供将来继承。无论如何,我会考虑对这些 protected 成员的需求设计不佳,并将它们重构为访问函数,但我认为这可以满足您的需求。稍后您可以重构 anotherMacro1 和 anotherMacro2 的内容。
关于c++ - 我可以在宏中编写模板类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21099524/