c++ - 在 C++ 中模仿类似 Golang 的接口(interface)

标签 c++

我想在 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/

相关文章:

c++ - 确定套接字中的可用字节数

c++ - 我可以使用 GT511C1 代替 GT511C3 指纹扫描仪吗?

c++ - 以预定义的非均匀概率生成范围内的随机数

c++ - 存储正常(即非动态分配)数据的非动态创建的 std::vectors 的内存释放问题

c++ - QGraphicsScene::items 不返回给定矩形的项目

c++ - 数组 : Storing Objects or References

c++ - 错误 : lvalue required as unary & operand

c++ - 具有 x、y、z 的点和具有 x()、y()、z() 的点的模板函数

c++ - 检查一棵树是否满足红黑树的black-height属性

c++ - QtCreator 和 Poco 无法在 Linux 上编译项目