名称和派生名称类之间的串联(作为模板args)
Concatenation between name and derived name class (as template args)
我正在尝试避免此解决方案的问题:
static const int FOO_Test = 7;
template < typename Derived >
class Foo {
public:
static const int Type;
};
const int Foo::Type = FOO_##Derived ;
class Test : public Foo<Test> {};
正如您看到的那样
宏连接不起作用(毕竟不确定)
自C 14以来,您可以使用变量模板来执行此操作。
它遵循一个最小的工作示例:
class Test;
template<typename> static constexpr int FOO;
template<> constexpr int FOO<Test> = 7;
template <typename Derived>
struct Foo {
static const int Type;
};
template<typename Derived>
const int Foo<Derived>::Type = FOO<Derived> ;
class Test : public Foo<Test> {};
int main () {
static_assert(Test::Type == 7, "!");
}
它有助于将FOO
值与Foo
类分开。
否则,您可以进行完整的专业知识并丢弃这些变量。
例如:
class Test;
template <typename Derived>
struct Foo {
static const int Type;
};
template<>
const int Foo<Test>::Type = 7 ;
class Test : public Foo<Test> {};
int main () {
static_assert(Test::Type == 7, "!");
}
如果您可以使用C 14,请使用SkyPjack的方法。如果不能,您可以写类似:
的东西#define DEFINE_FOO_TYPE(Derived)
const int Foo<Derived>::Type = FOO_##Derived
DEFINE_FOO_TYPE(Test);
,但是如果可能的话,我会尽量避免。
一个完整的示例:
// This probably wants to go in Foo.h
template < typename Derived >
class Foo {
public:
static const int Type;
};
#define DEFINE_FOO_TYPE(Derived)
template <> const int Foo<Derived>::Type = FOO_##Derived
// This probably wants to go in Test.h
static const int FOO_Test = 7;
class Test : public Foo<Test> {};
// This needs to go in Test.cpp (or some other central place)
// Note that it must follow definition of Test.
DEFINE_FOO_TYPE(Test);
// an empty main so the whole example will compile and run.
int main()
{}
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 存储模板类型以强制转换回派生<T>
- 需要从 istream 和 ostream 派生 iostream
- 在 C++ 中用派生类型重写成员函数
- 具有多个类、派生类的C++正向声明
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 名称和派生名称类之间的串联(作为模板args)