[英]C++: Trying to create a const static member in template
Here is the code I am trying to get to compile: 这是我想要编译的代码:
foo.h: foo.h中:
#include <limits>
template <typename T> class STreeNode {
public:
T key;
STreeNode<T>* child[2];
STreeNode( const T& k ) :
key(k), child{ nullptr, nullptr } {};
};
template <typename T>
class STree {
STreeNode<T> *root;
static constexpr T sentinel1 = std::numeric_limits<T>::min();
static constexpr T sentinel2 = std::numeric_limits<T>::max();
public:
STree() {
root = new STreeNode<T>( sentinel1 );
}
};
And I then instantiate it with: 然后我将其实例化为:
#include <limits>
#include "foo.h"
int main() {
STree<long long> t;
}
This compiles fine, but when it attempts to link, I get an undefined reference to STree<long long int>::sentinel1
. 这编译很好,但是当它试图链接时,我得到一个未定义的引用STree<long long int>::sentinel1
。 How can I resolve this? 我该如何解决这个问题?
Static members have to be initialized in a translation unit. 静态成员必须在翻译单元中初始化。 When you instantiate the template, the compiler generates the code where it is declared. 实例化模板时,编译器会生成声明它的代码。 I haven't had a chance to use constexpr yet, but I'm betting you can't assign to a static member in the template class definition as you have to include the static initialization outside the class. 我还没有机会使用constexpr,但是我打赌你不能在模板类定义中分配静态成员,因为你必须在类之外包含静态初始化。 I'm betting the following will work: 我打赌以下内容可行:
template <typename T>
class STree {
STreeNode<T> *root;
static const T sentinel1;
static const T sentinel2;
public:
STree() {
root = new STreeNode<T>( sentinel1 );
}
};
template<typename T>
const T STree<T>::sentinel1 = std::numeric_limits<T>::min();
template<typename T>
const T STree<T>::sentinel2 = std::numeric_limits<T>::max();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.