下面是我要编译的代码:
F.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 );
}
};然后我实例化它:
#include <limits>
#include "foo.h"
int main() {
STree<long long> t;
}这编译得很好,但是当它试图链接时,我得到了对STree<long long int>::sentinel1的一个未定义的引用。我怎么解决这个问题?
发布于 2013-12-04 07:09:25
静态成员必须在转换单元中初始化。当您实例化模板时,编译器将生成声明它的代码。我还没有机会使用constexpr,但我敢打赌,您不能在模板类定义中分配给静态成员,因为您必须包括类之外的静态初始化。我打赌以下几点会奏效:
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();https://stackoverflow.com/questions/20368268
复制相似问题