有没有可能;便秘“;没有hacks的'std::pair'字段? C++中编译以下代码: std::pair <int, int> x; static_cast <std::pair <const int, int>*> (&x); std::对x; 静态投影(&x);
给出一个错误:有没有可能;便秘“;没有hacks的'std::pair'字段? C++中编译以下代码: std::pair <int, int> x; static_cast <std::pair <const int, int>*> (&x); std::对x; 静态投影(&x);,c++,casting,constants,std-pair,C++,Casting,Constants,Std Pair,给出一个错误: error: invalid static_cast from type ‘std::pair<int, int>*’ to type ‘std::pair<const int, int>*’ 错误:从类型“std::pair*”到类型“std::pair*”的静态\u转换无效 我或多或少理解为什么会发生这种情况,因为在模板参数列表中限定类型的cv原则上会给出“不兼容”的结果。即使在这种情况下它并没有,编译器也并没有办法知道它 无论如何,有没有一种非黑
error: invalid static_cast from type ‘std::pair<int, int>*’ to type ‘std::pair<const int, int>*’
错误:从类型“std::pair*”到类型“std::pair*”的静态\u转换无效
我或多或少理解为什么会发生这种情况,因为在模板参数列表中限定类型的cv原则上会给出“不兼容”的结果。即使在这种情况下它并没有,编译器也并没有办法知道它
无论如何,有没有一种非黑客的方式来执行这种转换?我对使用reinterpret\u cast
处理任何事情都很谨慎,因为我以前遇到过类型双关语问题。另外,我不能使用临时代码,因为这是在性能关键的代码中
编辑:
这就是我正在做的。我正在实现一个与
std::unordered\u map
兼容的自定义容器接口。因此,其值\u类型
需要是对
。对于某些优化,我需要在内部将值存储为pair
,而不使用const
。但是,如果我这样做,我就不能(没有reinterpret\u cast
)在容器上实现迭代器,因为迭代器需要返回对值的引用,而我只有对这些非常量对的引用。这不是强制转换,但您可以执行以下操作:
std::pair<int, int> x;
std::pair<const int, int> y( x );
std::对x;
std::对y(x);
这应符合§20.2.2/4的规定。如何:
template< typename T1, typename T2 >
struct ref_pair {
public:
typedef const T1 first_type;
typedef T2 second_type;
ref_pair(first_type& f, second_type& s) : f_(f), s_(s) {}
first_type& first() {return *f_;}
second_type& second() {return *s_;}
private:
first_type* f_;
second_type* s_;
};
不过感觉脏兮兮的。我现在要洗手了。您打算使用什么样的用例?我很难理解这是如何使用的。你可以保留两个这样的结构,并定义一个从较少常数到较多常数的转换函数。@James McNellis:我猜他有一个函数返回一对,另一个函数取一对*@James McNellis:Maps将
对作为其值类型
,所以我需要(或者似乎需要,也许还有其他选择)进行一些优化。@doublep:也许如果你展示你试图优化的代码,它会有所帮助。诀窍是y.second
需要引用与x.second
相同的变量。可能std::对y(x.first,x.second)
可能有效。
std:::pair<const int,int>& rx = reinterpret_cast<std:::pair<const int,int>&>(x);