Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

Passing Variable Number of Arguments with different type - C++

I am coding in C++ and have a few questions regarding the ellipsis:

  1. Is it possible to pass in class or class pointer into the ellipsis?

  2. Basically what I want to do is to pass in variable number of arguments in the type of char* and class. I am using ellipsis currently and trying to figure out how to pass in the class. If ellipsis isn't applicable over here, what are the options available?

I want to let the user to directly call the function using func( params 1, params2, ...) without explicitly assigning the params into a vector or array first before passing the vector or array as argument to the function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should consider that using variadic functions (C-style) is a dangerous flaw. If the objects passed to the function mismatch the type awaited, or if you don't put the exact number of parameters awaited, then you basically have a violent crash at runtime.

In Bjarne Stroustrup C++ In Depth Series - C++ Coding Standards - 101 Rules, Guidelines, And Best Practices by Herb Sutter and Andrei Alexandrescu, chapter 98: Don't use varargs (ellipsis)

I deeply subscribe to @tenfour's proposal:

  • use an std::vector that contains all your parameters.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...