模板化结构继承自另一个模板化结构

时间:2014-12-05 05:00:30

标签: c++ templates c++03

我希望我的模板派生类der继承自foo。 这只是一个测试代码,我想知道我是否采取了正确的方法 der类本身是模板化的,我想要做的是在初始化列表类中传递其基类foo的模板类型。我使用以下代码

template<typename t , typename u>
struct foo
{
  void foo_method(t inp , u out)
  {
        std::cout << inp + out << "\n";
  }
};


template <typename m>
struct der : public foo<t,u> //Error t was not declared in the correct scope
{
  der():foo<t,u>(int,int)//I want to specify the types for the base class in initialization list
  {

  }
};


int main()
{
   der<std::string> d;

}

现在,当我尝试运行上面的代码时,我得到了

Error t was not declared in the correct scope

有关如何解决此问题的任何建议?

2 个答案:

答案 0 :(得分:3)

我认为这就是你要找的东西:

template <typename m>
struct der : public foo<int,int>
{
  der():foo<int,int>()
  {

  }
};

答案 1 :(得分:1)

这样做你想要的吗?我无法在你的问题中说出你的要求。

转载于http://ideone.com/dBCkQb

#include <iostream>

using namespace std;

template<typename t, typename u>
struct foo{
    foo(t a, u b) : x(a),y(b)
    {

    }
    t x;
    u y;
};

template <typename m, typename t, typename u>
struct der : public foo<t,u>{
    der(m a, t b, u c) :foo<t,u>(b,c), z(a)
    {

    }
    m z;
};


int main() {
    der<int,double,float> myder(1,1.03,2.05);
    cout << myder.x << endl << myder.y << endl << myder.z << endl;
    return 0;
}