对以下用户定义类片段中的模板实例化问题表示怀疑
Doubt with the template instantiation problem in the below snippet of a user defined class
在论坛中找不到任何相关的东西,所以,请帮我写这段代码。我正在复习我的c++概念,遇到了一个奇怪的错误
#include<iostream>
using namespace std ;
class base
{
int i ;
public:
virtual void f(){cout<<"base" ; return ;};
};
class derived: public base
{
int j ;
public:
void f() {cout<<"derived" ; return ;}
};
template<class T>
class test
{
public:
test(T b)
{
b.f(); cout<<endl<<" "<<sizeof(b)<<endl;
}
};
int main()
{
base b ;
derived d;
test<derived> t(b); // cannot instantiate user defined type without typename
}
以下代码编译失败,出现以下错误:
test.cpp: In function ‘int main()’:
test.cpp:28: error: no matching function for call to ‘test<derived>::test(base&)’
test.cpp:19: note: candidates are: test<T>::test(T) [with T = derived]
test.cpp:17: note: test<derived>::test(const test<derived>&)
我可以胡乱猜测,然后找到为什么会发生这种情况的答案。如果我从模板实例化一个新的基类,一切都很好,但这一个不行。有人能告诉我一个很好的模板实例化来源吗?规则/语义是什么,幕后发生了什么?感谢
您的测试片段有效地定义了这一点:
测试::测试(派生&(
正如错误所说,你试图调用这个:
test::test(base&(
如果我从模板实例化一个新的基类,一切都会很好。
同样,我相信,如果你通过"d"而不是"b",一切都会很好。
您应该能够在没有模板的情况下重现相同的场景:只定义了一个以"派生"为参数的成员函数,然后看看会发生什么:(
base
不是一个完整的derived
类型,因此您必须在模板中提供一个构造函数来填充缺失的详细信息。
template<class T> //original template
class test
{
public:
test(T b)
{
b.f();
cout<<endl<<" "<<sizeof(b)<<endl;
}
};
当您基于derived
创建此模板的实例时,编译器会将其转换为一个类,该类本质上可以归结为这个
class derivedtest
{
public:
derivedtest(derived b)
{
b.f();
cout<<endl<<" "<<sizeof(b)<<endl;
}
};
不再生成默认构造函数。但是,仍然会创建一个默认的复制构造函数。
derivedtest::derivedtest(derived const&);
正如您所看到的,没有办法将base(通过引用或复制(传递到类中。
解决方案是在模板中提供一个构造函数来填充缺失的细节:
template<class T>
class test
{
public:
test(base const& item)
: base(item)
{
}
test(T b)
{
b.f();
cout<<endl<<" "<<sizeof(b)<<endl;
}
};
顺便说一下,你的base
应该很可能有一个虚拟析构函数
并且CCD_ 5应该是CCD_ 6
相关文章:
- 从C++实例化QML
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?
- 显式模板实例化问题
- 实例化函数模板的编译问题
- 模板函数实例化的可移植性问题
- 模板函数实例化 自定义数据类型的问题
- 字符串实例化问题
- 在 C++ 中实例化指向新对象的指针时出现问题
- 何时会隐式实例化导致问题
- Cygwin gcc编译器使用GAlib的模板实例化问题
- 复杂数据类型的模板实例化问题
- 类和函数模板实例化的Visual Studio dll导出问题
- c++中的工厂模式.实例化问题
- Qt继承和实例化问题
- c++中多态性基类和继承类实例化的问题
- 在实例化结构模板时出现问题
- 实例化模板化类的问题
- 实例化子类的多态性问题
- 对以下用户定义类片段中的模板实例化问题表示怀疑
- 继承——实例化问题