Inherited constructor and stl containers error

148 views Asked by At

I am playing around with inherited constructors, however I have troubles understanding why gcc complains when I try to inherit from std::string.

I know it's not best practice and it should be avoided at all costs, so before shouting at me for that, I am not implementing it anywhere :-) This is just for pure curiosity.

I also tried the same scenario with a simple used defined class, and I don't have the same problem.

#include <string>
#include <vector>
#include <iostream>

using namespace std;

template <typename T>
struct Wrapper : public T
{
    using T::T;
};

struct A{
  A(int a) : _a(a) {} 
  int _a; 
};

int main()
{
   Wrapper<string> s("asd"); //compiles
   string a = "aaa";
   Wrapper<string> s2(a); //does not compile

   Wrapper<A> a(1);
   int temp = 1;
   Wrapper<A> b(temp);
}

an excerpt from the actual error:

main.cpp:25:24: error: no matching function for call to 'Wrapper<std::basic_string<char> >::Wrapper(std::string&)'

Wrapper<string> s2(a);
1

There are 1 answers

0
Anthony Williams On

Copy constructors are not inherited. You need to declare a constructor to take a T

Wrapper(T const& t):
    T(t){}

and possibly the non-const and move variants too:

Wrapper(T& t):
    T(t){}
Wrapper(T&& t):
    T(std::move(t)){}