【问题标题】:How do you initialize a static templated container?如何初始化静态模板化容器?
【发布时间】:2011-04-21 11:17:34
【问题描述】:

我正在尝试找出初始化其模板值为私有内部类的静态容器变量的正确方法。这是一个玩具示例

#include <vector>

using namespace std;

template <class myType>
class Foo {
private:
    class Bar {
        int x;
    };

    static vector<Bar*> bars;
};

template <class myType>
vector<Bar*> Foo<myType>::bars; // error C2065: 'Bar' : undeclared identifier

我也试过

...

template <class myType>
vector<Foo<myType>::Bar*> Foo<myType>::bars; // error C2059: syntax error : '>'

如果class Barclass Foo 之外声明,它会起作用,但从设计的角度来看,这是一个丑陋的解决方案。有什么建议吗?

仅供参考,所有内容都在 .h 文件中声明。

【问题讨论】:

    标签: c++ templates class static nested


    【解决方案1】:

    试试这个:

    template <class myType>
    vector<typename Foo<myType>::Bar*> Foo<myType>::bars;
    

    【讨论】:

    • 比我快 4 秒! :+1来自我。
    • 我总是被大比分击败。 :(
    • 是的,也打败了我。规则是,在 A::B 之前使用关键字 typename,只要它应该是一个类型并且表达式 A 涉及模板参数。
    • 它有效。谢谢!你们真棒。现在谷歌typename :-)
    • 如果有人想很好地解释为什么 C++ 在 aschepler 描述的情况下需要 typename,请参阅此站点 pages.cs.wisc.edu/~driscoll/typename.html
    【解决方案2】:

    vector&lt;Foo::Bar*&gt; Foo&lt;myType&gt;::bars; ...注意Foo::

    【讨论】:

    • @dgnorton:你试过编译它吗?它在gcc 上失败。 Foo 需要使用类型参数等进行限定。
    • @Richard,在 VS 2008 上是(没有警告)...在我在 gcc 上编译的路上
    • @Richard,我不担心代表。我会把我的错误答案留在这里,以供其他人的教育。仍在进行 gcc 测试。
    • @Richard,gcc 根本不喜欢它。只需将其投票(因为它应得的),以便其他使用 VS 2008(VC9 编译器)的人可能受益。
    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2016-03-10
    • 1970-01-01
    相关资源
    最近更新 更多