在C++中模仿类似 Golang 的界面
Mimic Golang-like interfaces in C++
我想在 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或更高版本(。
相关文章:
- Qt5 用户界面编译器:-i 选项不可用
- 在 Golang 中等C++结构中提供代码提示/标记
- 如何使用VirtualDesktopManager界面?
- 如何使用谷歌基准测试对自定义界面进行基准测试
- 使用std::tie进行类似golang的错误处理,同时返回结果,是否有缺点?(C++11)
- 如何简化此添加界面
- Golang CGO with large char pointer语言 - SEGSERV
- 如何编译谷歌Protobuf命令行界面编译
- 动词/动作命令行界面的任何C++库?
- 在C++中模仿类似 Golang 的界面
- 记录器的流界面,C
- 如何在C++命令行界面程序中运行 COM (.ocx) 对象.(VS2017)
- 如何在不破坏装饰器模式的情况下瘦身胖界面?
- QMenuBar 不使用原生样式? c++ , QTDesigner.用户界面
- 使用部分共享界面组织对象
- 可以使用仅功能成员属性进行回调界面
- 为什么C++升压库中的累加器具有类似功能的界面?
- 用MacOS主机上的Windows目标交叉编译Golang
- 界面设计:超载功能的安全性采用字符串和字符阵列
- boost :: Asio连接错误的界面