Java varargs equivalent in C++

Java varargs equivalent in C++

本文关键字:C++ in equivalent varargs Java      更新时间:2023-10-16

我有一个用Java编写的函数,它接受varargs作为参数。我想将该函数移植到C++。我尝试搜索,但我得到的最接近的是使用参数列表的 std::vector。将 varargs 转换为 C++ 的最佳方法是什么?函数如下。

public EventHandlerQueue<T> get (final EventHandler<T> ... handlers)
{
     // Do something with handlers
     return new EventHandlerQueue<T>(handlers)
}  

我想将该函数移植到C++。我试图搜索,但 我得到的最接近的是使用参数列表的 std::vector。

这是完全正确的,也正是Java varags列表的实际内容,只是语法有所不同。

Java

中的varargs是纯语法糖。它被编译器转换为对传递/接收EventHandler<T>数组的函数的调用。

C++11 中最接近的是 std::initializer_list<EventHandler<T>>,您需要将参数封装在一对额外的大括号中:

EventHandlerQueue<T> get(std::initailizer_list<EventHandler<T>> handlers);
obj.get( {EventHandler1, EventHandler2} );
// asuming that `obj` is an object for which the above member is defined.

在 C++03 中没有类似的语法糖,您需要创建一个数组/向量并传递它。由于数组具有静态定义的大小,因此这里最好的选择是传递std::vector<EventHandler<T> >

C++这些是"可变参数模板",正如@chris所说。

  • http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=138
  • http://en.wikipedia.org/wiki/Variadic_templates

维基百科的例子:

template<typename T, typename... Args>
void printf(const char *s, T value, Args... args)
{
    while (*s) {
        if (*s == '%' && *(++s) != '%') {
            std::cout << value;
            ++s;
            printf(s, args...); // call even when *s == 0 to detect extra arguments
            return;
        }
        std::cout << *s++;
    }
    throw std::logic_error("extra arguments provided to printf");
}