如何从模板访问模板化类的静态
How to access static of templated class from template?
我正在尝试使用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
作为编译时间常数。
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 如何从静态向量访问类元素?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 如何在复杂继承中访问静态成员变量
- 如何在类内部使用和访问静态指针到成员值s_ptm?
- 类无法访问自己的私有静态 constexpr 方法 - Clang bug?
- decltype:使用指针访问类的静态成员
- 从 exe 和 dll 访问静态库中的 extern 变量
- 线程时访问静态映射时出现隔离错误
- C++访问静态 constexpr 数组
- 将静态字符数组中的字符分配给动态分配的字符数组 - 访问冲突
- 访问从 CPP 文件到其他头文件的静态变量
- 为什么类成员数据必须是静态的才能被模板化类的模板化结构成员访问
- 是否通过单元化指针UB访问静态类成员
- 访问模板化类的非模板基的静态数据
- Windows C++静态库在初始化期间无法访问外部方法
- C++无法访问或使用静态函数
- 使用静态 std::vector 类成员时出现访问冲突
- 可以静态访问全局静态变量的静态函数