繁体   English   中英

我可以在 using 声明中正确使用 C++20 概念吗?

[英]Can I use C++20 concepts properly in a using declaration?

我玩了一下 C++20 中提供的概念,并想出了一个简单的例子,令我惊讶的是,它并没有产生预期的结果(请留下关于我的例子有用性的任何讨论:-)) :

#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 还不够稳定,无法正确处理这种情况? 我怀疑混合类型别名和要求存在问题(如本答案中所述),但我无法掌握它 - 特别是,我的示例编译,而引用帖子中的示例没有。

你的概念:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM