简体   繁体   English

模板 function 作为模板参数

[英]A template function as a template argument

How to make the pseudo code below compile?如何使下面的伪代码编译?

#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 and CopyVectorAsync are the functions that copy some vector of elements of type T using different algorithms. CopyVectorCopyVectorAsync是使用不同算法复制T类型元素的某些向量的函数。 Test function calls a given copy functions with different element types. Test function 调用具有不同元素类型的给定复制函数。 main function calls CopyVector and CopyVectorAsync for all the element types. main function 为所有元素类型调用CopyVectorCopyVectorAsync

You can't have a template template parameter that accepts function templates, only class templates.您不能有一个模板模板参数接受 function 模板,只有 class 模板。 Luckily we can make a class that looks rather like a function.幸运的是,我们可以制作一个看起来很像 function 的 class。

#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>();
}

You cannot pass overload set or functions template as (template) parameter.您不能将重载集或函数模板作为(模板)参数传递。

You can pass template template parameter for classes:您可以为类传递模板模板参数:

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>();
}

or pass functor with template method.或通过模板方法传递函子。

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)>();
}

Passing parameter by regular argument might allow "simpler" syntax:通过常规参数传递参数可能允许“更简单”的语法:

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>(); });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM