名称和派生名称类之间的串联(作为模板args)

Concatenation between name and derived name class (as template args)

本文关键字:args 派生 之间      更新时间:2023-10-16

我正在尝试避免此解决方案的问题:

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() 
{}