指定模板中的函数接口

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

Specify function interface in template

问题

  1. 我有一个模板类,它转发一个函数:
  2. template <class T>
  3. class Foo{
  4. template <typename Func, typename... Args>
  5. void Bar(Func function, Args&&... args) {
  6. T t;
  7. (t->*function)(std::forward<Args>(args)...);
  8. }
  9. }
  10. 这个可以工作,但是有没有办法检查 `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. 在签名中指定这一点并不是真正必要的,因为它将在错误的情况下无法编译,但您可以像这样指定成员函数指针:
  2. template <class T>
  3. class Foo{
  4. public:
  5. template <typename Func, typename... Args>
  6. void Bar(Func T::*function, Args&&... args) {
  7. T t;
  8. (t.*function)(std::forward<Args>(args)...);
  9. }
  10. };
  1. 并调用它:
  2. struct S
  3. {
  4. void func(int) {}
  5. };
  6. void freeFunc(int) {}
  7. int main()
  8. {
  9. Foo<S> f;
  10. f.Bar(&S::func, 42); //OK
  11. //f.Bar(&freeFunc, 42); //ERROR
  12. }

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-2.html
匿名

发表评论

匿名网友

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

确定