【问题标题】:c++ call template constructor to instantiatec++调用模板构造函数实例化
【发布时间】:2016-12-26 10:57:10
【问题描述】:

给出以下程序,

你好.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.

【问题讨论】:

  • @user1438832 world&lt;Foo&gt; w(); 是非常有效的 C++ 代码
  • 抱歉,是的,它有效,但目的是传递 foo 对象。
  • @user1438832 @Danh 对不起,我打错了。虽然它是有效的,但 world&lt;Foo&gt; w(f) 不是原因。 Dahn 是正确的,我不应该再把 T 放在子类中。

标签: c++ c++11 templates constructor generic-programming


【解决方案1】:

world&lt;T&gt;

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

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

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

Demo


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

world<Foo> w();

这将w 声明为没有参数的函数并返回world&lt;Foo&gt;

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

world<Foo> w(f);

world<Foo> w{f};

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      相关资源
      最近更新 更多