Привет всем программистам и им сочуствующим.
Я тут сам
кое что протестировал на таком примере.
class C1
{
public:
C1(): m_Int(100),m_Char("OK")
{
}
virtual ~C1()
{
}
template<class T> operator T ()
{
T* res=NULL;
if(typeid(T)==typeid(int))
res=(T*)&m_Int;
else
if(typeid(T)==typeid(char*))
res=(T*)&m_Char;
if(res==NULL) throw "Error type cast";
return *res;
}
protected:
int m_Int;
char* m_Char;
};
class C2
{
public:
C2()
{
C1 c1;
int r=c1;
char* d1=c1;
try
{
double g=c1;
}
catch(char* err)
{
::MessageBox(NULL,err,"ERROR!",0);
}
}
~C2()
{
}
} c2;
и, вот какие резульраты я получил:
/ RTTI была во всех тестах была включена /
--VC6--
Компилятор пропустил эту конструкцию, но при выполнении кода дебагер не заходит в тело оператора и, валится с ошибкой.
--VC7--
Компилятор не пропускает такой код вообще.
--C++Builder 5--
Тут, как ни странно, все работает корректно !!?
p/s
С точки зрения синтаксиса C++ тут все правильно -- все дело в реализации !
Спасибо всем, кто пытался ответить на этот вопрос.
Здравствуйте 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!