嘿家伙。感谢点击。我正在努力与包括。基本上,我正在尝试创建一个模板类,其中有一个函数可以接受该模板的特定实例。我做了以下人为的例子来说明这一点。转发声明/包含模板类 - “不完整类型的无效使用”
比方说,我有一个标记有模板(通用)类型数据的个人世界。我有一个特定的个人,称为国王。所有的个人都应该能够在国王面前跪下。一般来说,个人可以被标记为任何东西。国王以数字标记(第一,第二位国王)。
的误差
g++ -g -O2 -Wall -Wno-sign-compare -Iinclude -DHAVE_CONFIG_H -c -o Individual.o Individual.cpp
g++ -g -O2 -Wall -Wno-sign-compare -Iinclude -DHAVE_CONFIG_H -c -o King.o King.cpp
In file included from King.h:3,
from King.cpp:2:
Individual.h: In member function ‘void Individual<Data>::KneelBeforeTheKing(King*)’:
Individual.h:21: error: invalid use of incomplete type ‘struct King’
Individual.h:2: error: forward declaration of ‘struct King’
make: *** [King.o] Error 1
Individual.h(Individual.cpp为空)
//Individual.h
#pragma once
class King;
#include "King.h"
#include <cstdlib>
#include <cstdio>
template <typename Data> class Individual
{
protected:
Data d;
public:
void Breathe()
{
printf("Breathing...\n");
};
void KneelBeforeTheKing(King* king)
{
king->CommandToKneel();
printf("Kneeling...\n");
};
Individual(Data a_d):d(a_d){};
};
King.h
//King.h
#pragma once
#include "Individual.h"
#include <cstdlib>
#include <cstdio>
class King : public Individual<int>
{
protected:
void CommandToKneel();
public:
King(int a_d):
Individual<int>(a_d)
{
printf("I am the No. %d King\n", d);
};
};
King.cpp
//King.cpp
#include "King.h"
#include <string>
int main(int argc, char** argv)
{
Individual<std::string> person("Townsperson");
King* king = new King(1);
king->Breathe();
person.Breathe();
person.KneelBeforeTheKing(king);
}
void King::CommandToKneel()
{
printf("Kneel before me!\n");
}
的Makefile
CXX = g++
CXXFLAGS = -g -O2 -Wall -Wno-sign-compare -Iinclude -DHAVE_CONFIG_H
OBJS = Individual.o King.o
test: $(OBJS)
$(CXX) -o [email protected] $^
clean:
rm -rf $(OBJS) test
all: test
我在想我的设计是不正确的,因为我碰到的问题似乎有点人为的问题。我需要一个模板化的课程的原因是存储模板化的数据(一个国王被标记为第N个国王,一个人被标记为字符串作为他们的名字,另一种类型的人可以被标记为人的号码,即人# 234" )。有没有办法存储模板化的数据,而无需制作模板类? – SharkCop 2010-11-21 20:00:44
@TheChariot:默认情况下(除非您在代码中声明)模板实例化是不相关的类。如果您有一个想要用语言表达的概念(“个人”),并且符合该概念的不同实体共享通用功能,请考虑使用继承。基类不会有任何存储的数据,每个派生类将添加特定的数据(一个普通人的字符串,一个未命名人员的数字......)在你的设计中,尽管他们共享一些方法,“Individual”和'个人'不能通过相同的接口传递。 –
2010-11-22 09:00:33