Java varargs equivalent in C++
Java varargs equivalent in C++
我有一个用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");
}
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- Tensorflow Hub in C++
- Centos7 g++ "to_string is not in a member of std"
- InitializeCriticalSectionEx Not Located In KERNEL32.Dll
- 将 lambda 表达式传递给 std::function in C++
- @CPPFLAGS@在 Makefile.in 中意味着什么?
- std::async from std::async in windows xp