3

I'm using std::any with RTTI and exceptions disabled. It works and std::any_cast<T>() is able to detect whether the type is correct as explained in std::any without RTTI, how does it work?. std::any::type() is disabled without RTTI though.

I'd like to check whether my std::any object contains a value of a given type. Is there any way to do that?

Helloer
  • 417
  • 3
  • 13
  • I don't understand the question. You said that `any_cast`'s detection works even without RTTI. So... just use that to detect what type it is. – Nicol Bolas Aug 21 '20 at 14:43
  • @NicolBolas Exceptions are also disabled, so a bad any_cast will crash the program. – user253751 Aug 21 '20 at 14:44
  • 2
    @user253751: Not if you cast a pointer to an `any` to a `T*`. – Nicol Bolas Aug 21 '20 at 14:44
  • Does this answer your question? [std::any without RTTI, how does it work?](https://stackoverflow.com/questions/51361606/stdany-without-rtti-how-does-it-work) – Red.Wave Aug 21 '20 at 16:42

1 Answers1

5

You can cast a pointer to your any value and check whether the result is null:

#include <any>
#include <iostream>

int main( int argc, char** argv ) {
    std::any any = 5;
    
    if( auto x = std::any_cast<double>(&any) ) {
        std::cout << "Double " << *x << std::endl;
    }
    if( auto x = std::any_cast<int>(&any) ) {
        std::cout << "Int " << *x << std::endl;
    }
    
    return 0;
}
peoro
  • 25,562
  • 20
  • 98
  • 150