[我正在尝试编写一种适用于迭代器的算法(类似于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算法,但是我需要编写一种特殊的算法,以在迭代器指向...时采取不同的行动]]
std::iterator_traits
约束“专用”模板。您还需要一个助手来检查迭代器特征返回的std::iterator_traits
是否是value_type
的特殊化。该代码是std::complex