简体   繁体   中英

C++ Template Inheritance

I couldn't find any similar questions with my Googling' skills, so hopefully SO can help. (Sample header psuedocode below)

namespace randomNamespace{
template <typename A, typename B>
class Shape{
    public:
        Shape(int);
        ~Shape();

        bool insert(std::pair<A,B> ab);
    private:
        std::vector<std::pair<A,B> > someListOfPairs;
};
}

class Square : public Shape<string, string>     //causes error requiring template before '<'
{
public:
    Square(int);    //When defined it is Square(int x) : Shape(x); as an initialization list to call superclass constructor
    ~Square();

    bool insert(std::pair<string, string> p);
private:
    //Shape<string, string> someShape    -- see question #3
};

1) What is the proper syntax for inheriting a template'd generic base class?

2) Does Class Square have access to someListOfPairs (not talking about it being private), such as when I call Square's insert(pair of strings), it will then call Shape's insert(pair of generic type)? (Also how would this actually be implemented??)

3) Would I have to define an object of Shape someShape to properly use the Shape class members even though it is already using inheritance?

1) What is the proper syntax for inheriting a template'd generic base class?

There's nothing wrong with the syntax of inheritance, you just need to specify the namespace of your base class:

class Square : public randomNamespace::Shape<std::string, std::string> { ...
                      ^^^^^^^^^^^^^^^

2) Does Class Square have access to someListOfPairs (not talking about it being private), such as when I call Square's insert(pair of strings), it will then call Shape's insert(pair of generic type)? (Also how would this actually be implemented??)

You could call the insert member function of Shape from the member function of Square in the following way:

bool Square::insert(std::pair<std::string, std::string> p) {   
  randomNamespace::Shape<std::string, std::string>::insert(p);
  // ... 
  return true; 
}

3) Would I have to define an object of Shape someShape to properly use the Shape class members even though it is already using inheritance?

Yes you would have to initialize the base class in the initializer list of Square s constructor:

Square::Square(int a) : randomNamespace::Shape<std::string, std::string>(a) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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