【发布时间】: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
模板定义中一定有我遗漏的东西,但我不确定它在哪里。对于int 或double 等原始类型,它可以工作。它不适用于我定义的类,例如Foo.
【问题讨论】:
-
@user1438832
world<Foo> w();是非常有效的 C++ 代码 -
抱歉,是的,它有效,但目的是传递 foo 对象。
-
@user1438832 @Danh 对不起,我打错了。虽然它是有效的,但
world<Foo> w(f)不是原因。 Dahn 是正确的,我不应该再把 T 放在子类中。
标签: c++ c++11 templates constructor generic-programming