c++ - 概念包含适用于函数,但不适用于结构

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

对可能错误的标题表示歉意,这是我对正在发生的事情的最佳猜测。

我正在学习一些基本概念并尝试了这个:

#include <concepts>
#include <iostream>
#include <memory>

template<typename T>
concept eight = sizeof(T) == 8;

template<typename T>
concept basic = std::is_trivial_v<T>;

template<typename T>
requires eight<T>
constexpr void ff(){
    std::cout << "eight" << std::endl;
}

template<typename T>
requires eight<T> && basic<T>
constexpr void ff(){
    std::cout << "eight and basic" << std::endl;
}

template<typename T>
requires eight<T>
struct ffs{
};

template<typename T>
requires eight<T> && basic<T>
struct ffs{
};

对我来说最疯狂的是我得到 error当相同的东西适用于函数时,适用于结构。

:29:10: error: requires clause differs in template redeclaration requires eight && basic ^ :24:10: note: previous template declaration is here requires eight

可能我在这两种情况下都只是 UB+NDRing,但编译器在第一种情况下并不介意(不是说当我从代码中删除结构时,我的代码似乎按预期运行,包括根据概念正确区分要调用的内容),但这似乎不太可能。

附注如果有人想知道为什么我不使用 require 而不是简单的概念,这里是 answer .

最佳答案

在概念之前不允许重载模板类,即使有了概念仍然不允许。使用部分特化:

template <typename T>
requires eight<T>
struct ffs {};

template <typename T>
requires basic<T>
struct ffs<T> {};

或者使用简洁的语法:

template <eight T>
struct ffs {};

template <basic T>
struct ffs<T> {};

请注意,在这两种情况下,主模板上的约束会自动应用于所有特化。

关于c++ - 概念包含适用于函数,但不适用于结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70554169/

相关文章:

c++ - STL/Boost 相当于 LLVM SmallVector?

c++ - 为什么 C++20 std::condition_variable 不支持 std::stop_token?

c++ - 如何进行跨度类推导以正确执行右值数组的 CTAD?

c++ - 如何将shared_ptr<void>转换为另一种类型?

c++ - 在概念定义中,是否允许在 requires 表达式之外出现替换失败?

C++ 对 std::bitset 的位进行操作

c++ - 当我们在这个函数中反转字符串时,为什么 char *str 的指针没有改变?

c++ - exe中有哪些库

c++ - 明确的概念特化

c++ - 是否允许对封闭范围的 "capture"变量使用 requires 表达式?