禁用带有概念的非模板化方法 [英] Disable non-templated methods with concepts

查看:58
本文介绍了禁用带有概念的非模板化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在限制非模板化方法的语法?我在使用clang concept branch和gcc的Godbolt上尝试过的所有语法都无法编译:

Is there a syntax to constraint a non-templated method? All the syntaxes I've tried on godbolt with clang concepts branch and gcc fail to compile:

// 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所需的技巧相同,使方法成为模板,即使它们实际上不是模板.有趣的是,约束似乎不需要方法模板,它可以单独在类模板上正常工作,所以我真的希望有一种方法可以将约束应用于概念而不必求助于旧的技巧:

The trick to make it compile is the same trick you needed to do with SFINAE, make the methods template, even though they really are not templates. And funny enough, the constraint doesn't seem to need the method template, it can work fine on the class template alone, so I really hope there is a way to apply the constraints with concepts without having to resort to the old hacks:

// 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() {}
};


现实生活中的例子:


Real life example:

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>;

推荐答案

是的,有! requires子句可以作为函数声明符的最后一个元素出现,其中允许限制非模板化方法(或与此相关的自由函数)的情况:

Yes, there is!! The requires clause can appear as the last element of a function declarator, in which case it allows to constraint non-templated methods (or free functions for that matter):

// This works as expected! Yey!!

template <class T, bool Copyable_buf = false>
struct Buffer
{
    Buffer(const Buffer& other) requires Copyable_buf
    {
        // ...
    }
};

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

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


此答案是经验性的,基于对概念的当前实现的测试. Godbolt测试.储物柜出纳员的答案给出了确认该行为的标准报价.


This answer is empirical, based on testing on current implementations of concepts. Godbolt test. Storry Tellers's answer gives standard quotes confirming this behavior.

这篇关于禁用带有概念的非模板化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆