【问题标题】:Enable member functions of class templates using concepts使用概念启用类模板的成员函数
【发布时间】:2018-12-28 04:05:49
【问题描述】:

所以我有一个概念Fooable

template <typename T>
concept bool Fooable()
{
    return requires(...){ ... };
}

我有一个类模板Bar,它采用T 作为模板参数,我只想在TFooable 时启用成员函数:

template <typename T>
class Bar
{
public:
    template // ???
        requires Fooable<T>
    void MemFun();
};

在 C++17 中是否可以使用概念 TS 或在 C++2a 中?

【问题讨论】:

  • 不是答案,但如果您实际上不需要禁用函数来不参与重载解决方案,您可以简单地使用static_assert
  • @HolyBlackCat 我在测试中进行了完整的模板实例化,以查看所有成员函数是否正确。添加 static_assert 会破坏其中的一些。
  • 通过概念 TS 可以通过void MemFun() requires Fooable&lt;T&gt;() {}

标签: c++ c++17 c++-concepts c++20


【解决方案1】:

在 Concepts TS 和 C++20 设计中,函数都有一个可选的尾随 requires-clause。所以你不需要让你的成员函数成为一个模板来约束它:

void MemFun() requires Fooable<T>;

【讨论】:

    【解决方案2】:

    约束可以在函数的尾随位置:

    template <typename T>
    class Bar
    {
    public:
        void MemFun() requires Fooable<T>;
    };
    

    Live on Godbolt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 2016-10-05
      • 2012-04-22
      • 2019-11-23
      • 1970-01-01
      相关资源
      最近更新 更多