Reputation: 3279
A puzzling question to C++ template and type conversion is shown below... To make my life easier, I defined a template class to model a one-to-one relationship using a class BiMap:
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <string>
template<class T1, class T2>
class BiMap {
public:
T2& operator[] (T1& t1) {
return d1[t1];
}
T1& operator[] (T2& t2) {
return d2[t2];
}
private:
std::map<T1, T2> d1;
std::map<T2, T1> d2;
};
int main(int argc, char *argv[])
{
BiMap<std::string, int> m;
m["1"] = 2;
m[2] = 3;
printf("%d", m["1"]);
printf("%d", m[2]);
return 0;
}
But I get this compiling error:
testPedigree.cpp:45: error: no match for ‘operator[]’ in ‘m["1"]’
testPedigree.cpp:16: note: candidates are: T2& BiMap<T1, T2>::operator[](T1&) [with T1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, T2 = int]
testPedigree.cpp:19: note: T1& BiMap<T1, T2>::operator[](T2&) [with T1 = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, T2 = int]
I was expecting C++ will automatically cast const char* to std::string, as I asked the question in this post: Why I can use const char* as key in std::map<std::string, int>
Upvotes: 1
Views: 384
Reputation: 168696
Your code tries to bind a non-const
reference to a temporary (namely, the std::string
which is implicitly created from your const char[]
). Only const
references can be bound to temporaries.
Try:
T2& operator[] (const T1& t1) {
return d1[t1];
}
T1& operator[] (const T2& t2) {
return d2[t2];
}
You have some other trivial bugs in your sample. Here is a corrected, tested program:
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <string>
template<class T1, class T2>
class BiMap {
public:
T2& operator[] (const T1& t1) {
return d1[t1];
}
T1& operator[] (const T2& t2) {
return d2[t2];
}
private:
std::map<T1, T2> d1;
std::map<T2, T1> d2;
};
int main(int argc, char *argv[])
{
BiMap<std::string, int> m;
m["1"] = 2;
m[2] = "3";
printf("%d", m["1"]);
printf("%s\n", m[2].c_str());
return 0;
}
Upvotes: 3