为什么C++编译器将字符串类型识别为char[]

0 c++ c++14

我写了一个关于google::protobuf::Map的函数模板,代码如下:

\n
template <typename K, typename V>\nstruct ContainImpl<google::protobuf::Map<K, V>, K> {\n  static bool contains(const google::protobuf::Map<K, V>& container, const K& value) {\n    return container.find(value) != container.end();\n  }\n};\ntemplate <typename Container, typename T>\nbool Contains(const Container& container, const T& value) {\n  return ContainImpl<Container, T>::contains(container, value);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后,我这样调用该函数:

\n
Contains(*googleMapPtr, "operator_mykey1"); //googleMapPtr is ptr of google::protobuf::Map<string, string>\n
Run Code Online (Sandbox Code Playgroud)\n

最后,编译器将 Contains 的调用识别为

\n
bool Contains(const Container&, const T&) [with Container = google::protobuf::Map<std::basic_string<char>, std::basic_string<char> >; T = char [16]]'\n
Run Code Online (Sandbox Code Playgroud)\n

由于 std::basic_string 和 char [16] 之间的差异,它错过了 ContainImpl 的模板。那么为什么 C++ 编译器将“operator_mykey1”类型识别为 char[16],我该如何处理它。真诚期待答案\xe3\x80\x82

\n

use*_*522 6

因为 C++ 中的字符串文字不是std::string. 它是一个const char适当大小的数组。

如果您希望字符串文字成为std::string,则可以使用operator""sC++14 以来标准库中的用户定义字符串文字运算符:

using namespace std::literals;

//...

Contains(*googleMapPtr, "operator_mykey1"s);
Run Code Online (Sandbox Code Playgroud)

或者写出您想要一个std::string

Contains(*googleMapPtr, std::string("operator_mykey1"));
Run Code Online (Sandbox Code Playgroud)