-1

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

Chris
  • 26,361
  • 5
  • 21
  • 42
Kubaa322
  • 49
  • 5
  • No, there's no such thing like a general `Object` type in standard c++. The closest you can get is `std::any`. – πάντα ῥεῖ Dec 05 '22 at 15:09
  • `template void Write(const T& obj) { std::cout << typeid(obj).name() << std::endl; }`? – Jarod42 Dec 05 '22 at 15:11
  • 4
    You are confusing C++ with another language. Checking an object's type is very rarely required in C++, and this is not the way to do it. – john Dec 05 '22 at 15:11
  • 3
    @Dean2690 that's an incredibly bad idea. – πάντα ῥεῖ Dec 05 '22 at 15:11
  • 1
    I think you would benefit from [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Don't assume that C++ is like that other curly-brace language you're familiar with. – molbdnilo Dec 05 '22 at 15:20
  • if there was such a monster base class you'd need to pass by reference not by value. But who would built such a monster base class into a language ? ... oh wait... – 463035818_is_not_an_ai Dec 05 '22 at 15:20
  • If the intent is for human-readable output, you might want to [`demangle`](https://www.boost.org/doc/libs/1_80_0/libs/core/doc/html/core/demangle.html) the name. – Eljay Dec 05 '22 at 15:46

2 Answers2

1

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;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
0

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.

Stack Danny
  • 7,754
  • 2
  • 26
  • 55