如何获取模板模板参数扣除使用函数? [英] How to get template template argument deduction working with functions?
问题描述
考虑一组函数,例如
template< class Fun >
void A( const Fun& )
{
}
template< class Fun >
void B( const Fun& )
{
}
template< class Fun >
void C( const Fun& )
{
}
设计为将函数类型作为参数。
然后,这是完全确定:
designed to take function types as arguments. Then, this is perfectly ok:
template< class T >
void Func( const T& )
{
}
A( Func< int > );
B( Func< int > );
C( Func< int > );
现在我想摆脱重复 int
temaplate argument所以我试试这个:
Now I wanted to get rid of repeating the int
temaplate argument so I tried this:
template< class T >
struct Helper
{
template< template< class > class Fun >
static void A( Fun< T >& f )
{
A( f );
}
template< template< class > class Fun >
static void B( Fun< T >& f )
{
B( f );
}
...
};
typedef Helper< int > IntHelper;
IntHelper::A( Func ); //error
IntHelper::B( Func ); //
IntHelper::C( Func ); //
但是这无法在gcc 4.5.1(' :没有匹配的函数调用'Helper< int> ::(<未解决的重载函数类型>)'
)和MSVC10(不能使用函数模板'void Func const T&)'作为函数参数
和无法从'overloaded function type'中推导出'overloaded function type'的模板参数
)。
however this fails to compile on gcc 4.5.1 ('error: no matching function for call to 'Helper<int>::A(<unresolved overloaded function type>)'
) and MSVC10 (cannot use function template 'void Func(const T &)' as a function argument
and could not deduce template argument for 'overloaded function type' from 'overloaded function type'
).
有人可以解释原因,并且有办法解决这个问题吗?
Can someone explain why exactly, and is there a way around this?
强>确定我明白为什么现在是不可能的;对于包含一个解决方法的答案:在实际代码中有很多不同的 Func
s,说100,而只有大约6功能像A,B和C .. 。
edit ok I understand why it is not possible now; for the answers containing a workaround: in the actual code there are a lot of different Func
s, say 100, while there's only about 6 function like A, B and C...
推荐答案
形式 template< class>无论是作为声明还是作为模板模板参数(类似于),Fun类 c只是为类模板设计的,
Func
不是。它是一个函数模板。那些具有
模板< / * parameters * /> Ret foo(/ * parameters * /)
,它们不允许作为模板模板参数。
The form template<class> class Fun
, whether as a declaration or as a template template parameter (like you have), is designed for class templates only, which Func
isn't. It's a function template. Those have the form template</*parameters*/> Ret foo(/*parameters*/)
, and they aren't allowed as template template parameters.
一般来说,函数模板不能被操作
Generally speaking function templates cannot be manipulated as much as class templates.
有一种情况,你可以不必传递模板参数:
There is one situation where you can be spared the need to pass template parameters around:
// Deduces that Func<int> is meant
void (*p)(int) = Func;
然后,您可以将 p
传递给 A
, B
和 C
。
Then you can pass p
to A
, B
and C
.
(类似地,如果你有一个函数 void f(void(* p)(int));
$ c> f(Func)很好。)
(Similarly if you have a function void f(void(*p)(int));
then a call of the form f(Func)
is fine.)
这篇关于如何获取模板模板参数扣除使用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!