如何使下面的伪代码编译?
#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>();
}CopyVector和CopyVectorAsync是使用不同算法复制T类型元素的某些向量的函数。Test函数用不同的元素类型调用给定的复制函数。main函数为所有元素类型调用CopyVector和CopyVectorAsync。
发布于 2022-06-29 13:08:52
不能将重载集或函数模板作为(模板)参数传递。
您可以为类传递模板参数:
template <template <class> class copy>
void Test()
{
copy<char>{}();
copy<short>{}();
copy<int>{}();
}
template <class T>
struct CopyVector
{
void operator()() const{ /*...*/}
};
int main()
{
Test<CopyVector>();
}或者用模板法传递函子。
template <typename copy>
void Test()
{
copy{}.template operator()<char>();
copy{}.template operator()<short>();
copy{}.template operator()<int>();
}
template <class T>
void CopyVector() { /*...*/}
int main()
{
auto lambda = []<typename T>(){ CopyVector<T>(); };
Test<decltype(lambda)>();
}通过常规参数传递参数可能允许“更简单”的语法:
template <typename T>
void Test(T f)
{
f(std::type_identity<char>{});
f(std::type_identity<short>{});
f(std::type_identity<int>{});
}
template <class T>
void CopyVector(std::type_identity<T>) { /*...*/}
int main()
{
Test([]<typename T>(std::type_identity<T>){ CopyVector<T>(); });
}https://stackoverflow.com/questions/72798527
复制相似问题