微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用迭代器特征专门化函数模板?

如何解决如何使用迭代器特征专门化函数模板?

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的类型中推导出正确的类型。

这是一个demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。