A function that takes all types of arguments

Let's say I want to create a function that cout passes a value, but I don’t know if it is int or string , or ....

So something like:

 void print(info) { cout << info; } print(5); print("text"); 
+4
source share
3 answers

You can do this with a function template:

 template <typename T> void print( const T& info) { std::cout << info ; } 
+8
source

One option is to use a function template.

 template<typename Arg> void print(const Arg& arg) { std::cout << arg; } 
+3
source

We could use a template to complete it.

 template <typename T> void print(const T& t) { std::cout << t <<std::endl; } int main() { print(12); print("123456"); } 
+2
source

Source: https://habr.com/ru/post/1490825/


All Articles