复杂继承中的 C++ 模板

标签 c++ templates

<分区>

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

我有一个模板类型定义如下:

template<class TCoupon>
class CatBond : public Instrument {
public:
    class arguments;
class engine;

    //actual content
}

然后我想这样做:

template<class TCoupon>
    class CatBond<TCoupon>::engine :
        public GenericEngine<CatBond<TCoupon>::arguments,
                             CatBond<TCoupon>::results> {};

GenericEngine 在我尝试使用的 QuantLib 库中定义如下:

template<class ArgumentsType, class ResultsType>
class GenericEngine : public PricingEngine,
                      public Observer {
  public:
    PricingEngine::arguments* getArguments() const { return &arguments_; }
    const PricingEngine::results* getResults() const { return &results_; }
    void reset() { results_.reset(); }
    void update() { notifyObservers(); }
  protected:
    mutable ArgumentsType arguments_;
    mutable ResultsType results_;
};

但是,这不能编译:

Warning 1   warning C4346: 'Oasis::CatBond<TCoupon>::arguments' : dependent name is not a type  c:\users\ga1009\documents\dev\oasis\catbonds\CatBond.h  213
Error   2   error C2923: 'QuantLib::GenericEngine' : 'Oasis::CatBond<TCoupon>::arguments' is not a valid template type argument for parameter 'ArgumentsType'   c:\users\ga1009\documents\dev\oasis\catbonds\CatBond.h  213

我怎样才能让它发挥作用?当 CatBond 是具体类型时,这种构造非常有效。

最佳答案

根据 Pubby 的提示,正确的实现是:

template<class TCoupon>
    class CatBond<TCoupon>::engine :
        public GenericEngine<typename CatBond<TCoupon>::arguments,
                             typename CatBond<TCoupon>::results> {};

问题是像 CatBond<TCoupon>::arguments 这样的构造默认情况下,C++ 编译器假定它们是一个变量而不是类型名,因此如果在我们的例子中我们需要使用 typename 显式声明这些是类型关键字。

关于复杂继承中的 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14630500/

相关文章:

c++ - 函数的宏参数

c++ - Quake 2 中的 Windows 消息循环实现

c++ - 推导指针非类型模板参数的类型

c++ - 是否可以使用类型特征来检查类型是否是容器?

c++ - 错误 : no matching function for call for function pointer

C++ 数据结构编程 : Passing Values by Reference?

c++ - 我可以在 "too few initializers"上导致编译错误吗?

C++成员函数模板的隐式实例化

c++ - C++ 模板中的类型名

c++ - 随机访问迭代器 : What am I missing?