我想在 c++ 中实现没有继承的类似 golang 的接口(interface)。
例如:-
//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 或更高版本)。
关于c++ - 在 C++ 中模仿类似 Golang 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44856485/