例如,我有一些功能模板
template <typename T>
void foo(T);
template <typename T>
void bar(T);
// others
Run Code Online (Sandbox Code Playgroud)
我需要将每一个传递给一个算法,该算法将用各种类型调用它,例如
template <typename F>
void some_algorithm(F f)
{
// call f with argument of type int
// call f with argument of type SomeClass
// etc.
}
Run Code Online (Sandbox Code Playgroud)
我无法传递我的函数模板未实例化,但我无法使用任何特定类型实例化它,因为some_algorithm需要使用几种不同类型的参数调用它.
我可以将我的函数模板调整为多态函数对象,例如
struct foo_polymorphic
{
template <typename T>
void operator()(T t)
{
foo(t);
}
};
Run Code Online (Sandbox Code Playgroud)
然后传递给它some_algorithm(foo_polymorphic()).但这需要为我的每个功能模板编写一个单独的适配器.
是否有一个通用的适应函数模板是一个多态函数对象,即一些机制,我可以重新使用的每一个我需要适应的功能模板,而不必为每一个单独声明什么方式?
所以我知道C++有一个名为"模板模板参数"的功能,您可以将类模板作为模板参数传递.例如:
template <typename T>
class vector { ... };
template <template <typename> class container> // this is a template template parameter
class foo { ... };
...
foo<vector> f; // pass the vector template itself as template parameter
Run Code Online (Sandbox Code Playgroud)
功能模板有类似之处吗?即有没有办法将函数模板(例如std::make_pair)作为模板参数传递给类?