1

これは、このSOの質問に部分的に関連しています。

私には2つのクラスがあり、どちらもテンプレート化されています。例:

class Base
{
public:
    template< class T > void operator=(T other)
    {
        //irrelevant
    }

    Derived toDerived()
    {
        Derived d;
        //do stuff;
        return d;
    }
};

class Derived: public Base
{
public:
    template< class T > void foo( T other )
    {
        //do stuff 
    }
};

ご覧のとおり、両方ともテンプレート化されており、Baseクラス関数内でのインスタンスを作成する必要がありますDerived。もちろん、今のようにエラーが発生しますDerived does not name a typeDerived残念ながら、別のエラーが発生するため、前方宣言することはできませんvariable 'Derived d ' has initializer but incomplete type

上記のSOの質問から、コンパイラーが正しく前方宣言できるようにするには、すべてのテンプレートパラメーターについて知る必要があることを理解しています。しかし、明らかにDerived、宣言を上に移動することはできません。まったく同じ問題が発生するため、その逆も同様です。

これを達成する方法はありますか?

4

3 に答える 3

4

この問題はテンプレートには何もありません。の前方宣言を使用して、の宣言Derivedをコンパイルし、Base::toDerived()の定義に応じて関数定義を移動することができます。Derived Derived

// Forward declaration of Derived
class Derived;

// Definition of Base
class Base
{
public:
   // Base::toDerived() declaration only
   Derived toDerived();
};

// Definition of Derived
class Derived: public Base
{
public:
...
};

// Base::toDerived() definition
inline Derived Base::toDerived()
{
   Derived d;
   // Do dirty things
   return d;
}
于 2012-09-28T06:05:36.790 に答える
3
// Declare, but do not define
class Derived;

class Base {
public:    
    // Declare, but do not define
    // at this point Derived must be declared to be able
    // to use it in the return type
    Derived toDerived();
};

// Define
class Derived: public Base {
    // Rest of definition
};

// At this point Derived is defined

// Define
Derived Base::toDerived()
{
    // Implementation goes here
}
于 2012-09-28T06:05:32.080 に答える
3

できるよ

class Derived;

class Base
{
public:
    template< class T > void operator=(T other)
    {
        //irrelevant
    }

    Derived toDerived();
};

class Derived: public Base
{
public:
    template< class T > void foo( T other )
    {
        //do stuff 
    }
};

Derived Base::toDerived()
{
    Derived d;
    //do stuff;
    return d;
}

ご覧のとおり、テンプレートとは何の関係もありません。

また、このデザインは単に正しく感じられません。

于 2012-09-28T06:06:33.327 に答える