【问题标题】:Can I use C++20 concepts properly in a using declaration?我可以在 using 声明中正确使用 C++20 概念吗?
【发布时间】:2020-02-25 15:03:08
【问题描述】:

我玩了一下 C++20 中提供的概念,并想出了一个简单的例子,令我惊讶的是,does not produce the expected results(请留下任何关于我的例子有用性的讨论是 :-)) :

#include <iostream>
#include <type_traits>
#include <vector>

template <typename T>
concept i_am_integral = requires { std::is_integral_v<T> == true; };

template <typename T> requires i_am_integral<T>
using intvector = std::vector<T>;

int main() {
    intvector<int> v = { 1, 2, 3 }; // <- This is fine, int is an integral type

    // I would expect this to fail:
    intvector<double> w = { 1.1, 2.2, 3.3 };

    // I'm curious, so let's print the vector
    for (auto x : w) { std::cout << x << '\n'; }

    // Same here - IMO, this should fail:
    struct S{};
    intvector<S> s;
}

我试图将intvector 设为“受限”std::vector,它只允许采用整数类型。但是,intvector 似乎可以像原始向量一样吞下任意类型,包括用户定义的类型。

这是我的错还是 clang 还不够稳定无法正确处理此案例?我怀疑在混合类型别名和要求方面存在问题(如this answer 中所述),但我无法理解它 - 特别是,我的示例编译,而引用帖子中的示例没有。

【问题讨论】:

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


    【解决方案1】:

    你的概念:

    template <typename T>
    concept i_am_integral = requires { std::is_integral_v<T> == true; };
    

    不检查类型是否为整数。相反,它检查是否可以将std::is_integral_v&lt;T&gt;true 进行比较(这始终是可能的)。要修复您的代码,您应该这样做:

    template <typename T>
    concept i_am_integral = std::is_integral_v<T>;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2022-10-14
      • 2019-05-06
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多