简体   繁体   English

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

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

I was playing around a bit with Concepts offered in C++20 and came up with a simple example, which, to my surprise, does not produce the expected results (please leave any discussion on the usefulness of my example be:-)):我玩了一下 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;
}

I tried to make intvector a "restricted" std::vector which is only allowed to take integral types.我试图使intvector成为“受限制的” std::vector ,它只允许采用整数类型。 However, intvector seems to swallow arbitrary types just like the original vector, including user defined types.但是, intvector似乎可以像原始向量一样吞下任意类型,包括用户定义的类型。

Is this my fault or is clang not yet stable enough to handle this case properly?这是我的错还是 clang 还不够稳定,无法正确处理这种情况? I suspect there is an issue in mixing type aliases and requirements (as stated in this answer ), but I am unable to grasp it - in particular, my example compiles, while the one in the referenced post doesn't.我怀疑混合类型别名和要求存在问题(如本答案中所述),但我无法掌握它 - 特别是,我的示例编译,而引用帖子中的示例没有。

Your concept:你的概念:

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

does not check if the type is integral.不检查类型是否为整数。 Instead, it checks if comparing std::is_integral_v<T> with true is possible (which is always possible).相反,它检查是否可以将std::is_integral_v<T>true进行比较(这总是可能的)。 To fix your code you should just do:要修复您的代码,您应该这样做:

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