【问题标题】:Templated structure inheriting from another Templated Structure从另一个模板结构继承的模板结构
【发布时间】:2014-12-05 05:00:30
【问题描述】:

我希望我的模板派生类 der 从 foo 继承。 这只是一个测试代码,我想看看我是否在这里采取了正确的方法 der 类本身是模板化的,我要做的是在初始化列表 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

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

【问题讨论】:

  • 如果你不提供模板参数,编译器应该如何知道你想从foo&lt;&gt;继承什么?
  • 你的问题没有多大意义。 foo 没有两个参数的构造函数,那么您要传递给它什么? tu 应该是什么?

标签: c++ templates c++03


【解决方案1】:

我想这就是你要找的:

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

  }
};

【讨论】:

  • 当然,编译器生成的版本已经调用了基类default-ctor。
  • 那么我们不需要 foo() 。我想知道是否可以在初始化列表中指定它们。我很好奇
  • @MistyD:如果您的意思是在此处指定它们,那么不,但我不太确定您真正想要完成什么。
  • 另外,我如何调用基类的方法说 foo_method ? foo::foo_method();好像不行?
  • @MistyD:这取决于上下文。如果你在一个类dir的方法中,那么因为继承,你可以简单的说foo_method()
【解决方案2】:

这是你想要的吗?我真的不知道你在你的问题中要求什么。

转载于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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2013-06-02
    • 1970-01-01
    • 2021-04-06
    • 2016-07-17
    相关资源
    最近更新 更多