2016-05-14 16 views
1

私は教育目的でスマートポインタクラスを実装しようとしています。クラスUがクラスTの基底であるとき、私は以下を行うことができます。スマートポインタインプリメンテーションの暗黙のキャスト

ptr<T> t; 
ptr<U> u = t; 

私はこの暗黙のキャストを実装するのに苦労しているので、誰かがこれを手伝ってくれますか?

+2

'ptr ' 'ptr 'の 'is_base_of'に制限されたコンストラクタを与えますか? –

答えて

2

これを実現するためにを使用した例です。 example.h

#include <type_traits> 

template <typename T> 
class Example { 
public: 
    template < 
    typename T2, 
    typename = typename std::enable_if<std::is_base_of<T, T2>::value>::type 
    > 
    Example (const Example<T2> &) {} 

    Example() = default; 
}; 

予想したように、次のプログラムが正常にコンパイル:

#include <example.h> 

class Foo {}; 
class Bar : public Foo {}; 

int main (int argc, char * argv []) { 
    Example<Bar> bar; 
    Example<Foo> foo = bar; 
} 

クラスBarは、クラスFooから派生しているので、Example<Foo>Example<Bar>から初期化することができます。予想通り

はまた、次のプログラムは、コンパイルに失敗します。

#include <example.h> 

class Foo {}; 
class Baz {}; 

int main (int argc, char * argv []) { 
    Example<Baz> baz; 
    Example<Foo> foo = baz; 
} 

クラスBazがクラスFooとは無関係ですので、Example<Foo>Example<Baz>から初期化することはできません。 Clangは、次のエラーメッセージを表示します。error: no viable conversion from 'Example<Baz>' to 'Example<Foo>'

関連する問題