说我有以下代码:模板参数本身是否可以模板化?
#include <iostream>
#include <functional>
template <int func(int)>
struct S : std::unary_function<int, int>
{
int operator()(int x) const
{
return func(x);
}
};
int foo(int x)
{
return x;
}
int main()
{
S<foo> s;
std::cout << s(42) << std::endl;
}
这工作没关系,结束了一个函子,这意味着它可以在其它模板函数中使用的内部的功能的一种方式(如sort
,例如(假设函子有正确的签名))。我不想创造一切可能的回报/参数类型算符结构(抓实我不能),所以我尝试了以下内容:
template <template <typename R, // Make the return type and argument type template parameters!
typename A> R func(A)>
struct S : std::unary_function<R, A>
{
R operator()(A arg) const
{
return func(arg);
}
};
那没有工作; it gave me compilation errors。于是我尝试:
template <typename R, typename A, R func(A)>
struct S : std::unary_function<R, A>
{
R operator()(A arg) const
{
return func(arg);
}
};
其中做工作。不幸的是,我不得不将S
的实例更改为S<int, int, foo> s;
而不是更好的S<foo> s;
。
是它在所有可能的模板化的模板参数,这样我可以做S<foo> s;
,而不是硬编码在S
函数的返回类型和参数类型传递的功能?
我的google-foo无法找到具体的答案。
编辑:现在我想知道这是不可能的。我只是想到“如果foo
是一个重载函数?”据我所知,没有办法知道哪个foo
要使用时说S<foo> s;
,并因此明确指出返回/参数类型是是必要的。这是正确的想法,这是否意味着我的第一个问题的答案是“不,这是不可能的”?
是的,你对我的间接函数调用的担心是正确的...这个代码是超级计算机的模板元编程库。感谢标准的报价! – Cornstalks