如何处理彼此依赖并拥有模板成员的类?

时间:2012-09-28 05:55:17

标签: c++ templates forward-declaration

这部分与this SO question有关。

我有两个类,它们都是模板化的,例如:

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 type。不幸的是,我不能只是向前声明Derived,因为它会导致另一个错误variable 'Derived d ' has initializer but incomplete type

从我上面提到的SO问题中我了解到编译器需要知道所有模板参数才能正确地向前声明它。但很明显我不能仅仅移动Derived声明,因为它会导致完全相同的问题,反之亦然。

有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:4)

此问题与模板无关。您可以使用Derived的前向声明来编译Base::toDerived()的声明并移动函数定义 取决于<{strong> 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;
}

答案 1 :(得分: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
}

答案 2 :(得分: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;
}

正如您所看到的,它与模板无关。

此外,这种设计感觉不对。