如何使下面的伪代码编译?
#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)
CopyVector和CopyVectorAsync是使用不同算法复制某些类型元素向量的函数T。Test函数调用具有不同元素类型的给定复制函数。main函数调用CopyVector和CopyVectorAsync所有元素类型。
您不能拥有接受函数模板的模板模板参数,而只能接受类模板。幸运的是,我们可以创建一个看起来更像函数的类。
#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)
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |