在模板中指定函数接口

huangapple go评论140阅读模式
英文:

Specify function interface in template

问题

我有一个模板类,用于转发函数:

template <class T>
class Foo{
  template <typename Func, typename... Args>
  void Bar(Func function, Args&&... args) {
   T t;
   (t->*function)(std::forward<Args>(args)...);
  } 
}

这个代码是可以工作的,但是有没有办法检查 Func 是否包含在 T 的接口中,即 T::Func?现在,如果我输入一个错误的函数,编译器会报错说 t->*function 不存在,但是我想在函数接口中指定它应该是一个 T::Func。然而,我似乎无法找到正确的语法。

英文:

I have a template class that forwards a function:

template &lt;class T&gt;
class Foo{
  template &lt;typename Func, typename... Args&gt;
  void Bar(Func function, Args&amp;&amp;... args) {
   T t;
   (t-&gt;*function)(std::forward&lt;Args&gt;(args)...);
  } 
}

This works, but is there any way to check whether Func is contained in the interface of T, so T::Func? Now, if I enter a wrong function the compiler would complain that t-&gt;*function doesn't exist, but I would like to specify in the function interface that it should be a T::Func. However I can't seem to get the syntax for this right.

答案1

得分: 3

这不是真的必要在签名中指定这一点,因为它无论如何都会在错误的情况下编译失败,但你可以像这样指定成员函数指针:

template <class T>
class Foo{
public:
  template <typename Func, typename... Args>
  void Bar(Func T::*function, Args&&... args) {
   T t;
   (t.*function)(std::forward<Args>(args)...);
  } 
};

调用它的方式如下:

struct S
{
    void func(int) {}
};
void freeFunc(int) {}

int main()
{
    Foo<S> f;
    f.Bar(&S::func, 42); //OK
    //f.Bar(&freeFunc, 42); //ERROR
}

Compiler Explorer

英文:

It's not really necessary to specify this in the signature, since it will fail to compile for the wrong cases anyway, but you could specify member function pointers like this:

template &lt;class T&gt;
class Foo{
public:
  template &lt;typename Func, typename... Args&gt;
  void Bar(Func T::*function, Args&amp;&amp;... args) {
   T t;
   (t.*function)(std::forward&lt;Args&gt;(args)...);
  } 
};

And to call it:

struct S
{
    void func(int) {}
};
void freeFunc(int) {}

int main()
{
    Foo&lt;S&gt; f;
    f.Bar(&amp;S::func, 42); //OK
    //f.Bar(&amp;freeFunc, 42); //ERROR
}

Compiler Explorer

huangapple
  • 本文由 发表于 2023年8月9日 16:06:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定