c++ - 派生模板类访问基类成员数据

标签 c++ templates inheritance scope name-lookup

这个问题是对 this thread 中提出的问题的进一步插入.

使用以下类定义:

template <class T>
class Foo {

public:
    Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg)
    {
        /* do something for foo */
    }
    T Foo_T;        // either a TypeA or a TypeB - TBD
    foo_arg_t _foo_arg;
};

template <class T>
class Bar : public Foo<T> {
public:
    Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
    : Foo<T>(bar_arg)   // base-class initializer
    {

        Foo<T>::Foo_T = T(a_arg);
    }

    Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
    : Foo<T>(bar_arg)
    {
        Foo<T>::Foo_T = T(b_arg);
    }

    void BarFunc ();

};

template <class T>
void Bar<T>::BarFunc () {
    std::cout << _foo_arg << std::endl;   // This doesn't work - compiler error is: error: ‘_foo_arg’ was not declared in this scope
    std::cout << Bar<T>::_foo_arg << std::endl;   // This works!
}

当访问模板类的基类成员时,似乎我必须始终使用 Bar<T>::_foo_arg 的模板样式语法显式限定成员。 .有没有办法避免这种情况? “using”语句/指令可以在模板类方法中发挥作用以简化代码吗?

编辑:

通过使用 this-> 语法限定变量来解决范围问题。

最佳答案

您可以使用 this-> 来明确您指的是类的成员:

void Bar<T>::BarFunc () {
    std::cout << this->_foo_arg << std::endl;
}

或者你也可以在方法中使用“using”:

void Bar<T>::BarFunc () {
    using Bar<T>::_foo_arg;             // Might not work in g++, IIRC
    std::cout << _foo_arg << std::endl;
}

这让编译器清楚地知道成员名称取决于模板参数,以便它在正确的位置搜索该名称的定义。有关更多信息,请参阅 this entry in the C++ Faq Lite .

关于c++ - 派生模板类访问基类成员数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49645682/

相关文章:

c++ - 在容器中查找以给定字符开头的所有单词

c++ - 如何正确使用选项和标志来更改 OpenMesh 中的 read_mesh 和 write_mesh 函数?

模板中的 C++ 模板

c++ - 我可以模板化用户定义的文字吗?

c++ - C++ 中的非虚拟多态性

Javascript类继承和所有继承的名称?

java - 如何通过 Socket 发送子类并在另一端恢复它们

c++ - 交叉编译教程

C++奇怪的值重置

c++ - 启用 C++11 时如何修复 'wrong number of template arguments''?