給下面的程序,C++調用模板的構造方法實例
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
必須有我在模板定義中錯過的東西,但我不確定它在哪裏。對於原始類型,如int
或double
,它可以工作。它不適用於我定義的類,例如Foo
。
world w(f); –
user1438832
@ user1438832'world w();'是非常有效的C++代碼 –
Danh
對不起,是它的有效,但目的是傳遞foo對象。 – user1438832