作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我想创建一个模板类,可以容纳容器和容器的任意组合。例如,std::vector<std::string>
或 std::map<std::tree>
,例如。
我尝试了很多组合,但我必须承认模板的复杂性让我不知所措。我编译的关闭是这样的:
template <class Vector, template <typename, class Containee = std::string> class Container>
class GenericContainer
{
Container<Containee> mLemario;
};
虽然它编译到目前为止,然后,当我想实例化它时,我会收到很多错误。
MyContainer<std::vector, std::string> myContainer;
我是否使用了正确的方法来创建那种类?
最佳答案
对于 std::vector
(以及类似的)@ songyuanyao提供了一个很好的答案。但由于您还提到了 std::map
,我将添加一个简单的扩展 @ songyuanyao的答案,online .
#include <iostream>
#include <vector>
#include <string>
#include <map>
template <template <typename...> class Container, typename Containee = std::string, typename... extras>
class GenericContainer
{
Container<Containee, extras ...> mLemario;
// Use 'Containee' here (if needed) like sizeof(Containee)
// or have another member variable like: Containee& my_ref.
};
int main()
{
GenericContainer<std::vector, std::string> myContainer1;
GenericContainer<std::vector, std::string, std::allocator<std::string>> myContainer2; // Explicitly using std::allocator<std::string>
GenericContainer<std::map, std::string, int> myContainer3; // Map: Key = std::string, Value = int
}
关于c++ - 具有模板模板参数的模板定义,可以专门化为类,例如,std::vector<std::string> 或 std::map<std::tree>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45811378/
出于好奇,我尝试了一些原型(prototype)制作,但似乎只允许在第一个位置使用子例程的原型(prototype) &。 当我写作时 sub test (&$$) { do_somethin
我需要开发一个类似于 Android Play 商店应用程序或类似 this app 的应用程序.我阅读了很多教程,发现几乎每个教程都有与 this one 类似的例子。 . 我已经开始使用我的应用程
考虑一个表示“事件之间的时间”的列: (5, 40, 3, 6, 0, 9, 0, 4, 5, 18, 2, 4, 3, 2) 我想将这些分组到 30 个桶中,但桶会重置。期望的结果: (0, 1,
我是一名优秀的程序员,十分优秀!