Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting constructors of template class in c++

In c++11 it is possible to inherit constructors. I have the following code (reproducing example), which fails to compile:

template<class T> class A
{
    ...
}

template<class T> class B : public A<T>
{
    public:       
        B(int a, int b = 0);
}
template<class T> B::B(int a, int b /* =0 */)
{
    ...
}

class C : public B<int>
{
    public: 
    using B::B;
}

The following code doesn't run with the error that C doesn't have the constructor, i.e. the one from B is not inherited:

C obj(5);
//or
C obj(5, 3);
like image 254
Oleg Shirokikh Avatar asked Sep 16 '25 07:09

Oleg Shirokikh


2 Answers

Visual Studio 2013 does not support inheriting constructors. See Support For C++11 Features for more information. Here's the relevant part:

C++11 Core Language Features

  • inheriting constructors
    • Visual Studio 2010: No
    • Visual Studio 2012: No
    • Visual Studio 2013: No

Update

Looks like support for inheriting constructors was added in the November 2013 CTP (hat tip: @yngum)

like image 114
godel9 Avatar answered Sep 17 '25 19:09

godel9


The problem with your original code is that B::B is private, so make it public.

template<class T>
class B : public A<T>
{
public:   // THIS
    B(int a, int b = 0);
}

Live example.

like image 23
Mark Garcia Avatar answered Sep 17 '25 21:09

Mark Garcia