C++ pass variable type to function
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>()
.
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.