isa
isa

Reputation: 462

C++ function dynamic data type definition

in C++, when you define a function which takes one argument, you have to define the data type of that variable:

void makeProccess(int request)

However, I want to implement a function which takes different data types rather taking statically defined integer type.

void makeProccess(anyType request)

How can I design a proccess like this, any idea?

Thanks.

Upvotes: 3

Views: 3000

Answers (4)

Doug
Doug

Reputation: 9100

Firstly, the "use templates" answers are very useful - you should investigate templates - this is another alternative to those.

If the function is passing the value through to 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. This can be a bit dangerous, though, because you can easily get code that is coupled/interdependent in ways that aren't obvious, and that crashes at runtime instead of failing to compile (which is what would happen with templates). However, it can be significantly more understandable to non-expert C++ coders than large quantities of template code.

(Note that boost::any also requires that the type is copyable and assignable.)

Upvotes: 0

Stephen
Stephen

Reputation: 49156

Use templates:

template <typename T>
void makeProcess(T request) {
  // request is of type "T", which can vary
  cout << "request: " << request;
}

An additional benefit, is you can specialize it:

template <>
void makeProcess(string request) {
  cout << "This is special handling for a string request: " << request;
}

Upvotes: 4

Luzik
Luzik

Reputation: 286

Have You consider using tamplates for that ?

template <class T> void makeProcess(T request)
{
    // code
}

Upvotes: 1

Tejs
Tejs

Reputation: 41236

You'll want to look up C++ Templates - here's a good link: http://www.cplusplus.com/doc/tutorial/templates/

Upvotes: 1

Related Questions