Thread: "Any" type using "Boost"

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    417

    "Any" type using "Boost"

    You can get Boost at http://www.boost.org/

    The particular file I am curious is this: http://www.boost.org/boost/any.hpp

    *(any_cast<int>(const_cast<any *>(&x)));

    Only problem is... How can I find out what int is? I want to overload the << operator so that you can cout it without knowing the datatype. Is there a way to use it without specifying <int> ?

    Cause if you have this:

    Code:
    int main()
    {
    	any x(10);
    	//x.getdata();
    	cout << *(any_cast<int>(const_cast<any *>(&x)));
    	cout << endl;
    	x = 'a';
    	//x.getdata();
    	cout << *(any_cast<int>(const_cast<any *>(&x)));
    	cout << endl;
    
    	return 0;
    }
    Also, you can use
    cout << any_cast<int>(x);
    instead of using the const_cast.

    You get a run time error because it isn't an int, but a char.

    Would you need to have a "getint()" and a "getchar()" etc function for every datatype that you want?

    So is "held" actually stored in a way you can get it without knowing the type?
    Last edited by Trauts; 04-30-2003 at 05:35 PM.

  2. #2
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    Any does not know it's "type" at compile time, thus I beleve you need to rely on run-time testing. To build getchar() you need to ether test x.type()==typeid(char) or do the cast and catch the exception.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  2. Little Array Difficulty
    By G4B3 in forum C Programming
    Replies: 16
    Last Post: 03-19-2008, 12:59 AM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. odd errors from msvc std library files
    By blight2c in forum C++ Programming
    Replies: 6
    Last Post: 04-30-2002, 12:06 AM
  5. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM