如何从模板访问模板化类的静态

How to access static of templated class from template?

本文关键字:静态 访问      更新时间:2023-10-16

我正在尝试使用CRTP模式编写一个模板。我希望模板访问模板化类中的static const

我的模板在它自己的标题中是这样的:

template <class T> foo {
  static const int readValue = T::value
}

我从这样的模板继承(在另一个头文件中):

class fooImpl: foo<fooImpl> {
  static const int value = 42; 
}

然而,clang抱怨道:

在"fooImpl"中没有名为"value"的成员

我想我明白了鸡和蛋的问题。模板不知道fooImpl的定义,因此在实例化时无法知道它具有成员value

但是我该如何解决它呢?有没有一种方法可以将const值在编译时传播到实例化的模板中?

foo<fooImpl>基类在基类列表中实例化,但此时fooImpl是不完整类型,并且foo::value尚未声明。

您可以稍后移动静态成员的定义:

template <class T> struct foo {
  static const int readValue;
};
class fooImpl: foo<fooImpl> {
  static const int value = 42; 
};
template<class T> const int foo<T>::readValue = T::value;

但是,这不允许您在foo的主体中使用readValue作为编译时间常数。