在C++中模仿类似 Golang 的界面

Mimic Golang-like interfaces in C++

本文关键字:Golang 界面 C++      更新时间:2023-10-16

我想在 c++ 中实现类似 golang 的接口而不继承。

例如:-

//interface
struct Copyable{
void copy();
}
class Animal { //which implements the interface but doesn't inherit it.
....
void copy();
...
}
//consumer function
void Copy(Interface<Copyable> item){
item.copy();
}
int main(){
Animal a;
Copy(a);
}

有什么方法可以实现这一点吗?

是的,您可以使用模板:

template <typename T>
void Copy(T item) {
item.copy();
}

那么你根本不需要类Copyable

如果类型T没有copy()方法,它将无法编译(如您所料(。

C++ Concepts是一个提议的功能,有朝一日可能会成为标准语言,但目前仅受某些编译器支持,例如GCC(6或更高版本(。