我有一个处理相同概念的类的适配器类。
现在,我想要该适配器,基于模板参数 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/