Jay
Jay

Reputation: 79

Use different parameter data types in same function? (C++)

So say I had:

public: static void print(string message) { }

Is there a way I could make it accept other data types (eg. int, double etc) in the same function? So I could call it like print(7) and it would work?

Thanks everyone for the answers; in the title I wanted it as the same function because I didn't realise functions could have the same names as each other (like variables). Hence, I thought the only way you could do it was through the same function. As I am quite new to C++, I preferred the method of just using the same function name and doing it with different parameters (the overloading method).

Upvotes: 0

Views: 5078

Answers (4)

FelipeDurar
FelipeDurar

Reputation: 1179

just create functions with the same name but with different parameters, this is called function overload, for example:

void print(char *message) { printf("%s", message); }
void print(int val) { printf("%d", val); }
void print(char ch) { printf("%c", ch); }

All above functions are overloaded, see examples of calling:

print("Hello World!");
print(10);
print('P');

this is only available in C++ (not in C)

Upvotes: 0

Sdghasemi
Sdghasemi

Reputation: 5598

You can easily do that by using templates. like this:

template <class T>
class CTest{
    .
    .
    .
}
template <class T>
static void print::CTest<T>(T message){...}

and then specify your variable type while using in your main function.

Upvotes: 0

luk32
luk32

Reputation: 16070

This is what the templates are for e.g:

template<typename Type>
void print_something(Type something) {
  std::cout << something << '\n';
}

The compiler is smart enough to deduce type from parameter. So you can call it like this:

print_something("test");
print_something(42);

It also works for member functions. What compiler does is it substitutes the Type with a concrete type (like int, or char*, or std::string) and produces an overload.

Upvotes: 1

smali
smali

Reputation: 4805

You can use C++ templates, Template provide generic data types in c++. see this for more details.

http://www.tutorialspoint.com/cplusplus/cpp_templates.htm http://www.cprogramming.com/tutorial/templates.html

Upvotes: 0

Related Questions