0

I wrote a function template about google::protobuf::Map,code as follows:

template <typename K, typename V>
struct ContainImpl<google::protobuf::Map<K, V>, K> {
  static bool contains(const google::protobuf::Map<K, V>& container, const K& value) {
    return container.find(value) != container.end();
  }
};
template <typename Container, typename T>
bool Contains(const Container& container, const T& value) {
  return ContainImpl<Container, T>::contains(container, value);
}

then,I call the function in this way:

Contains(*googleMapPtr, "operator_mykey1"); //googleMapPtr is ptr of google::protobuf::Map<string, string>

Finally, The compiler recognizes the call of Contains as

bool Contains(const Container&, const T&) [with Container = google::protobuf::Map<std::basic_string<char>, std::basic_string<char> >; T = char [16]]'

because of the diff between std::basic_string and char [16], it miss the template of ContainImpl.so why the C++ compiler recognize the "operator_mykey1" type as char[16], how can i deal with it. Sincerely looking forward to the answer。

273K
  • 29,503
  • 10
  • 41
  • 64
  • See also [What is the datatype of string literal in C++?](https://stackoverflow.com/questions/12517983/) – JaMiT Aug 26 '22 at 03:15
  • For problem see [What is the datatype of string literal in C++?](https://stackoverflow.com/questions/12517983/what-is-the-datatype-of-string-literal-in-c) and for solution see [Why do i can't add an string to an letter of another string?](https://stackoverflow.com/questions/73401155/why-do-i-cant-add-an-string-to-an-letter-of-another-string). – Jason Aug 26 '22 at 04:54
  • Also, refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Aug 26 '22 at 04:55

1 Answers1

6

Because a string literal in C++ is not a std::string. It is an array of const char of the appropriate size.

If you want a string literal to become a std::string, you can use the user-defined string literal operator operator""s from the standard library since C++14:

using namespace std::literals;

//...

Contains(*googleMapPtr, "operator_mykey1"s);

or alternatively write out that you want a std::string:

Contains(*googleMapPtr, std::string("operator_mykey1"));
user17732522
  • 53,019
  • 2
  • 56
  • 105