jeremiah chandler
jeremiah chandler

Reputation: 3

Expecting various argument types in c++

I'm creating an equivalent to JavaScript's console.log in C++, but am unsure how to have my function expect different types of arguments.

In JavaScript:

function print(arg)
{
    if(typeof arg=="number") { ... }
    if(typeof arg=="string") { ... }       
}

Of course, JavaScript doesn't care what you give a function, but C++ does, so how can I have it catch any ( or at least specify types for it to accept ), to be handled later in the function itself?

All I have so far:

void print(string input)
{
    cout << input << "\n";
}

Upvotes: 0

Views: 169

Answers (3)

David Grayson
David Grayson

Reputation: 87396

You can use function templates as described by NathanOliver.

You can also use function overloading: just define multiple functions with the same name but different argument types. The compiler will choose the right one. Function overloading might be better than a template function depending on what you are doing. In particular, if every type of parameter requires a different function body to handle it, function overloading probably makes more sense than a template.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180585

You can accomplish this with a function template.

template <typename T>
void print(const T& output)
{
    std::cout << output << "\n";
}

This will create a print function for each type you pass to it.

Edit:

From the comments if you want this to work with arrays as well then you can add

template<typename T, std::size_t N>
void print(T (&output)[N])
{
    for (std::size_t i = 0; i < N; i++)
    {
        std::cout << output[i] << " ";
    }
    std::cout << "\n";
}

You cann see all of this working together in this Live Example

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

This is a solved problem.

std::cerr << "My console output with a number! " << 42 << std::endl;

This goes to stderr, an output stream typically handled by your shell differently than stdout, so as to aid in debugging and fault-finding. It's the perfect analogue to JavaScript's console.log, and it already exists.

Upvotes: 0

Related Questions