我正在尝试构建一个带有静态数据成员的模板类,但当我尝试编译以下代码时收到此错误消息:
|In instantiation of ‘T<int>& T<int>::t’:|
16|required from here|
16|error: explicit instantiation of ‘T<int>::t’ but no definition available [-fpermissive]|
|In instantiation of ‘T<int>& T<int>::t’:|
16|required from here|
16|error: explicit instantiation of ‘T<int>::t’ but no definition available [-fpermissive]|
||=== Build finished: 2 errors, 4 warnings (0 minutes, 0 seconds) ===|
代码(经过提炼以证明问题。)
template <class A>
class T {
private:
static T& t;
public:
T& getT() {return t;}
};
T<int> i;
template T<int>& T<int>::t;
int main()
{
i.getT();
return 0;
}
恐怕我不明白“没有可用的定义”是什么意思。我认为“模板 T&T::t;”将定义静态数据成员。
我在 Linux 上使用 GCC:
hbarta@cypress:~$ c++ --version
c++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
感谢您的帮助!
编辑:将静态成员声明为引用显然是一个错误,我已经更正了。
感谢为此提供的几种解决方案和建议。我将不得不研究它们并决定哪个是最合适的。
FWIW,我打算做的是重新发明一个单链表。目标是 Arduino,资源有限,对代码和 RAM 大小很敏感。否则我会非常乐意使用 STL 容器。我正在编写一个单链表,静态数据成员将是一个哨兵,指向列表的头部。列表中的最后一个元素指向哨兵。对于第一次迭代,我开始使用继承编写此代码,但很快发现各种派生类没有通用代码。 (他们在概念上有相似之处,但并没有转化为实现,例如,他们有不同的列表和不同的处理,所以在我看来,继承是一个糟糕的初始选择。)希望这种困难并不表明模板同样不是一个好选择选择。
最佳答案
您对静态成员的定义是错误的。对于所有 T,您要么必须以模板化的方式进行:
template <class A> T<A>& T<A>::t = /* ??? */;
或者仅作为整数的特化:
template<> T<int>& T<int>::t = /* ??? */;
后者会给您留下一个问题,即使用 int 以外的任何其他类型实例化 T 都需要您定义这些实例化的静态成员。
另外,如果静态成员是一个引用,你需要有一些对象来绑定(bind)它,用???
表示。在我的片段中。使静态成员成为 T<A>
的对象而不是引用将解决这个问题。
关于c++ - 显式实例化...但没有可用的定义 [-fpermissive],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22635400/