c++ - 如何专门化具有迭代器特征的函数模板?
问题描述
template <typename ForwIt>
typename std::iterator_traits<ForwIt>::value_type
foo(ForwIt begin, ForwIt end, double bar)
{
using value_type = typename std::iterator_traits<ForwIt>::value_type;
// value_type is the type of the values the iterator ForIt points to
value_type baz;
// Do stuff with the values in range [begin, end).
// And modify baz;
return baz;
}
int main()
{
std::vector<int> numbers;
for (int i = 0; i < 10; ++i)
numbers.push_back(i);
const std::vector<int> v0(numbers.begin(), numbers.end());
const std::vector<float> v1(numbers.begin(), numbers.end());
std::cout << foo(v0.begin(), v0.end(), 0.1) << ' ' <<
foo(v1.begin(), v1.end(), 0.1) << std::endl;
return 0;
}
foo
函数的返回类型的value_type
推导是推导出来的。现在这适用于所有数字类型。
但我希望返回类型(和类型baz
)是推导整数类型的double
时候。value_type
在这种情况下如何进行专业化?
解决方案
您可以避免专门化,或编写另一个重载。相反,您可以使用conditional_t
根据某些条件选择特定类型
// alias for convenience
using T = typename std::iterator_traits<ForwIt>::value_type;
// if T is int, value_type is double, otherwise it's just T
using value_type = std::conditional_t<std::is_same_v<T, int>, double, T>;
对于返回类型,只需使用auto
,就会从 的类型推导出正确的类型baz
。
这是一个演示
推荐阅读
- python - 为什么此示例中的图形大小(y 轴)会波动?
- rdbms - 有没有办法计算存储过程的标识符?
- c++ - 如何查看对象中的所有数据和字段
- javascript - 使用 createElementNS 添加的 SVG 元素在 DOM 中,但在屏幕上不可见
- salesforce - Apex,SOQL,将结果从数据库添加到列表,错误
- python - 每月和前几个月的月份转换
- javascript - 如何通过在引导多重选择器中选择选项来切换地图框中的显示符号?
- java - 带有多个选择选项列表的表单绑定
- python - 列表中最常见的单词,其中包含列表
- github - Github 操作将子模块排除在 .net 构建/测试之外