我的Boost标头的本地版本(1.56.0)定义了以下函数boost/any.hpp,逐字复制:
// Note: The "unsafe" versions of any_cast are not part of the
// public interface and may be removed at any time. They are
// required where we know what type is stored in the any and can't
// use typeid() comparison, e.g., when our types may travel across
// different shared libraries.
template<typename ValueType>
inline ValueType * unsafe_any_cast(any * operand) BOOST_NOEXCEPT
{
return &static_cast<any::holder<ValueType> *>(operand->content)->held;
}
template<typename ValueType>
inline const ValueType * unsafe_any_cast(const any * operand) …Run Code Online (Sandbox Code Playgroud) #include <iostream>
#include <any>
#include <string>
#include <vector>
#include <map>
using namespace std;
string AnyPrint(const std::any &value)
{
cout << size_t(&value) << ", " << value.type().name() << " ";
if (auto x = std::any_cast<int>(&value)) {
return "int(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<float>(&value)) {
return "float(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<double>(&value)) {
return "double(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<string>(&value)) {
return "string(\"" + (*x) + "\")"; …Run Code Online (Sandbox Code Playgroud) 这个脚本
#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)
抱歉,如果这听起来有点愚蠢
出于调试目的,我正在编写一个函数,该函数迭代任何类型的可选变量向量以检查哪些变量已初始化,但对has_value()所有变量的检查都返回了true,尽管尚未为其中某些变量分配任何值。
我很感激任何帮助指出我的误解,因为我是 C++ 新手。代码如下。请注意,当注释行被取消注释时,if 语句会发现该变量没有值。
#include <iostream>
#include <optional>
#include <any>
bool SimpleCheck(std::vector<std::optional<std::any>> toCheck)
{
bool res = false;
for (int i = 0; i < toCheck.size(); ++i)
{
// toCheck[i] = std::nullopt;
if (!toCheck[i].has_value())
{
std::cout << "item at index " << i << " had no value\n";
res = true;
}
}
return res;
}
int main()
{
std::optional<int> i = 5;
std::optional<std::string> str;
std::optional<double> doub = std::nullopt;
bool check = SimpleCheck({i, str, doub}); …Run Code Online (Sandbox Code Playgroud) 以下代码
using vptr = std::vector<std::unique_ptr<int>>;
auto m = std::unordered_map<int, std::any>{};
m.try_emplace(0, move(vptr{}));
Run Code Online (Sandbox Code Playgroud)
无法编译,抱怨使用的已删除副本构造函数unique_ptr。在模板参数中替换std::any为之后,vptr此代码将编译,因此问题显然与any
如何强制std::any移动而不是复制?