Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有可能;便秘“;没有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 - Fatal编程技术网

有没有可能;便秘“;没有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);