我想知道C ++(尤其是C ++ 20)中是否有一种方法可以为类/结构编写某种接口。
例如,在Java接口中,是一个完全“抽象类”,用于将具有空主体的相关方法分组:
interface Animal
{
public void animalSound();
public void run();
}
在C ++中,您可以使用纯虚方法声明来实现相同的行为。
class Animal
{
public:
virtual void animalSound() = 0;
virtual void run() = 0;
};
但是使用虚拟方法会产生运行时成本,并且我对继承不感兴趣。 因此,该运行时成本应该没有必要。我只想对我的“动物”类/结构进行编译时检查。
我确信使用C ++ 20的Concepts是可以实现的 您可以将其应用于类,以确保提供了一组特定的方法。
我试图做的事情看起来像这样。
template<typename Animal_> concept Animal =
requires()
{
(Animal_{}); // default constructable
(Animal_{}.animalSound());
(Animal_{}.run());
};
但是我不确定这是不是很C ++。
(通过一种方法可以要求方法的返回类型为特定类型吗?)
而且我不确定如何将其附加到类/结构上。
My first thought was to use a static_assert
inside the class/struct:
class Cow
{
private: // compile time type checking
static_assert(std::is_matching_concept<Animal, Cow>);
public:
void animalSound() const noexcept {}
void run() const noexcept {}
};
Where std::is_matching_concept
is a placeholder for a constraint that I can not find.
我正在寻找最佳实践反馈和建议来解决我的问题。