C 调用模板构造函数实例化
c++ call template constructor to instantiate
给出以下程序,
你好。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
模板定义中一定有一些我错过的东西,但是我不确定它在哪里。对于诸如int
或double
之类的原始类型,它有效。它不适用于我定义的类,例如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) {}
};
演示
与您问的错误无关,在您的主要内容中:
world<Foo> w();
此将w
声明为没有参数的函数,然后返回world<Foo>
。
我想这不是您想要的(如果我错了,请原谅我)。我想这就是您想要的:
world<Foo> w(f);
或
world<Foo> w{f};
来自父类的私人数据已封装,并且确实存在。在儿童类中以相同的变量名称定义数据会导致此类错误,无论它是关于模板类还是正常类。
相关文章:
- 如何使用非默认构造函数实例化模板化类
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 我们可以用参数化构造函数初始化结构的数组吗?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- C++ - 使用另一个类的构造函数实例化一个对象
- 类内初始化与构造函数初始化列表的顺序
- 在保证复制的世界中构造函数实例化
- 防止复制构造函数实例化 C++11 类"deleting"
- 为构造函数初始化引用实例变量提供默认值
- C 调用模板构造函数实例化
- C++.对象使用错误的构造函数实例化
- C++如何用参数化构造函数实例化对象
- 为什么无法使用复制构造函数实例化"non const"而可以在没有复制构造函数的情况下实例化配对?
- C++中函数返回的值是右值吗?无法使用复制/移动构造函数初始化实例
- 用自定义构造函数初始化c++类的实例作为Objective C类成员
- C++:当类被模板化时,如何在使用默认构造函数实例化后将输入放入对象中
- 如何使用已知的非默认构造函数实例化未知大小的可变参数元组