c++ - 是否可以使用 `requires` 子句启用/禁用纯虚函数?

标签 c++ pure-virtual c++-concepts

我有一个处理相同概念的类的适配器类。
现在,我想要该适配器,基于模板参数 RO (只读)禁用 pack() .但我不知道这是否在纯虚拟机中不受支持,或者只是我写错了。

template<bool RO>   // means read only functionality
class Adapter
{
    struct AbstractAdapter
    {
        virtual ~AbstractAdapter() = default;
        virtual void unpack() = 0;
        virtual void pack() = 0 requires (!RO);   // compile ERROR!! ERROR!! ERROR!!
    };


    template<typename T> requires (Reader<T> || Writer<T>)
    struct TemplateAdapter : public AbstractAdapter
    {
        virtual void unpack()
        {
            if constexpr (!Reader<T>) throw UnsupportedOperationEx{};
            else client.unpack();
        }
        virtual void pack() requires (!RO)
        {
            if constexpr (!Writer<T>) throw UnsupportedOperationEx{};
            else client.pack();
        }

        T client;
    };

public:
    void unpack() { client->unpack(); }
    void pack() requires(!RO) { client->pack(); }

private:
    AbstractAdapter *client;
};

最佳答案

在 C++20 标准中,11.7.2 [class.virtual] 第 6 段说:

A virtual function shall not have a trailing requires-clause (9.3). *[Example:

struct A {
    virtual void f() requires true;
         // error: virtual function cannot be constrained (13.5.2)
};

— end example]


它更冗长,但您可以改为使用 std::conditional 在 ReadOnly 和 ReadWrite 适配器层次结构之间进行选择。 (避免使用大写的多字符标识符 [带或不带下划线) - 最佳实践将它们留给预处理器使用)。

关于c++ - 是否可以使用 `requires` 子句启用/禁用纯虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63104956/

相关文章:

php mcrypt_encrypt 到 C/C++/MFC equalivilent

c++ - 文件输入和编译错误

c++ - 为什么纯虚拟析构函数需要实现

C++ map.clear() 纯虚方法运行时报错

c++ - 在什么情况下给出一个纯虚函数的实现是有利的?

c++ - 使用 C++20 概念强制类实现一组方法

c++ - 如何使用 `requires` 和 `-> return_type` 声明成员函数

c++ - 我如何使用 std::constructible_from

c++ - 隐藏结构如何工作?

c++ - std::具有相同基类的类的变体