C 调用模板构造函数实例化

c++ call template constructor to instantiate

本文关键字:构造函数 实例化 调用      更新时间:2023-10-16

给出以下程序,

你好。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之类的原始类型,它有效。它不适用于我定义的类,例如Foo

world<T>

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

因为在这种情况下TFoo)不默认构造。我想这是错误的,因为hello<T>中还有另一个T _data;。删除它,您的代码应该很好地工作。这样:

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

演示


与您问的错误无关,在您的主要内容中:

world<Foo> w();

此将w声明为没有参数的函数,然后返回world<Foo>

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

world<Foo> w(f);

world<Foo> w{f};

来自父类的私人数据已封装,并且确实存在。在儿童类中以相同的变量名称定义数据会导致此类错误,无论它是关于模板类还是正常类。