我定义了一组函数模板:

template < typename type >
void foo ( type object )
{
    //  foo the object
}

template < typename type >
void bar ( type object )
{
    //  bar the object
}

template < typename type >
void baz ( type object )
{
    //  baz the object
}

现在我想定义一个函数模板,它接受一个指向上述任何函数的指针。
    template < /* ??? */ , typename T , typename... TT >
    void for_each ( T parameter , TT... other parameters )
    {
       // process the first parameter using the function pointer defined by the first template parameter
       // recursice call to for_each
    }

声明第一个模板参数的正确方法是什么?

P.S.我确实知道有一种解决方法可以将前三个函数分别包装在一个类中并使它们成为静态。我只是想知道是否有直接的方法来解决这个问题。

最佳答案

struct foo_overload_set_t {
  template<typename... Ts>
  auto operator()(Ts&&... ts) const
  -> decltype( foo(std::forward<Ts>(ts)...) ) {
      return ( foo(std::forward<Ts>(ts)...) );
  }
};
static const foo_overload_set_t foo_overload_set;

现在 foo_overload_set 是一个单独的对象,可以像一个函数一样对待,并且在调用时根据传入的参数对函数 foo 进行重载解析。

即,foo( a, b, c, d, e ) 运行相同的代码,并为任何参数集给出与 foo_overload_set( a, b, c, d, e ) 完全相同的结果。

但是 foo_overload_set 是一个对象,而 foo 是一组不确定的函数,根据用于调用它的参数动态创建。

我们可以将所述对象传递给您的 for_each :
template<typename OverloadSet>
void for_each( OverloadSet ) {} // do nothing

template < typename OverloadSet , typename T , typename... TT >
void for_each ( OverloadSet overload, T&& parameter , TT&&... other_parameters )
{
   overload( std::forward<T>(parameter) );
   for_each( overload, std::forward<TT>(other_parameters)... );
}

像这样调用:
for_each( foo_overload_set, a, b, c, d, e );

它继续在 foo 上调用 a ,然后在 b 上,然后在 c 上,等等。

关于c++ - 模板函数指针作为模板参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21523874/

10-11 23:06
查看更多