在C ++可变参数模板中传递变量参数 [英] Passing variable arguments in a C++ variadic template

查看:185
本文介绍了在C ++可变参数模板中传递变量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个模板函数接受变量参数,并调用其他函数的那些参数...

Say I have a template function that accepts variable arguments and calls other functions with those arguments...

template<typename... A> func(int i, A... args)
{
  // do something common

  switch (i)
  {
    case 0: x(args...); break;
    case 1: y(args...); break;
    case 2: z(args...); break;

    default: break; 
  }

  // do something common
}

...而其他函数定义为...

...and the other functions are defined as...

void x(int a, int b);
void y(int a, int b);  // note: takes same args as x()
void z(std::string a);

这不会编译,因为调用带有std :: string参数的func

This doesn't compile because calling func() with a std::string argument will not find a match for x() and y() that takes a std::string argument.

注意,func()使用一些外部标准(参数i的值在这个示例)决定哪个函数传递参数args。

Note that func() uses some external criteria (the value of parameter i in this example) to decide which other function to pass parameter args to.

有没有办法解决这个问题,而不使用像sts:tuple这样的参数args通过?

Is there a way to pull this off without resorting to something like stuffing parameter args into a std:tuple and passing that?

好吧,我想出了一种方法, 。这里是一个示例类来说明...

Ok, I figured out an approach that works well enough for my purposes. Here's an example class to illustrate...

class X
{
  private:

    bool a(int) { return true; }
    bool b(int) { return true; }

    template<typename... A> bool a(const A&...) { return false; }
    template<typename... A> bool b(const A&...) { return false; }

  public:

    template<typename... A> void x(int i, const A&... args)
    {
        if (i == 0)
        {
            a(args...);
        }
        else
        {
            b(args...);
        }
    }
};



<其中参数不是单个int。这解决了我收到的编译器错误,并启用了我正在寻找的更简单的类API。

The variadic template methods for a() and b() will catch any calls made to X.x() where the arguments are not a single int. This resolves the compiler error I was receiving and enables the simpler class API that I was looking for.

推荐答案

template <typename A1>
func(A1 arg1)
{
    x(arg1);
}

template <typename A1, typename A2>
func(A1 arg1, A2 arg2)
{
    y(arg1, arg2);
}

template <typename A1, typename A2, typename A3>
func(A1 arg1, A2 arg2, A3 arg3)
{
    z(arg1, arg2, arg3);
}

(任何附加的通用代码当然可以分解成一个单独的函数,可能是一个可变函数模板。)

(Any additional, common code can of course be factored into a separate, common function, possibly a variadic function template.)

这篇关于在C ++可变参数模板中传递变量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆