c++ - 使用语法在派生类中公开基类别名模板和变量模板?

标签 c++ templates inheritance c++17 using-declaration

在繁重的模板元编程上下文中考虑基础模板类和派生模板类(此处为了易于阅读并着重于此问题而对其进行了简化)。

template <class T>
struct base {
    using type = T;
    static constexpr int value = 0;
    template <class... Args>
    constexpr void function(Args&&...) {}
    template <class U>
    using alias_template = base<U>;
    template <class U>
    static constexpr int variable_template = 0; 
};

template <class T>
struct derived: base<T> {
    using typename base<T>::type;           // Using base typedef
    using base<T>::value;                   // Using base static data member
    using base<T>::function;                // Using base function members (regardless of template or not)
    //using typename base<T>::alias_template; // DOES NOT SEEM TO WORK
    //using base<T>::variable_template;       // DOES NOT SEEM TO WORK

    using typedef_test = type;                                          // Working
    static constexpr int value_test = value;                            // Working
    using alias_template_test = alias_template<T>;                      // ERROR
    static constexpr int variable_template_test = variable_template<T>; // ERROR
};

问题:是否存在using语法来公开从基类继承的别名模板和变量模板,以便编译当前错​​误的行?有什么解决方法可以避免在派生类中每次都指定base<T>::(这里仍然很简单,但是在我的实际代码中,每次指定都很快变得很烦人)?

最佳答案

using doesn't work this way用于依赖成员模板:

A using-declaration also can't be used to introduce the name of a dependent member template as a template-name (the template disambiguator for dependent names is not permitted)



我不确定这是否满足您的要求,但是为了使别名像模板一样工作,您可以在根据基本成员模板定义的派生类中声明新的成员模板:
template<typename U>
using alias_template = typename base<T>::template alias_template<U>;

template<typename U>
static constexpr auto variable_template = base<T>::template variable_template<U>;

但是,IMO每次指定base<T>::都不是问题,并且比引入新模板更干净。您甚至可以使用using Base = my_long_base_class_name<T>;将其缩短

关于c++ - 使用语法在派生类中公开基类别名模板和变量模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61857361/

相关文章:

继承

c++ - 我不明白为什么这会导致我的程序崩溃?

c++ - 邻接矩阵上的 BFS

c++ - 带有 c++17 的 `filesystem` 在我的 mac os x high sierra 上不起作用

c++ - 在模板的情况下包含头文件。

java - 从Java模板直接访问DAO

c++ - 这是使用基于范围的 for 循环的合理方法吗?

c++ - 在显式初始化期间尝试创建函数拷贝时出错

c++ - 覆盖虚函数的问题

java - 实现多个接口(interface)时尽量减少代码重复