Re: teplate<class T> operator T () <--> 2
От: Юнусов Булат Россия  
Дата: 21.08.02 08:57
Оценка:
Здравствуйте Eugene-32, Вы писали:

E3>С точки зрения синтаксиса C++ тут все правильно -- все дело в реализации !



#include <typeinfo>
#include <iostream>

class Foo
{
public:
    Foo() : m_Int(100), m_Char("OK")
    {
    }
    virtual ~Foo()
    {
    }      
    template<class T> operator T()
    {
        T* res = NULL;

        if(typeid(T) == typeid(int))
        {
            res = reinterpret_cast<T*>(&m_Int);
        }
        else if( typeid(T) == typeid(char*) )
        {
            res = reinterpret_cast<T*>(&m_Char);
        }

        if(res==NULL) 
        {
            throw std::bad_cast();
        }

        return *res; 
    }   
    
protected:
    int m_Int;
    char * m_Char;
};

class Test
{
public:
    Test()
    {
        Foo m_Foo;
        try
        {
            int ival = m_Foo;
            std::cout << "ival= " << ival << std::endl;
            
            char* szval = m_Foo;
            std::cout << "szval= " << szval << std::endl;
            
            double dval = m_Foo;
            std::cout << "dval= " << dval << std::endl;
        }
        catch(std::bad_cast &e)
        {
            std::cout << "ERROR! " << e.what() << std::endl;
        }
        catch(...)
        {
            std::cout << "ERROR! " << "Oops!" << std::endl;
        }
    }
    ~Test()
    {
    }
} g_Test;


int main(int argc, char* argv[])
{
    return 0;
}



Вывод gcc 2953
ival= 100
szval= OK
ERROR! 8bad_cast



Вывод msvc sp5
ERROR! Oops!
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.