Multiple inheritance from two derived classes with templates and constructors

I follow the example here , however I use templates and call the constructor of one of the derived classes. The following code works without templates, but when it is turned on, I'm not sure why I get the following error:

: error: no matching function for call toAbsInit<double>::AbsInit()’
     NotAbsTotal(int x) : AbsInit(x) {};
                                   ^

Here is the code:

#include <iostream>

using namespace std;

template<typename T>
class AbsBase
{
    virtual void init() = 0;
    virtual void work() = 0;
};

template<typename T>
class AbsInit : public virtual AbsBase<T>
{
public:
    int n;
    AbsInit(int x)
    {
        n = x;
    }
    void init() {  }
};

template<typename T>
class AbsWork : public virtual AbsBase<T>
{
    void work() {  }
};

template<typename T>
class NotAbsTotal : public AbsInit<T>, public AbsWork<T>
{
public:
    T y;
    NotAbsTotal(int x) : AbsInit(x) {};
};    // Nothing, both should be defined


int main() {
  NotAbsTotal<double> foo(10);
  cout << foo.n << endl;

}
+4
source share
2 answers

You need to pass the template argument (in this case T) to the base template class.

Change it

template<typename T>
class NotAbsTotal : public AbsInit<T>, public AbsWork<T>
{
public:
    T y;
    NotAbsTotal(int x) : AbsInit<T>(x) // You need to pass the template parameter
    {};
};    
+2
source

In the snippet below ...

template<typename T>
class NotAbsTotal : public AbsInit<T>
{
    NotAbsTotal(int x) : AbsInit(x) {}
};

... AbsInit<T>is a dependent base class :

- , .

... - (AbsInit), :

- ( [class]) .

... [temp.dep]/p3:

([temp.dep.type]) , . [:

typedef double A;
template<class T> class B {
  typedef int A;
};
template<class T> struct X : B<T> {
  A a;              // a has type double
};

[...]

- ]

, AbsInit , AbsInit<T>. , , , .

, AbsInit:

NotAbsTotal(int x) : AbsInit<T>(x) {}
//                          ~~^

:

NotAbsTotal(int x) : NotAbsTotal::AbsInit(x) {}
//                   ~~~~~~~~~~^

: (, , , AbsInit<int>), .

+2

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


All Articles