如何从基类调用方法,其中基类是模板参数

时间:2012-12-20 07:51:26

标签: c++

我有一个类似下面的c ++类,在vc ++上工作,但在linux gcc 4.7中不再工作了。我不知道如何让它再次发挥作用。

test.h

template<typename a>
class test: public a
{
public:
    void fun();
};

TEST.CPP

template<typename a>
void test<a>::fun()
{
   template_class_method(); <-- this is a public method from template_class 
}
    template class test<template_class>;

template_class.h

class template_class {
public:
    template_class();
    virtual ~template_class();
    void template_class_method();

};

template_class.cpp

#include "templateclass.h"

template_class::template_class() {
    // TODO Auto-generated constructor stub

}

template_class::~template_class() {
    // TODO Auto-generated destructor stub
}

void template_class::template_class_method() {
}

2 个答案:

答案 0 :(得分:9)

您需要使用基类名称限定它:

a::template_class_method();

资格a::是必要的,因为template_class_method中存在a。 C ++规则是,如果基类是类模板或模板参数,则其所有成员对派生类自动可见。为了帮助编译器找到成员,您需要告诉它在基类中查找成员,您需要为其定义{{1 }或base::member_function()

在您的情况下,由于基数为base::member_data,成员为a,因此您必须这样写:

template_class_method

请注意,这样的基类称为依赖基类,因为依赖于模板参数。

答案 1 :(得分:2)

我不知道为什么@Karthik T删除了答案,但答案是在正确的道路上。你有几个选择

  1. 使用限定名称a::template_class_method()

    template<typename a>
    class test : public a
    {
    public:
      void fun()
      {
        a::template_class_method();
      }
    };
    
  2. 使用类成员访问语法this->template_class_method()

    template<typename a>
    class test : public a
    {
    public:
      void fun()
      {
        this->template_class_method();
      }
    };
    
  3. 通过using-declaration

    使基类方法可见
    template<typename a>
    class test : public a
    {
    public:
      using a::template_class_method;
      void fun()
      {
        template_class_method();
      }
    };
    
  4. 请注意,第一种方法将抑制template_class_method的虚拟性(在虚拟的情况下),因此应谨慎使用。因此,方法编号2是首选,因为它保留了template_class_method的自然行为。

    您的评论指出this->template_class_method()“不起作用”尚不清楚。它没有任何问题。此外,正如我上面所说,这通常是比使用限定名称更好的选择。