【发布时间】:2016-05-04 12:20:05
【问题描述】:
我正在使用标准容器,例如 vector 和 pair,使用自定义类型作为模板参数。大多数情况下,这些模板类型是 const 限定的,如:
std::vector<const std::pair<const customType, const double>>
已经定义了Hash()运算符和比较运算符==和
当我将这些值传递给标准库函数(如 partial_sort_copy、partial_sort 和擦除)时,就会出现问题。出于某种原因,这些函数最终会尝试对给定类型进行分配,最终由于 const 导致编译失败。
有没有办法将 const 转换为 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 值对。也许定义一个 ADL 可用的
swap会有所帮助,但您必须继承std::pair,因为在std中定义任何内容都不是一个好主意。 -
感谢您的回答。我会查一下 ADL。
-
@bipll 完全允许在 std 命名空间中定义函数重载/模板,如
swap和hash。 -
其实我是在 hash
的 operator() 的情况下这样做的 -
@Johan,但 std::swap 没有被 ADL 捕获,嗯?
标签: c++ templates vector constants std-pair