自分自身の型、基本クラスの型、void型、またはこれらの型のCV修飾子とリファレンス型への変換関数は、書くことができる。ただし、変換の際に呼ばれることはない。
struct Base { } ;
struct Derived : Base
{
operator Base() ;
operator Derived() ;
operator void() ;
} ;
規格には、仮想変換関数を通して、呼ばれる可能性があると書かれているが、どういうコードを書けばそんな可能性が生まれるのだろう。試しにこんなコードを書いてみたが、
struct Base1 { } ;
struct Base2
{
virtual operator Base1 &()
{
static Base1 ret ;
std::cout << "Base2::operator Base1 * is called" << std::endl ;
return ret ;
}
} ;
struct Derived : Base1, Base2
{
virtual operator Derived &()
{
std::cout << "Derived::operator Derived & is called" << std::endl ;
return *this ;
}
} ;
void f( Base2 & b2 )
{
Base1 & b1 = b2 ;
}
int main()
{
Derived d ;
f(d) ;
}
うまくいかないようだ。
2 comments:
こうでしょうか
#include
struct B;
struct A
{
virtual operator B() = 0;
};
struct B : A
{
operator B() { std::cout << "B::operator B" << std::endl; return *this; }
};
struct C : B
{
operator B() { std::cout << "C::operator B" << std::endl; return *this; }
};
int main()
{
B b;
C c;
A& a_b = b;
A& a_c = c;
b = a_b;
b = a_c;
}
その手があったか。
Post a Comment