如何使用函数获得模板-模板参数推导

How to get template template argument deduction working with functions?

本文关键字:参数 何使用 函数      更新时间:2023-10-16

考虑一组类似的函数

template< class Fun >
void A( const Fun& )
{
}
template< class Fun >
void B( const Fun& )
{
}
template< class Fun >
void C( const Fun& )
{
}

设计用于将函数类型作为参数。那么,这完全可以:

template< class T >
void Func( const T& )
{
}
A( Func< int > );
B( Func< int > );
C( Func< int > );

现在我想摆脱重复int temaplate的争论,所以我尝试了这个:

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('error: no matching function for call to 'Helper<int>::A(<unresolved overloaded function type>)')和MSVC10(cannot use function template 'void Func(const T &)' as a function argumentcould not deduce template argument for 'overloaded function type' from 'overloaded function type')上编译。

有人能解释清楚为什么吗?有办法解决这个问题吗?

编辑好的,我理解为什么现在不可能;对于包含变通方法的答案:在实际代码中有很多不同的Func,比如100,而只有大约6个函数,比如a、B和C…

表单template<class> class Fun,无论是作为声明还是作为模板模板参数(就像您所做的那样),都是为模板设计的,而Func不是。这是一个函数模板。它们的形式为template</*parameters*/> Ret foo(/*parameters*/),不允许作为模板模板参数。

一般来说,函数模板不能像类模板那样被操纵。

有一种情况可以省去传递模板参数的需要:

// Deduces that Func<int> is meant
void (*p)(int) = Func;

然后可以将p传递给ABC

(类似地,如果您有一个函数void f(void(*p)(int));,那么形式为f(Func)的调用也可以。)

Func是一个函数模板,因此不能将其作为值传递给函数。

您也不能将其作为模板模板参数传递,因为模板模板参数必须是类模板(而不是函数模板)。

可以传递一个模板模板参数,该参数封装函数模板(例如,从静态成员函数返回其实例化):

template<class T> struct FuncHelper {
    static void (*f())(const T &) { return &(Func<T>); }
};
template<typename T>
struct Helper
{
  template< template< class > class Fun >
  static void A()
  {
    A( Fun<T>::f() );
  }
};
Helper<int>::A<FuncHelper>();

虽然可以使用类模板作为模板参数,例如

template <typename> class Foo;
template <template <typename> class C> void doit() { /* ...*/ };
doit<Foo>();

(语义上)不可能使用函数模板作为模板参数(没有"函数模板指针")。通常的方法是使用功能对象,例如

template <typename T>
struct Func
{
  void operator()(T const &) const
  {
     /* ... */
  }
};

template <typename T>
struct helper
{
  template <template <typename> class F>
  static void A()
  {
    A(F<T>);
  }
  // etc
};
typedef helper<int> int_helper;
int_helper::A<Func>();

如果Func可以声明为具有auto类型参数的lambda(使用C++14的泛型lambda),则ABC的定义不需要更改,并且可以在不指定参数类型的情况下调用:

auto Func = [](auto const&)
{
};
A(Func);
B(Func);
C(Func);

实时演示