【问题标题】:Inheritance of public typedef with templates使用模板继承公共 typedef
【发布时间】:2021-04-11 20:06:37
【问题描述】:

我正在尝试从继承的类 (B) 访问基 (A) 类中定义的公共 typedef。

但我仍然需要用 A 来限定类型名。

有没有一种语法可以明确地使 B 可以使用 mytype 而无需使用多余的诡计?

template <typename T>
class A {
public:
        typedef T mytype;
};

template <typename T>
class B : public A<T> {
public:
        /* This seems redundant */
        typename A<T>::mytype foo(typename A<T>::mytype x) {
                return x;
        }

        /* This is also redundant but would make bar below work*/
        // typedef typename A<T>::mytype mytype;

        /* This feels natural but does not work */
        mytype bar(mytype x) {
                return x;
        }
};

【问题讨论】:

  • 在 B 类中,添加这一行:using mytype = typename A&lt;T&gt;::mytype;
  • @Eljay 不会 using A&lt;T&gt;::mytype; 已经工作了吗?
  • 这似乎不起作用,我认为 using 更多的是使用 T 本身的 typedef。

标签: c++ templates inheritance typedef


【解决方案1】:

原因是非限定查找找不到相关基类的成员。
一种解决方案是使查找合格:

typename B::mytype

为了不用每次都输入这个,你可以在 B 中引入一个别名:

using mytype = typename B::mytype;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2011-04-06
    • 2011-03-03
    • 2015-04-18
    • 2018-05-23
    • 2011-01-05
    相关资源
    最近更新 更多