c++ - 使用概念禁用非模板化方法

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

是否有约束非模板化方法的语法?我在带有 clang 概念分支和 gcc 的 godbolt 上尝试过的所有语法都无法编译:

// these examples do not compile

template <bool B>
struct X
{
    requires B
    void foo() {}
};

template <class T>
struct Y
{
    requires (std::is_trivially_copyable_v<T>)
    auto foo() {}
};

让它编译的技巧与你需要用 SFINAE 做的技巧相同,制作方法模板,即使它们真的不是模板。有趣的是,约束似乎不需要方法模板,它可以单独在类模板上正常工作,所以我真的希望有一种方法可以将约束应用于概念,而不必求助于旧的黑客:
// old hacks

template <bool B>
struct X
{
    template <bool = B>
    requires B
    auto foo() {}
};

template <class T>
struct Y
{
    template <class = T>
    requires std::is_trivially_copyable_v<T>
    auto foo() {}
};

现实生活中的例子:
template <class T, bool Copyable_buf = false>
struct Buffer
{
    /* ... */

    requires Copyable_buf
    Buffer(const Buffer& other)  {}

    /* ... */
};

template <class T>
using Copyable_buffer = Buffer<T, true>;

最佳答案

为了支持另一个答案,以下是最新标准草案中关于此的规范性措辞:

[dcl.decl]

1 A declarator declares a single variable, function, or type, within a declaration. The init-declarator-list appearing in a declaration is a comma-separated sequence of declarators, each of which can have an initializer.

init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator
init-declarator:
    declarator initializeropt
    declarator requires-clause

4 The optional requires-clause ([temp]) in an init-declarator or member-declarator shall not be present when the declarator does not declare a function ([dcl.fct]). When present after a declarator, the requires-clause is called the trailing requires-clause. The trailing requires-clause introduces the constraint-expression that results from interpreting its constraint-logical-or-expression as a constraint-expression. [ Example:

void f1(int a) requires true;               // OK
auto f2(int a) -> bool requires true;       // OK
auto f3(int a) requires true -> bool;       // error: requires-clause precedes trailing-return-type
void (*pf)() requires true;                 // error: constraint on a variable
void g(int (*)() requires true);            // error: constraint on a parameter-declaration

auto* p = new void(*)(char) requires true;  // error: not a function declaration

— end example ]



正如这两段所指定的,尾部的 requires 子句可以出现在函数声明符的末尾。它的意思是通过它作为参数(包括概念)接受的常量表达式来约束函数。

关于c++ - 使用概念禁用非模板化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381851/

相关文章:

c++ - 如何检查 ranges::algorithms 如 find_if 是否返回值?

c++ - 是否可以在 C++20 的 requires 子句中初始化模板内部类?

C++:多态容器/迭代器与编译时概念/特征

c++ - clang 是否已经支持 C++11?

c++ - 编写扩展 LinkedList 的对象

c++ - 映射#include 的工具

c++ - std::invocable 和 std::regular_invocable 概念之间有什么区别?

c++ - 如何在 C++ 中专门化可变参数模板函数?

具有类似 friend 访问权限的 C++ 概念

c++ - 如何在 C 和 C++ 中分配和释放 *array* 内存?