2012-12-20 2 views
3

저는 아래의 하나처럼 vC++에서 작동하는 C++ 클래스를 가지고 있지만, 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() { 
} 
+3

이 더 이상 작동하지 않는다는 것은 컴파일러 오류가 발생했음을 의미합니까? 그들에게 – Geoffroy

+0

나쁜 말 보여줘. 오류 - 템플릿 매개 변수에 의존하는 'template_class_method'에 대한 인수가 없으므로 'template_class_method'의 선언을 사용할 수 있어야합니다 [-fpermissive]. –

답변

9

당신은 같은 기본 클래스 이름을 수식 할 필요가 : template_class_methoda에 존재하기 때문에

a::template_class_method(); 

자격 a:: 필요하다. C++ 규칙은 기본 클래스가 클래스 템플릿 또는 템플릿 인수 인 경우 해당 멤버가 모두 이 아니고 파생 클래스에 자동으로 표시되는 것입니다 (). 컴파일러가 구성원을 찾는 데 도움이되도록 으로 말하면 base::member_function() 또는 base::member_data 형태의 구성원을 정규화해야하는 기본 클래스의 구성원을 찾습니다. 귀하의 경우에는

, 기본은 a이며, 회원은 template_class_method, 그래서 당신이 작성해야하기 때문에 : 이러한 기본 클래스가 그것을 이후 의존 기본 클래스를 호출된다는

a::template_class_method(); 

주 템플릿 인수에이 적용됩니다.

+0

오류가 발생했습니다 - 'base'가 선언되지 않았습니다 –

+1

@BryanFok : 물론'base'는 이름이 아닙니다. 'a'라고 써야합니다. – Nawaz

+0

오류가 발생했습니다. 템플릿 매개 변수에 의존하는 'template_class_method'에 대한 인수가 없으므로 'template_class_method'의 선언을 사용할 수 있어야합니다. [-fpermissive] –

2

왜 @ Karthik T가 대답을 삭제했는지 모르지만 그 답변은 올바른 길에있었습니다. 당신은 몇 가지 옵션

  1. this->template_class_method()

    template<typename a> 
    class test : public a 
    { 
    public: 
        void fun() 
        { 
        this->template_class_method(); 
        } 
    }; 
    
  2. 사용 선언

    를 통해 볼 수 기본 클래스 메서드를 확인 사용 수식 명 a::template_class_method()

    template<typename a> 
    class test : public a 
    { 
    public: 
        void fun() 
        { 
        a::template_class_method(); 
        } 
    }; 
    
  3. 사용 클래스 멤버 액세스 구문

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

첫 번째 방법은 template_class_method (가상 인 경우)의 가상도를 억제하므로주의해서 사용해야합니다. 이러한 이유로 자연수 인 template_class_method을 유지하므로 메서드 번호 2가 좋습니다.

this->template_class_method() "does not work"라는 귀하의 의견이 명확하지 않습니다. 아무런 문제없이 작동합니다. 게다가 위에서 말했듯이 일반적으로 정규화 된 이름을 사용하는 것보다 더 나은 옵션입니다.

+0

+1. – Nawaz

관련 문제