简体   繁体   English

如何专门化具有迭代器特征的 function 模板?

[英]How to specialize a function template with iterator traits?

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;
}

Deduction of the return type of foo function is whatever the value_type is is deduced to. foo function 的返回类型的推导就是value_type的推导。 Now this works for all numeric types.现在这适用于所有数字类型。

But I want the return type (and type of baz ) to be double when value_type is deduced integer type.但是我希望在推导value_type integer 类型时返回类型(和baz的类型)是double的。 How can I make a specialization in this case?在这种情况下如何进行专业化?

You can avoid specializations, or writing another overload.您可以避免专门化,或编写另一个重载。 Instead, you can use conditional_t to select a specific type according to some condition相反,您可以根据某些条件使用conditional_t到 select 特定类型

// 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>;

For the return type, simply use auto , and the correct type will be deduced from the type of baz .对于返回类型,只需使用auto ,从baz的类型中会推断出正确的类型。

Here's a demo这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM