我已经看了很长时间了。我不明白是什么在困扰它。给我问题的最小代码如下所示。我评论发生错误的行。编译错误跟在代码后面。
#include <map>
#include <cstdlib>
#include <cstdint>
template<std::size_t D>
class myclassA{
private:
std::array<std::string, D> a;
std::map<std::string, std::size_t> a_type_num;
std::array<std::size_t, D> a_dims;
// used to initialize a_type_num
inline std::map<std::string, std::size_t> return_type_dims() const{
std::map<std::string, std::size_t> temp;
for(auto const &s: a)
temp.emplace(s, 0);
for(auto const &s: a)
temp[s]++;
return temp;
};
// used to initialize a_dims
inline std::array<std::size_t, D> return_site_dims() const{
std::array<std::size_t, D> temp;
for(int i=0; i<D; i++)
temp[i] = a_type_num[a[i]]; // ERROR!!!
return temp;
};
public:
// constructor
myclassA(const std::array<std::string,D> &user) : a(user)
, a_type_num(return_type_dims())
, a_dims(return_site_dims())
{};
};
int main(int argc, char *argv[]){
myclassA<4> co({"d","d","p","p"});
return 0;
}
编译时出现错误:
src/main.cpp(32): error: no operator "[]" matches these operands
operand types are: const std::map<std::__cxx11::string, std::size_t, std::less<std::__cxx11::string>, std::allocator<std::pair<const std::__cxx11::string, std::size_t>>> [ const std::__cxx11::string ]
temp[i] = a_type_num[a[i]];
^
detected during:
instantiation of "std::array<std::size_t={unsigned long}, D> myclassA<D>::return_site_dims() const [with D=4UL]" at line 40
instantiation of "myclassA<D>::myclassA(const std::array<std::__cxx11::string, D> &) [with D=4UL]" at line 45
另一方面,像这样的东西编译得很好(我的意思是代码什么都不做,但它编译):
#include <map>
#include <cstdlib>
#include <cstdint>
int main(int argc, char *argv[]){
// myclassA<4> co({"d","d","p","p"});
std::array<std::string, 10> a;
std::map<std::string, std::size_t> a_type_num;
std::array<std::size_t, 10> temp;
for(int i=0; i<10; i++)
temp[i] = a_type_num[a[i]];
return 0;
所以我的问题是:它为什么抱怨no operator "[]" matches these operands
呢?