模板类型参数的 C++ 常量

标签 c++ templates vector constants std-pair

我正在使用标准容器,例如 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> to vector<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/

相关文章:

c++ - 扁平化二维 vector 的通用方法

css - 用于网站开发的 Gimp vs Inkscape vs Fireworks?

c++ - std::vector<std::unique_ptr<T>> 有更好的替代方案吗?

C++ 堆栈模板

C++ - 使用 Visual Studio 的成员函数声明

c++ - 使用 RAX/EAX/AX/AL/AH 寄存器作为目的地时,进位加法是否更快?

c++ - 在 Windows 10 VS2015 上构建 Boost - 无法打开 *.lib

c++ - 大型模板类样板代码

c++ - 2d std::vector 连续内存?

c++ - 插入链表的 vector 元素?