3

私は vc++ で動作する以下のような C++ クラスを持っていますが、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() {
}
4

2 に答える 2

9

基本クラス名で次のように修飾する必要があります。

a::template_class_method();

に存在するため、資格a::が必要です。C ++の規則では、ベースがクラステンプレートまたはテンプレート引数である場合、そのすべてのメンバーが派生クラスに自動的に表示されるわけではありません。コンパイラーがメンバーを見つけるのを助けるために、基本クラスでメンバーを探すようにコンパイラーに指示する必要があります。そのためには、またはの形式のメンバーを修飾する必要があります。template_class_methodabase::member_function()base::member_data

あなたの場合、ベースはa、であり、メンバーはtemplate_class_methodであるため、次のように記述する必要があります。

a::template_class_method();

このような基本クラスは、テンプレート引数に依存するため、依存基本クラスと呼ばれることに注意してください。

于 2012-12-20T07:53:46.663 に答える
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();
      }
    };
    

template_class_method最初の方法は(仮想の場合)の仮想性を抑制するため、注意して使用する必要があります。このため、 の自然な動作が保持されるため、方法番号 2 が推奨されtemplate_class_methodます。

this->template_class_method()「うまくいかない」というあなたのコメントは不明確です。問題なく動作します。さらに、上で述べたように、これは通常、修飾名を使用するよりも優れたオプションです。

于 2012-12-20T08:43:46.300 に答える