c++类重载:是否有可能让编译器根据模板判断使用哪一个?
C++ classes overloading: is it possible to make compiler see which one to use based on template?
我已经创建了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
没有给你的东西
相关文章:
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 替换密码:哪一个?
- For-loop或std::any_of,我应该使用哪一个?
- 哪一个是最好的方法类或结构?在 C++ 中
- 静态常量与常量局部变量,哪一个性能更好
- 一个互斥锁与多个互斥锁.哪一个更适合线程池?
- cv::String 和 std::string:何时使用哪一个以及必须同时使用两者?
- 哪一个对物体检测更快?
- 哪一个更适合存储字符、矢量<char>或字符串?
- Visual C++ 和 gcc 之间从 std::isblank 返回不一致.哪一个错了
- 在 C 和 C++ 编程中使用哪一个更好?
- 这两者中的哪一个是实现标头的正确方法
- 带大小参数和不带大小参数的"运算符删除":当两者都可用时,选择哪一个?
- C++编译器在封装行为上存在分歧 - 哪一个做对了?
- 对于初学者来说,我应该学习" c or c++ "之间的哪一个才能使用Arduino UNO?
- MongoC ++驱动程序BSON构造:基于流与基于字符串解析.哪一个性能更好?
- 这些指针中的哪一个需要免费()或delete()
- 哪一个先走? '