c++类重载:是否有可能让编译器根据模板判断使用哪一个?

C++ classes overloading: is it possible to make compiler see which one to use based on template?

本文关键字:判断 哪一个 重载 是否 有可能 编译器 c++      更新时间:2023-10-16

我已经创建了N个类,从一个到N个int到构造函数(我希望这就足够了),但似乎我错了。

下面是两个示例类:

template < class T0 , class T1>
class my_map {
    typedef T0 type_0;
    typedef T1 type_1;
    std::map<std::string, type_0* > T0_var;
    std::map<std::string, type_1* > T1_var;
    friend class apitemp;
public:
    my_map(  int meaningless0 = 42  , int meaningless1 = 42  ) {}
    class apitemp {
        std::string n_;
        my_map* p;
    public: apitemp(std::string name_, my_map* parent) : n_(name_), p(parent) {}
            operator type_0*() {return p->T0_var[n_] ; }
            operator type_1*() {return p->T1_var[n_] ; } 
    };
    void insert(std::string name, type_0* ptr)
    { T0_var[name] = ptr; } 
    void insert(std::string name, type_1* ptr)
    { T1_var[name] = ptr; } 
    apitemp operator[](std::string n_) {return apitemp(n_, this);} 
}; 
template < class T0> 
class my_map
{ 
    typedef T0 type_0; 
    std::map<std::string, type_0* > T0_var;
    friend class apitemp;
public: 
    my_map(  int meaningless0 = 42  ) {} 
    class apitemp 
    {
        std::string n_;
        my_map* p;
    public:
        apitemp(std::string name_, my_map* parent) : n_(name_), p(parent) {}
        operator type_0*() {return p->T0_var[n_] ; }
    }; 
    void insert(std::string name, type_0* ptr) 
    { T0_var[name] = ptr; } 
    apitemp operator[](std::string n_) {return apitemp(n_, this);} 
};

顺序不重要…当两个类都存在时,我无法编译我的代码,当一个被注释时(我们只使用两个类中的一个的API),一切都编译…但是当我尝试使用两者时,我会得到编译器错误……所以我想知道如何使这些类可重写?

你不能像你想做的那样在类型参数的数量上"重载"模板。对这个限制的正确反应取决于你到底想做什么。

似乎你的目的是让一个map从一个字符串映射到一个可变数量的值(在编译时设置)。但是您已经有了这样一个模板化的容器:std::map本身!

// This maps to int
std::map<std::string, int> map_to_int;
struct foo {
    std::string str;
    int i;
};
// This effectively maps to 2 fields
std::map<std::string, struct foo> map_to_struct;
// etc etc

如果你被允许写

std::map<std::string, std::string*, int*> does_not_compile;

不会给你任何上面的map_to_struct没有给你的东西