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

foo function 的返回類型的推導就是value_type的推導。 現在這適用於所有數字類型。

但是我希望在推導value_type integer 類型時返回類型(和baz的類型)是double的。 在這種情況下如何進行專業化?

您可以避免專門化,或編寫另一個重載。 相反,您可以根據某些條件使用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>;

對於返回類型,只需使用auto ,從baz的類型中會推斷出正確的類型。

這是一個演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM