nullptr作为boost::any映射的标志值

nullptr as flag value for boost::any map

本文关键字:标志 映射 any 作为 boost nullptr      更新时间:2023-10-16

如果我使用boost::any设置一个通用容器映射,并使用C++11中的新nullptr作为类似于isset()类型操作的初始化值,是否存在任何潜在的陷阱?

例如:

std::map<std::string, boost::any> map;
map["A"] = nullptr;
map["B"] = nullptr;
map["C"] = nullptr;
map["D"] = nullptr;
map["A"] = 1;
map["C"] = 3;
// assume error checking, other types, etc.
for(auto k : map) {
    if (k.second.type() != typeid(nullptr)) {
        std::cout << k.first << " : " << boost::any_cast<int>(k.second) << std::endl;
    }
}

在C++11之前,我将boost::any封装在一个带有bool isset的结构中,但这似乎是可行的。有陷阱吗?

我看不到任何陷阱(除了要小心将其专门设置为nullptr_t,而不是任何其他指针类型);但为什么不让它为空,并用它的empty()成员函数检查它呢?