java的varargs是否有C ++ 14的等价物? [英] Is there C++14 equivalent for java's varargs?

查看:87
本文介绍了java的varargs是否有C ++ 14的等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力为我们从Java中了解的varargs找到一个C ++(14)等价物。



我尝试了什么:



我有点(但不完全)了解可变参数模板和函数,所以我认为我想做的是这样的:

 模板< typename ... A> 
void foo(A ... a){ / * ... * / }



现在,虽然这适用于可变数量的参数,但我也希望能够指定A中所有类型应该是哪种类型。例如在Java中可以做到:

  void  oof( int  ... i){ / *   ... * / } 



有没有一种干净的方法可以在C ++ 14中实现这一点?

解决方案

使用Java varags,所有参数都是相同的类型。它与传递数组和它的大小基本相同。



所以你可以改用这样的东西:

  void  foo( int  * arr, size_t  size); 
void foo(std :: vector< int>& arr);



限制模板到特定类型只是模板的意图。但是,有可能之前已经被问: C ++ - 限制可变参数模板参数 - 堆栈溢出 [ ^ ]。


I'm struggling to find a C++ (14) equivalent for the varargs we know from Java.

What I have tried:

I kinda (but not fully) understand variadic templates and functions, so what I think I'd like to do is something like this:

template <typename... A>
void foo(A... a) { /*...*/ }


Now, while this works for a variable amount of parameters, I'd also like to be able to specify of which type all the types in A should be. For example in Java one could do:

void oof(int... i) { /*...*/ }


Is there a clean way to achieve this in C++ 14?

解决方案

With Java varags, all parameters are of the same type. It is basically the same as passing an array and it's size.

So you might use something like this instead:

void foo(int *arr, size_t size);
void foo(std::vector<int>& arr);


Limiting templates to specific types only is just not the intention of templates. But it is possible and has been asked before: c++ - Restrict variadic template arguments - Stack Overflow[^].


这篇关于java的varargs是否有C ++ 14的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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