继承的构造函数和stl容器错误

Inherited constructor and stl containers error

本文关键字:错误 stl 构造函数 继承      更新时间:2023-10-16

我在玩继承的构造函数,但我很难理解为什么当我试图从std::string继承时,gcc会抱怨。

我知道这不是最好的做法,应该不惜一切代价避免,所以在对我大喊大叫之前,我不会在任何地方实施它:-)这纯粹是出于好奇。

我还用一个简单的已定义类尝试了同样的场景,但我没有遇到同样的问题。

#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);
}

实际错误摘录:

main.cpp:25:24:错误:没有用于调用'Wrapper<std::basic_string<char> >::Wrapper(std::string&)' 的匹配函数

Wrapper<string> s2(a);
复制构造函数不是继承的。您需要声明一个构造函数来获取T
Wrapper(T const& t):
    T(t){}

可能还有非const和移动变体:

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