There is an application in which, when deviations from some parameters occur, it is necessary to report (call the method) to the special module the place where the deviation occurred and the values ​​of some variables. The number and types of these variables is not known in advance and varies from case to case. There are many different cases. The question is, is there any container in std or boost through which you can pass an arbitrary number of elements of an arbitrary type to a function?

def Foo(container): for c in container: print(c) A = ["Text", 14, 99.0004] Foo (A) 

Wrote an example in python. I need to do something like this in C ++, preferably not having a garden again.

  • Foo(...) and pass on what you want :) - Harry
  • @Harry left to read about functions with a variable number of arguments. Thanks for the tip. - mrFieldy
  • @mrFieldy Foo(...) does not allow to transmit anything at all. Functions with a variable number of parameters should not be used at all , since they are not type safe. And if you want to transfer anything in any quantities, use vector<boost::any> . But in the context of such a question, it is frankly unclear why you need C ++ at all if you are trying to cram dynamic typing. - VTT
  • There is also a variadic template. But writing code on it for fans and connoisseurs - KoVadim
  • @VTT I really love C ++ =). - mrFieldy

2 answers 2

Yet it seems to me that perhaps the closest thing to what you want is variable patterns:

 #include <iostream> #include <iomanip> using namespace std; void Foo() {} template<typename T, typename ...Types> void Foo(T a, Types... Args) { std::cout << a << std::endl; Foo(Args...); } int main() { Foo("Hello", 3.14, 824, 'a'); } 
  • You solved my problem. Thank. - mrFieldy
  • Yes, there is nothing, please contact :) - Harry

I now try all three ways (Foo (...), vector and variadic template). The first and really some very insecure canoe. So far, I’ve made it into vector but when casting cout << boost :: any_cast <...> (c) I don’t know what to do so as not to write a huge swich.

 using boost::any; using std::vector; using std::cout; using std::endl; using std::string; void Foo(vector<any>& container) { for (auto &c : container) { if (c.type() == typeid(int)) cout << boost::any_cast<int>(c) << endl; if (c.type() == typeid(double)) cout << boost::any_cast<double>(c) << endl; if (c.type() == typeid(char*)) cout << boost::any_cast<char*>(c) << endl; if (c.type() == typeid(std::string)) cout << boost::any_cast<std::string>(c) << endl; } }; void main() { vector<any> container; container.push_back(string("Text")); container.push_back(14); container.push_back(99.0004); //cout << typeid("Text").name(); container.push_back("Text"); // Этот вариант не срабатывает, как быть с типом char[5] ? Foo(container); system("PAUSE"); } 

But the current version does not look bad already, thank you very much @VTT for the hint.