How to forward declare a template class in namespace std?

后端 未结 4 1254
渐次进展
渐次进展 2020-12-02 06:30
#ifndef __TEST__
#define __TEST__

namespace std
{
    template
    class list;
}

template
void Pop(std::list * l)
{
           


        
相关标签:
4条回答
  • 2020-12-02 07:05

    Forward declaration should have complete template arguments list specified.

    0 讨论(0)
  • The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:

    namespace std {
      template<class T, class Allocator = std::allocator<T>>
      class list;
    }
    

    But to make even such a forward declaration in namespace std is explicitly prohibited by the standard: the only thing you're allowed to put in std is a template specialisation, commonly std::less on a user-defined type. Someone else can cite the relevant text if necessary.

    Just #include <list> and don't worry about it.

    Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H instead of __TEST__. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.

    0 讨论(0)
  • 2020-12-02 07:14

    there is a limited alternative you can use

    header:

    class std_int_vector;
    
    class A{
        std_int_vector* vector;
    public:
        A();
        virtual ~A();
    };
    

    cpp:

    #include "header.h"
    #include <vector>
    class std_int_vector: public std::vectror<int> {}
    
    A::A() : vector(new std_int_vector()) {}
    [...]
    

    not tested in real programs, so expect it to be non-perfect.

    0 讨论(0)
  • 2020-12-02 07:25

    I solved that problem.

    I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>) and its states (state pattern, forward declaration).

    The solution is as follows:

    In the *.cpp file, you must include the Header file that you forward, i.e.

    ifndef STATE_H_
    #define STATE_H_
    #include <stdlib.h>
    #include "Frame.h"
    
    template <class T>
    class LinkFrame;
    
    using namespace std;
    
    template <class T>
    class State {
    
      protected:
        LinkFrame<int> *myFrame;
    
    }
    

    Its cpp:

    #include "State.h"
    #include "Frame.h"
    #include  "LinkFrame.h"
    
    template <class T>
    bool State<T>::replace(Frame<T> *f){
    

    And... another class.

    0 讨论(0)
提交回复
热议问题