c++ - 模板继承 : There are no arguments that depend on a template parameter

标签 c++ templates inheritance

<分区>

我在编译以下代码时遇到了这个错误。 在做了一些研究并阅读了不同情况下的类似错误之后,我想出了我需要的解决方案。 但是我没有完全理解错误和修复的根本原因。

template <typename T>
class TestA {
    int a;
    T temp;

protected:
    int b; 

public: 
    int c;

    TestA(T te): a{10}, b{20}, c{30}, temp{te} {}

    int geta(){ return a; }
    int getb(){ return b; }
    int getc(){ return c; }
};

template <typename T>
class TestB {
    int atb;
    T tempb;

protected:
    int btb; 

public: 
    int ctb;

    TestB(T te) atb{10}, btb{20}, ctb{30}, tempb{te} {}
};

template <typename T>
class TestInh : public TestA<T>, public TestB<T> {
    int aa;
    T temptemp;

protected:
    int bb; 
    int b;

public: 
    int cc;

    TestInh(T te) : TestA<T>{te}, TestB<T>{te}, bb{10000}, b{-1000} {}

    int get_total() {
        // The error happens here!
        return geta();
    }
};

int main(int argc, char const *argv[]) {
    char text = 'a';
    TestInh<char> test(text);

    //std::cout << test.geta() << std::endl;
    std::cout << test.get_total() << std::endl;
    //std::cout << test.c << std::endl;
    return 0;
}

编译这段代码时,我得到了这个错误:

testtemplate.cc: In member function ‘int TestInh<T>::get_total()’:
testtemplate.cc:54:32: error: there are no arguments to ‘geta’ that depend on a template parameter, so a declaration of ‘geta’ must be available [-fpermissive]
int get_total() {return geta();}
                            ^
testtemplate.cc:54:32: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

它通过调用 this->geta() 而不是仅仅调用 geta() 来解决,但我不完全理解为什么编译器不能解决这个问题。

谁能解释一下为什么?

最佳答案

扩展依赖于模板参数的类时,this有点成为从属名称。

问题是,在执行两个阶段名称查找时,编译器不知道在哪里可以找到函数geta。 .他不知道它来自 parent 。因为模板特化是一回事,TestA<int>TestA<double>可以是具有不同功能和成员的两个完全不同的类。

随着 this添加关键字,编译器知道 geta必须是成员函数。

否则,它可能是成员函数或非成员函数,或者是 TestB 的成员函数.

想象一个将调用函数 geta 的模板代码来自 TestAgeta来自 TestB取决于一些模板条件。哎哟。编译器希望确保代码对于每个模板实例都是一致的。

另一种告诉编译器该函数作为成员函数存在的方法是添加一个 using 语句:

template <typename T> 
struct TestInh : TestA<T>, TestB<T> {
    // some code...

    using TestA<T>::geta;

    int get_total() {
        // works! With the above using statement,
        // the compiler knows that 'geta()' is
        // a member function of TestA<T>!
        return geta();
    }
};

关于c++ - 模板继承 : There are no arguments that depend on a template parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39667599/

相关文章:

java - Android: "Can not resolve method ' x( 重写父类(super class)方法时为 )'"

c++ - 类模板的智能指针 vector

python - Django 缓存不工作 cached_queries() 没有参数(给定 1)

c++ - C++如何区分派(dispatch)生类的对象

Javascript 原型(prototype)继承怪异

c++ - 如何遍历递归模板类

c++单例,堆栈溢出示例不起作用

c++ - 当未存储返回值时,std::async 不会生成新线程

c++ - 如何返回 std::map 项目

c++ - 如何对链表执行选择排序?