作为模板参数的模板函数

Ale*_*sky 0 c++ c++20

如何使下面的伪代码编译?

#include <vector>

template <class T>
void CopyVector() { std::vector<T> v; /*...*/}

template <class T>
void CopyVectorAsync() { std::vector<T> v; /*...*/}

template <template <class> void copy()>
void Test()
{
    copy<char>();
    copy<short>();
    copy<int>();
}

int main()
{
    Test<CopyVector>();
    Test<CopyVectorAsync>();
}
Run Code Online (Sandbox Code Playgroud)

CopyVectorCopyVectorAsync是使用不同算法复制某些类型元素向量的函数TTest函数调用具有不同元素类型的给定复制函数。main函数调用CopyVectorCopyVectorAsync所有元素类型。

Cal*_*eth 7

您不能拥有接受函数模板的模板模板参数,而只能接受类模板。幸运的是,我们可以创建一个看起来更像函数的类。

#include <vector>

template <class T>
struct CopyVector { void operator()() { std::vector<T> v; /*...*/} };

template <class T>
struct CopyVectorAsync{ void operator()() { std::vector<T> v; /*...*/} };

template <template <class> class copy>
void Test()
{
    copy<char>{}();
    copy<short>{}();
    copy<int>{}();
}

int main()
{
    Test<CopyVector>();
    Test<CopyVectorAsync>();
}
Run Code Online (Sandbox Code Playgroud)