我可以这样做:
std::vector<int> vec = { 1, 2, 3, 4, 5 };但我不能这样做:
std::vector<const type_info&> ClassBlackList = { typeid(Class1), typeid(Class2) };编译器说指向引用的指针非法,或者
std::vector<const type_info> ClassBlackList = { typeid(Class1), typeid(Class2) };编译器说Error C2338 C++标准禁止常量元素的容器,因为分配器的格式不正确。
或
std::vector<type_info> ClassBlackList = { typeid(Class1), typeid(Class2) };编译器说: Error C2280 'type_info::type_info(const type_info &)':试图引用已删除的函数
我也不能做push_back。有一个向量或type_info列表的解决方案是什么?
发布于 2021-08-05 12:28:47
您可以使用指针
std::vector<const std::type_info*> v = { &typeid(Class1), &typeid(Class2) };这是有效的,因为typeid返回对具有静态存储持续时间的对象的引用。
发布于 2021-08-05 12:33:23
由于几个基本原因,你不能有一个引用的向量。C++根本不是这样工作的。但是,您可以使用std::reference_wrapper来获得几乎相同的结果:
#include <functional>
#include <vector>
#include <typeinfo>
class A {
};
int main()
{
std::vector<std::reference_wrapper<const std::type_info>> avec;
auto &t=typeid(A);
avec.push_back(t);
const std::type_info &i=avec[0];
return 0;
}发布于 2021-08-05 12:35:27
你不能有引用数组,所以你可以把它们包装在std::reference_wrappers中:
#include <functional>
#include <typeinfo>
#include <vector>
std::vector<std::reference_wrapper<const std::type_info>> ClassBlackList = {
typeid(Class1),
typeid(Class2)
};名称ClassBlackList意味着您将对其进行大量搜索,并且列表中的元素必须是唯一的。在这种情况下,您可能希望使用std::set。
示例:
#include <functional>
#include <iostream>
#include <typeinfo>
#include <set>
struct Class1 {};
struct Class2 {};
struct Class3 {};
struct comp { // a functor to compare reference wrapped type_info's
std::size_t operator()(const std::reference_wrapper<const std::type_info>& lhs,
const std::reference_wrapper<const std::type_info>& rhs) const
{
return std::less<const std::type_info*>{}(&lhs.get(), &rhs.get());
}
};
int main() {
std::set<std::reference_wrapper<const std::type_info>, comp> ClassBlackList = {
typeid(Class1),
typeid(Class2)
};
// try to insert typeid(Class3) twice, it only succeeds the first time
auto[it1, inserted1] = ClassBlackList.insert(typeid(Class3));
std::cout << "inserted: " << inserted1 << '\n';
auto[it2, inserted2] = ClassBlackList.insert(typeid(Class3));
std::cout << "inserted: " << inserted2 << '\n';
}输出:
inserted: 1
inserted: 0https://stackoverflow.com/questions/68666574
复制相似问题