【问题标题】:Inheriting a templated conversion operator继承模板化转换运算符
【发布时间】:2020-10-14 14:03:48
【问题描述】:

考虑以下代码:

template <class R, class... Args>
using function_type = R(*)(Args...);

struct base {
    template <class R, class... Args>
    constexpr operator function_type<R, Args...>() const noexcept {
        return nullptr;
    }
};

struct derived: private base {
    template <class R, class... Args>
    using base::operator function_type<R, Args...>; // ERROR
};

在 C++20 中是否有可行的替代方法来继承和公开模板化转换函数?

【问题讨论】:

  • Afaics 当前的 C++2a 标准草案仍然包含阻止使用 using-declarations 引用基类的成员模板转换函数的特化的段落; eel.is/c++draft/namespace.udecl#4.sentence-2.
  • derived 中是否有 其他 转换函数会隐藏base 中的转换函数模板?
  • @DavisHerring 它正在尝试更改访问权限。
  • @T.C.:是的——我错过了私有继承。

标签: c++ inheritance template-meta-programming c++20 conversion-operator


【解决方案1】:

GCC 支持这个:[demo]

template <class R, class... Args>
using function_type = R(*)(Args...);

struct base {
    template <class R, class... Args>
    constexpr operator function_type<R, Args...>() const noexcept {
        return nullptr;
    }
};

struct derived: private base {
  
    using base::operator function_type<auto, auto...>; // No error!
};


int main (){
  derived d;
  static_cast <int(*)(int)>(d);
}

但我认为这是对可能来自概念 TS 的语言的扩展。

【讨论】:

    【解决方案2】:

    在 C++20 中是否有可行的替代方法来继承和公开模板化转换函数?

    我不知道通过using 直接公开它的方法。

    但你可以将它包装在派生运算符中

    struct derived: private base {
    
        template <typename R, typename... Args>
        constexpr operator function_type<R, Args...>() const noexcept {
           return base::operator function_type<R, Args...>();
        }
    
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-10
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2021-01-01
      相关资源
      最近更新 更多