为什么简单的bimap(std :: string< - > int)不起作用?

时间:2012-12-05 16:21:14

标签: c++ type-conversion

C ++模板和类型转换的一个令人费解的问题如下所示...... 为了让我的生活更轻松,我定义了一个模板类,使用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;     
}

但是我得到了这个编译错误:

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]

我期待C ++会自动将const char *转换为std :: string,因为我在这篇文章中提出了问题:Why I can use const char* as key in std::map<std::string, int>

1 个答案:

答案 0 :(得分:3)

您的代码尝试将非const引用绑定到临时(即std::string,它是从const char[]隐式创建的)。只有const个引用可以绑定到临时对象。

尝试:

  T2& operator[] (const T1& t1) {
    return d1[t1];
  }
  T1& operator[] (const T2& t2) {
    return d2[t2];
  }

您的样本中还有其他一些琐碎的错误。这是经过纠正的测试程序:

#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;
}