在模板中指定函数接口

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

Specify function interface in template

问题

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

  1. template <class T>
  2. class Foo{
  3. template <typename Func, typename... Args>
  4. void Bar(Func function, Args&&... args) {
  5. T t;
  6. (t->*function)(std::forward<Args>(args)...);
  7. }
  8. }

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

英文:

I have a template class that forwards a function:

  1. template &lt;class T&gt;
  2. class Foo{
  3. template &lt;typename Func, typename... Args&gt;
  4. void Bar(Func function, Args&amp;&amp;... args) {
  5. T t;
  6. (t-&gt;*function)(std::forward&lt;Args&gt;(args)...);
  7. }
  8. }

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

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

  1. template <class T>
  2. class Foo{
  3. public:
  4. template <typename Func, typename... Args>
  5. void Bar(Func T::*function, Args&&... args) {
  6. T t;
  7. (t.*function)(std::forward<Args>(args)...);
  8. }
  9. };

调用它的方式如下:

  1. struct S
  2. {
  3. void func(int) {}
  4. };
  5. void freeFunc(int) {}
  6. int main()
  7. {
  8. Foo<S> f;
  9. f.Bar(&S::func, 42); //OK
  10. //f.Bar(&freeFunc, 42); //ERROR
  11. }

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:

  1. template &lt;class T&gt;
  2. class Foo{
  3. public:
  4. template &lt;typename Func, typename... Args&gt;
  5. void Bar(Func T::*function, Args&amp;&amp;... args) {
  6. T t;
  7. (t.*function)(std::forward&lt;Args&gt;(args)...);
  8. }
  9. };

And to call it:

  1. struct S
  2. {
  3. void func(int) {}
  4. };
  5. void freeFunc(int) {}
  6. int main()
  7. {
  8. Foo&lt;S&gt; f;
  9. f.Bar(&amp;S::func, 42); //OK
  10. //f.Bar(&amp;freeFunc, 42); //ERROR
  11. }

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:

确定