【问题标题】:c++ deduce bool class template argument by constructor choicec ++通过构造函数选择推断bool类模板参数
【发布时间】:2021-08-13 22:09:12
【问题描述】:

我试图通过选择类构造函数来推断一个 bool 模板参数。 一个简单的例子:

template <typename A, bool Condition>
class Subrange {
    public:
    Subrange(A a) requires (not Condition); /* create Subrange<A, false> */
    Subrange(A a, int b) requires (Condition); /* create Subrange<A, true> */
};

这甚至可能吗,还是必须在构造函数上明确指定条件?
PS:条件不依赖A。

【问题讨论】:

  • 这没有意义,Subrange&lt;A,false&gt; 有一个 Subrange(A a, int b) 构造函数,反之亦然
  • @al3c 你说得对,我已经编辑了代码

标签: c++ templates c++17 template-argument-deduction ctad


【解决方案1】:

您可以为类模板参数推导 (CTAD)(C++17 起)定义user-defined deduction guide

template<typename A> Subrange(A a) -> Subrange<A, false>;
template<typename A> Subrange(A a, int b) -> Subrange<A, true>;

然后

Subrange s1(0);    // -> Subrange<int, false>
Subrange s2(0, 0); // -> Subrange<int, true>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2017-09-27
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多