C++ 如何创建一个不允许模板参数的 class 模板

C++ How to create a class template that allows no template arguments

如果我的标题令人困惑,我深表歉意。我想要做的是创建一个 class 模板,从头开始实现 std::map。我想要实现的是不在模板参数中使用特定的数据类型。请看下面的代码:

#include "pch.h"
#include <iostream>
#include <string>

using namespace std;
template<typename T, typename N>

class MyCustomMap{
    public:
    MyCustomMap();
    T* keys;
    N* values;
};

template<typename T, typename N>
MyCustomMap<T, N>::MyCustomMap(){
    this->keys = new T[10];
    this->values = new N[10];
}
....
....
int main(){
    MyCustomMap<int,string> map; //This works because I specified the argument list
    MyCustomMap map; //This is my goal

    // The main goal is to call Insert one after another with different data types
    map.Insert(1, "Test");
    map.Insert("Test2", 2);

    return 0;
}

这可能吗?感谢任何帮助,谢谢。

MyCustomMap map;

Is this possible?

简答:没有。

长答案:如果您将一些参数传递给构造函数

MyCustomMap map{1, "one"};

可以推导出 TintVchar const [4]

但是,不幸的是,只能从 C++17 开始;查看 this page 了解更多信息。

但是如果你不给构造函数传递参数,就没有办法推导出参数。

编辑

OP 精确

// The main goal is to call Insert one after another with different data types
map.Insert(1, "Test");
map.Insert("Test2", 2);

抱歉:我误解了你的问题。

但答案仍然是:不。

C++ 是一种编译型强类型语言。

并且模板 class 不是 class:是一组 classes。

当你实例化一个对象时

MyCustomMap map;

这个对象(map,在本例中)必须是一个精确类型的对象;编译器在编译时知道那个精确位置。

所以你不能实例化一个map类型,一般来说,MyCustomMap。您必须选择几种类型。也许使用默认值,也许通过构造函数参数推导类型,也许使用 auto 类型并使用函数返回的类型,但必须在声明变量时选择类型。不在之后。

而且,无论如何,如果你想要

map.Insert(1, "Test");  
map.Insert("Test2", 2);

您想要一件具有两种不同类型的现代物品。

C++17 中有这方面的东西:寻找 std::anystd::variant。但是没那么灵活。