C ++ dynamic data type definition
in C ++, when you define a function that takes one argument, you must define the data type of that variable:
void makeProccess(int request)
However, I want to implement a function that uses different data types, not a statically defined integer type.
void makeProccess(anyType request)
How can I create such a project, any idea?
Thanks.
a source to share
Use templates:
template <typename T>
void makeProcess(T request) {
// request is of type "T", which can vary
cout << "request: " << request;
}
An additional advantage, you can highlight it:
template <>
void makeProcess(string request) {
cout << "This is special handling for a string request: " << request;
}
a source to share
You want to look at C ++ templates - here's a good link: http://www.cplusplus.com/doc/tutorial/templates/
a source to share
First, the "use templates" answers are very helpful - you should investigate templates - this is another alternative to these.
If the function is passing the value through some other code that ultimately knows exactly what type is "inside", you can also use boost :: any - see http://www.boost.org/doc/libs/1_42_0/ doc / html / any.html . However, this can be a little dangerous because you can easily end up with code that is related / interdependent in ways that are not obvious, and that runtime crashes instead of not compiling (which will be with templates). However, this can be significantly more understandable to non-expert C ++ coders than a lot of boilerplate code.
(Note that boost :: any also requires the type to be copied and assigned.)
a source to share