无效的基类 T 错误
我正在尝试做这样的事情,但是,我收到一个错误, “无效的基类 T”。 据我们的理解,基类将在编译时使用类型名称 T 进行实例化,并且我将在编译时获得 T 的定义。我尝试用“Class”替换“Typename”,但仍然遇到相同的错误。有什么想法吗?
template <typename T>
class Base
{
private:
class A : public T{};
};
// It works when I do the following in main ...
class A{}
Base* B = new Base<A> B;
// It throws error, when I pass in int,double,float,
//makes sense,because these are basic data types ...
Base* B = new Base<int> B;
// Neil's Snippet with the error reproduced ...
#include <iostream>
using namespace std;
template <typename T>
class Base
{
public :
Base::Base(int a)
{
A a;
}
private:
class A : public T{};
};
Base <int> b;
int main(){
cout << &b << endl;
}
I am trying to do something like this, But, I am getting an error,
"Invalid Base class T".
As far as our understanding goes, Base class will get instantiated with Type name T in compile time and I will be getting the defination of T in compile time. I tried replacing "Typename" with "Class",still I get the same error. Any ideas ?
template <typename T>
class Base
{
private:
class A : public T{};
};
// It works when I do the following in main ...
class A{}
Base* B = new Base<A> B;
// It throws error, when I pass in int,double,float,
//makes sense,because these are basic data types ...
Base* B = new Base<int> B;
// Neil's Snippet with the error reproduced ...
#include <iostream>
using namespace std;
template <typename T>
class Base
{
public :
Base::Base(int a)
{
A a;
}
private:
class A : public T{};
};
Base <int> b;
int main(){
cout << &b << endl;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Typename
不是有效的 C++ 关键字,typename
是。类似地,Class
与class
不同。请注意,C++ 区分大小写。
除此之外,您的代码中缺少一个分号。
Typename
is not a valid C++ keyword,typename
is. SimilaryClass
is different fromclass
.Note that C++ is case sensitive.
Apart from that you are missing a semicolon in your code.
应编译以下代码:
请注意,
T
在实例化时应为完整类型。以下情况将会失败:The following code should compile:
Note, that
T
should be complete type at the point of instantination. The following will fail:您遇到了一些基本的语法错误,这让您感到悲伤:
Typename 应该是 typename,并且在内部类定义之后需要一个分号,因此可以完美编译:
You got a few basic syntax errors in this which is causing you grief:
Typename should be typename and you need a semi colon after the internal class definition, so this compiles perfectly:
编译:
为了 Nawaz 的利益而编辑。
This compiles:
Edited for the benefit of Nawaz.