Bfy*_*uvf 1 c++ unordered-map ostream stdany
这个脚本
#include <iostream>
#include <unordered_map>
#include <any>
using namespace std;
int main() {
unordered_map<int, any> test;
test[5] = "Hey!";
cout << test[5];
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么它不起作用?
candidate function not viable: no known conversion from 'std::__ndk1::unordered_map<int, std::__ndk1::any, std::__ndk1::hash<int>, std::__ndk1::equal_to<int>, std::__ndk1::allocator<std::__ndk1::pair<const int, std::__ndk1::any> > >::mapped_type' (aka 'std::__ndk1::any') to 'const void *' for 1st argument; take the address of the argument with &
basic_ostream& operator<<(const void* __p);
Run Code Online (Sandbox Code Playgroud)
抱歉,如果这听起来有点愚蠢
<<这是因为astd::ostream和的运算符没有定义重载std::any。
<<是为字符串文字、std::strings、数字和一些其他特定对象定义的。std::any这些都不是。
仅仅因为它碰巧实际上包含一个字符串并不会将其变成 astd::string或其他任何东西。仅仅因为你打开车门,进去坐下,或者把你的狗或者一堆杂货放进车里,并不会把你的车变成一个人,或者狗,或者一堆蔬菜。它仍然是一辆汽车,只是里面装了一些东西。
所以没有<<为此定义操作符。这就是您的 C++ 编译器告诉您的:它需要<<为std::ostreamand定义的运算符std::any,但实际上没有。