根据模板参数可以选择静态的类成员

Class members that are optionally static depending on template parameters

本文关键字:静态 选择 成员 参数      更新时间:2023-10-16

>想象两个类,StaticFooNonStaticFoo,它们是相同的,只是类成员在StaticFoo中是静态的,但在NonStaticFoo中不是静态的。
简单的例子:

class StaticFoo {
static void bar();
static int v;
};
class NonStaticFoo {
void bar();
int v;
};

是否可以分解出模板类Foo以避免代码重复?
这样就可以使用类似的东西

using StaticFoo = Foo<true>;
using NonStaticFoo = Foo<false>;

是否可以分解出模板类 Foo 以避免代码重复?

"不">

不幸的是,static不像noexcept那样通过表达式参数化,所以你不能说static(false)这样的话。

如果不使用宏,您将被迫专用化模板,以便您可以在专用化中拥有static成员:

template<bool = false>
class Foo{
void bar();
int v;
};
template<>
class Foo<true>{
static void bar();
static int v;
};