简体   繁体   English

具有虚拟功能的模板类的前向声明实例

[英]Forward Declare instance of Template Class with Virtual Functions

I have created a template class A<T> in mynamespace which I need to forward declare to use in class B in mynamespace2 . 我已经在mynamespace创建了模板类A<T> ,我需要对其进行转发声明以在mynamespace2Bmynamespace2 Is it possible to forward declare a specific instance of A for use in B , namely A<int> ? 是否可以转发声明A的特定实例供B使用,即A<int>

File: ah 档案:啊

#include "b.h"

namespace mynamespace{    
    template <class T>
    class A{
        A(T);                                // constructor
        mynamespace2::B* b_attribute;
    };    
}

File: bh 档案:bh

/* How to forward declare A<int>? This doesn't work:
 *
 *  namespace mynamespace{
 *     class A<int>;
 *  }
 * 
 * neither does this:
 *
 * namespace mynamespace{
 *     template <class T>
 *     class A<T>
 * }
 */

namespace mynamespace2{    
    class B{
        B();
        mynamespace::A<int>* a_attribute;    // for use over here
        virtual void f(A<int>*);             // note: virtual function
    };    
}

I appreciate any help. 感谢您的帮助。

This is no different than forward-declaring anything else, except that you have to get the namespace right: 这与向前声明其他任何内容都没有什么不同,除了您必须正确获得名称空间:

namespace mynamespace{    
    template <class T> class A;
}

A is declared in mynamespace , so you have to specify it, as such. A是在mynamespace中声明的,因此必须这样指定。

If you really want to avoid explicitly specifying the namespace every time, add a using declaration: 如果您确实想避免每次都明确指定名称空间,请添加一个using声明:

namespace mynamespace2{
    using mynamespace::A;

    class B{
        B();
        A<int>* a_attribute;    // for use over here
    };    
}

Once a using declaration is made, you can just refer to A anywhere within mynamespace2 . 做出using声明后,您可以仅在mynamespace2 A任何地方引用A

Note that you must still forward-declare the template in the other namespace, before pulling it in with using . 请注意,在使用using模板之前,您仍然必须在另一个名称空间中向前声明模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM