【问题标题】:Confusion with C++20 concepts: constructible_from constraint on member type与 C++20 概念混淆:constructible_from 对成员类型的约束
【发布时间】:2021-09-10 02:13:51
【问题描述】:

(问题源于玩弄概念;不要认为这是一个必然的工程选择或任何事情。)

我试图指定满足概念的类型必须具有成员类型,并且该成员类型必须以某种方式可构造。作为一个最小的例子,它必须可以从 3 个整数构造。但我不知道如何正确表达:

#include <concepts>

template <typename T> concept Foo = requires {
  typename T::TypeLikeThreeIntegers;
  std::constructible_from<typename T::TypeLikeThreeIntegers, int, int, int>;
  // I originally wrote
  // std::constructible_from<T::TypeLikeThreeIntegers, int, int, int>;
  // but compiler (clang++-12) gave an error and suggested the typename keyword
};

struct ThreeIntegers {
  int x, y, z;
};

struct SatisfiesFoo {
  using TypeLikeThreeIntegers = ThreeIntegers;
};

static_assert(Foo<SatisfiesFoo>);
// all is good so far

struct OnlyTwoIntegers {
  int x, y;
};

struct ShouldNotSatisfyFoo {
  using TypeLikeThreeIntegers = OnlyTwoIntegers;
};

static_assert(Foo<ShouldNotSatisfyFoo>);
// I expect this to fail but it doesn't!

int main() {
  SatisfiesFoo::TypeLikeThreeIntegers v1{1, 2, 3};
  // ShouldNotSatisfyFoo::TypeLikeThreeIntegers v2{1, 2, 3}; (error)
  // would like the concept Foo to prevent such an error and give useful diagnostic
}

【问题讨论】:

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


    【解决方案1】:

    requires 子句中的std::constructible_from 只会检查std::constructible_from有效性,不会评估它,你应该使用额外的requires 来检查:

    template <typename T> concept Foo = requires {
      typename T::TypeLikeThreeIntegers;
      requires std::constructible_from<typename T::TypeLikeThreeIntegers, int, int, int>;
    };
    

    但这应该足够了:

    template <typename T> concept Foo = 
      std::constructible_from<typename T::TypeLikeThreeIntegers, int, int, int>;
    

    Demo.

    请注意,Clang 将still fail,因为它没有实现P0960R3,所以目前is_constructible 不适用于聚合:

    struct S { int x; };
    static_assert(std::is_constructible_v<S, int>); // fails only on Clang
    

    【讨论】:

    • 谢谢。您的回答确实向我阐明了简单需求和嵌套需求之间的区别。
    猜你喜欢
    • 2022-09-29
    • 2019-11-20
    • 2013-03-30
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多