c++调用模板构造函数实例化

c++ call template constructor to instantiate

给出如下程序,

hello.h

#ifndef HELLO_
#define HELLO_

template <typename T>
class hello
{
  T _data;
public:
  hello(T t)
  : _data(t) {}
};

template <typename T>
class world : public hello<T>
{
  T _data;
public:
  world(T t)
  : hello<T>(t) {}
};

#endif

main.cc

#include <iostream>
#include "hello.h"

using namespace std;

class Foo
{
  int _x;
public:
  Foo(int x) : _x(x) {}
};

int main()
{
  Foo f(1);
  world<Foo> w(f);

  return 0;
}

我是用c++11编译的,编译器报错如下:

In file included from main.cc:2:0:
hello.h: In instantiation of ‘world<T>::world(T) [with T = Foo]’:
main.cc:16:22:   required from here
hello.h:19:15: error: no matching function for call to ‘Foo::Foo()’
   : hello<T>(t) {}
               ^
main.cc:10:3: note: candidate: Foo::Foo(int)
   Foo(int x) : _x(x) {}
   ^
main.cc:10:3: note:   candidate expects 1 argument, 0 provided
main.cc:6:7: note: candidate: constexpr Foo::Foo(const Foo&)
 class Foo
       ^
main.cc:6:7: note:   candidate expects 1 argument, 0 provided
main.cc:6:7: note: candidate: constexpr Foo::Foo(Foo&&)
main.cc:6:7: note:   candidate expects 1 argument, 0 provided

模板定义中一定有我遗漏的东西,但我不确定它在哪里。对于 intdouble 等原始类型,它有效。它不适用于我定义的 class,例如Foo.

world<T>

template <typename T>
class world : public hello<T>
{
  T _data;
public:
  world(T t)
  : hello<T>(t) {}
};

因为 T 在这种情况下 (Foo) 不可默认构造。我猜这是错误添加的,因为 hello<T> 中还有另一个 T _data;。删除它,您的代码应该可以正常工作。像这样:

template <typename T>
class world : public hello<T>
{
public:
  world(T t)
  : hello<T>(t) {}
};

Demo


与您提出的错误无关,主要是:

world<Foo> w();

这将 w 声明为不带参数的函数,并且 return world<Foo>

我猜这不是你想要的(如果我错了请原谅我)。我想这就是你想要的:

world<Foo> w(f);

world<Foo> w{f};

来自父级 class 的私人数据被封装并且它们确实存在。在子class中重复定义具有相同变量名的数据会导致这样的错误,无论是关于模板class还是普通class。