我如何专门针对指向复杂值的迭代器算法?

问题描述 投票:0回答:1

[我正在尝试编写一种适用于迭代器的算法(类似于STL算法,但是我需要编写一种算法的特殊性,以在迭代器指向complex值与常规double值时有所不同。] >

这是一个基本示例:

#include <complex>
#include <iostream>
#include <vector>

using namespace std;

template <typename InputIt>
void DoSomething(InputIt first, InputIt last)
{
    cout << "Regular Double" << endl;

    for (; first != last; ++first)
    {
        cout << *first << endl;
    }
}

//// Specialize the template for containers holding complex values
//template <typename InputItToComplex>
//void DoSomething(InputItToComplex first, InputItToComplex last)
//{
//  cout << "Complex Double" << endl;
//
//  for (; first != last; ++first)
//  {
//      cout << *first << endl;
//  }
//}

int main()
{
    vector<double> values = { 1.5, 2.2, 3.1, 4.5, 5.1, 6.9, 7.1, 8.9 };

    // Call the regular template
    DoSomething(values.begin(), values.end());

    vector<complex<double>> cplx_values = { complex<double>{1.4, 2.1}, complex<double>{2.2, 3.5}, complex<double>{7.1, 9.1 } };

    // Need to call the complex specialized version of the template
    DoSomething(cplx_values.begin(), cplx_values.end());
}

我如何编写专业化名称,以便当我有一个包含complex值的容器时,它将自动使用complex专业化版本?上面注释掉的代码显然不起作用,因为它只会导致两个模棱两可的定义。

我正在尝试编写一种适用于迭代器的算法(类似于STL算法,但是我需要编写一种特殊的算法,以在迭代器指向...时采取不同的行动]]

c++ templates iterator template-specialization overload-resolution
1个回答
2
投票
您可以使用SFINAEstd::iterator_traits约束“专用”模板。您还需要一个助手来检查迭代器特征返回的std::iterator_traits是否是value_type的特殊化。该代码是

std::complex

© www.soinside.com 2019 - 2024. All rights reserved.