【发布时间】:2017-04-10 20:58:12
【问题描述】:
谁能告诉我为什么下面的代码无法编译?我自己试图弄清楚这一点,但我发现的每个答案似乎都与手头的问题略有不同。这是尝试编译的结果:
jefferson@ubuntu:~$ g++ -std=c++14 templates.cpp
templates.cpp: In function ‘int main()’:
templates.cpp:26:19: error: template argument 1 is invalid
std::vector<Foo*> flubs;
^
templates.cpp:26:19: error: template argument 2 is invalid
这里是有问题的代码:
1 #include <stdio.h>
2 #include <vector>
3 template <class T>
4 class Foo {
5 public:
6 virtual void f() const = 0;
7 };
8
9 class Bar : public Foo<Bar> {
10 public:
11 void f() const { printf("foobar\n"); };
12 };
13
14 class Baz : public Foo<Baz> {
15 public:
16 void f() const { printf("foobaz\n"); };
17 };
18
19 int
20 main()
21 {
22 Bar bar = Bar();
23 Baz baz = Baz();
24 bar.f();
25 baz.f();
26 std::vector<Foo*> flubs;
27 return 0;
28 }
【问题讨论】:
-
template<class T> class Foo是一个模板类。没有Foo类(无模板),因此没有Foo* -
为什么
Foo是一个模板类?你不能用非泛型的Foo类实现你想要的功能吗? -
为什么 Foo 是一个模板?它没有使用它的模板参数。
-
这只是一个玩具程序来说明我遇到的真正问题。
-
@Xirema,n.m.,我明白你的意思,你说得对,这里不需要模板。
标签: c++ templates generics compiler-errors abstract-class