小编Rob*_*sch的帖子

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

我想知道 C++(尤其是 C++20)中是否有一种方法可以为类/结构编写某种接口。

例如,在 Java 中,接口是一个完全“抽象类”,用于将相关方法与空主体分组:

interface Animal
{
  public void animalSound();
  public void run();
}
Run Code Online (Sandbox Code Playgroud)

在 C++ 中,您可以使用纯虚方法声明来实现相同的行为。

class Animal
{
public:
  virtual void animalSound() = 0;
  virtual void run() = 0;
};
Run Code Online (Sandbox Code Playgroud)

但是使用虚拟方法会产生运行时成本,而且我对继承不感兴趣。所以这个运行时成本应该是没有必要的。我只想检查我的“动物”类/结构的编译时间。

通过 C++20 的概念,我确信构建一个可以应用于类的构造以保证提供一组特定的方法是可以实现的。

我想做的事情看起来有点像这样。

template<typename Animal_> concept Animal =
requires()
{
  (Animal_{}); // default constructable

  (Animal_{}.animalSound());
  (Animal_{}.run());
};
Run Code Online (Sandbox Code Playgroud)

但我不确定这样做是否非常c++。

(请问有没有办法要求方法的返回类型是特定类型?)

我不确定如何将其附加到类/结构中。

static_assert我的第一个想法是在类/结构内部使用 a :

class Cow
{
private: // compile time type checking
  static_assert(std::is_matching_concept<Animal, Cow>);

public:
  void animalSound() const noexcept {}
  void run() const …
Run Code Online (Sandbox Code Playgroud)

c++ templates class c++-concepts c++20

8
推荐指数
1
解决办法
2460
查看次数

标签 统计

c++ ×1

c++-concepts ×1

c++20 ×1

class ×1

templates ×1