Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pass variable type to function

How can I pass a variable type to a function? like this:

void foo(type){     cout << sizeof(type); } 
like image 628
user3325976 Avatar asked Mar 02 '14 11:03

user3325976


People also ask

Can you pass a type as an argument in C?

You don't actually pass a type to a function here, but create new code for every time you use it. To avoid doubt: ({...}) is a "statement expression", which is a GCC extension and not standard C.

Can we pass variables to functions?

variable is in the scope of startFunction and its value is passed to adding function. variable2 is only in the scope of function adding where the value of 1 is added to the value of variable. you return the value of variable2 but there is no variable to receive that value.

Can you pass a global variable to function in C?

Both local and global variables are passed to functions by value in C. If you need to pass by reference, you will need to use pointers.


2 Answers

You can't pass types like that because types are not objects. They do not exist at run time. Instead, you want a template, which allows you to instantiate functions with different types at compile time:

template <typename T> void foo() {   cout << sizeof(T); } 

You could call this function with, for example, foo<int>(). It would instantiate a version of the function with T replaced with int. Look up function templates.

like image 95
Joseph Mansfield Avatar answered Oct 06 '22 16:10

Joseph Mansfield


As Joseph Mansfield pointed out, a function template will do what you want. In some situations, it may make sense to add a parameter to the function so you don't have to explicitly specify the template argument:

template <typename T> void foo(T) {   cout << sizeof(T) } 

That allows you to call the function as foo(x), where x is a variable of type T. The parameterless version would have to be called as foo<T>().

like image 24
microtherion Avatar answered Oct 06 '22 16:10

microtherion