我正在使用标准容器,例如 vector 和 pair,使用自定义类型作为模板参数。大多数情况下,这些模板类型是 const 限定的,如:
std::vector<const std::pair<const customType, const double>>
Hash() 运算符和比较运算符 == 和 < 已经定义。
当我将这些值传递给标准库函数(如 partial_sort_copy、partial_sort 和 erase)时,问题就出现了。出于某种原因,这些函数最终会尝试对给定类型进行赋值,最终由于常量而导致编译失败。
有什么方法可以将常量强制转换为 vector 和 pair 的模板类型吗?即,类型转换 vector<const myType>
至 vector<myType>
.
提前致谢。
编辑:现在有冲突的最小示例代码!
// Non-working code:
std::vector<const std::pair<const int, const double>> list{ { 3, 3. }, { 2, 2. }, { 1, 1. }, { 0, 0. } };
std::partial_sort(list.begin(), list.begin() + 2, list.end(), [](const std::pair<const int, const double>& x, const std::pair<const int, const double>& y){ return x.first < y.first; });
// This works, actually:
std::vector<std::pair<int, double>> list{ { 3, 3. }, { 2, 2. }, { 1, 1. }, { 0, 0. } };
std::partial_sort(list.begin(), list.begin() + 2, list.end(), [](const std::pair<int, double>& x, const std::pair<int, double>& y){ return x.first < y.first; });
标准库不喜欢我的代码的什么地方?
最佳答案
这种 const 类型的容器是未定义的行为。 std::vector<const T>
使用 std::allocator<const T>
作为其分配器类型,并且分配器要求规定值类型必须是非常量对象类型。
即使忽略...
Is there any way to cast the consts out on template types for vector and pair? I.e., casting
vector<const myType>
tovector<myType>
.
没有。
一般some_template<T>
和 some_template<const T>
是完全不相关的类型,所以你不能在它们之间转换。与 const some_template<T>
不同,它们之间没有有效的转换和 some_template<T>
.
所以你应该停止使用 const 对象的 vector 。而是使用非常量对象的 const vector 。
关于模板类型参数的 C++ 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37027662/