How can I pass a variable type to a function? like this:
void foo(type){
cout << sizeof(type);
}
How can I pass a variable type to a function? like this:
void foo(type){
cout << sizeof(type);
}
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.
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>()
.
A bit late - but it can be achieved using macros - like this:
#define foo(T) std::cout << sizeof(T)
...
foo(MyType);
You can do this:
#include <typeinfo>
template<class input>
void GetType(input inp){
auto argumentType = typeid(inp).name();
}
Seems like it's not exactly you are looking for, but it may help.