Forward "Preliminary Declaration" of a Class in C ++

I have a situation in which I want to declare a member function of a class that returns a type that depends on the class itself. Let me give you an example:

class Substring {
    private:
        string the_substring_;
    public:
        // (...)
        static SubstringTree getAllSubstring(string main_string, int min_size);
};

And substringTree is defined as follows:

typedef set<Substring, Substring::Comparator> SubstringTree;

My problem is that if I set the SubstringTree definition after defining the substring, the static method says that it does not know the substring. If I cancel the declarations, then typedef says that it does not know the substring.

How can i do this? Thanks in advance.

+3
source share
4 answers

You can define it inside the class:

class Substring {
    private:
        string the_substring_;
    public:
        // (...)
        typedef set<Substring, Substring::Comparator> SubstringTree;
        static SubstringTree getAllSubstring(string main_string, int min_size);
};
+5
source

As you wrote it, the short answer is: you cannot.

:

1) SubstringTree

class Substring {
public:
    class Comparator;
    typedef set< Substring, Comparator> Tree;

private:
    string the_substring_;
public:
    // (...)
    static Tree getAllSubstring(string main_string, int min_size);
};

typedef Substring::Tree SubstringTree;

2) :

class Substring;
class SubstringComparator;
typedef set< Substring, SubstringComparator> SubstringTree;

class Substring {
public:

private:
    string the_substring_;
public:
    // (...)
    static SubstringTree getAllSubstring(string main_string, int min_size);
};

3) , :

template <typename String>
struct TreeHelper
{
  typedef set< String, typename String::Comparator> Tree;
};

class Substring {
public:
  class Comparator;

private:
  string the_substring_;
public:
  // (...)
  static TreeHelper<Substring>::Tree getAllSubstring(string main_string
                                             , int min_size);
};

typedef TreeHelper<Substring>::Tree SubstringTree;
+7

You can predict the class with this:

class Foo;

Keep in mind that before a class is really defined, you can only declare pointers to it, not instances.

+3
source

forward declaration

class Substring;

I don't know if this will work for use without substring pointers.

0
source

Source: https://habr.com/ru/post/1712110/


All Articles