Home > Mobile >  How can I pass an any object to a function?
How can I pass an any object to a function?

Time:12-06

I am trying to pass an any object to a function (to check its type), and I have something like this:

void Write(Object obj)
{
    cout << typeid(obj).name() << endl;
}

But i got an error 'Write' was not declared in this scope. I assume that there is no an 'Object' type

CodePudding user response:

C is not Java. There is not an Object class that every other class inherits from. You can use a template, but you still won't have the same kind of runtime introspection in C .

template <class Object>
void Write(Object obj) {
    std::cout << ... << std::endl;
}

As noted in a comment, you probably want to pass the argument by const reference, rather than value.

template <class Object>
void Write(const Object& obj) {
    std::cout << ... << std::endl;
}

CodePudding user response:

In addition to the other answer, in you can use auto to let the compiler figure out the type. This means if you pass an int, auto results in the int type. This is the closest, in terms of syntax, you will get to having an "any" type.

Live Demo:

void Write(auto obj){
    std::cout << typeid(obj).name() << std::endl;
}

int main() {
    Write(int{});
}

output:

int

Read here why using namespace std; is considered bad practice.

  • Related