C++:声明、定义和调用返回模板类对象的函数? 我使用模板来实现C++中的一个模式类,它存储任何类型的值。此模式类CConfigPropertytemplate类有两个变量valueDefaultValue和它存储的数据类型值的类型。在另一个类CDefaultConfig中,我有一个std::map,它将存储这个类的对象。为此,我创建了一个返回模板类对象的方法。我在这个实现中遇到两个编译错误。我使用的是Xcode
1字段的类型“CDefaultConfig::DefaultValue”不完整 2调用“SetStringValueforModal”时没有匹配的成员函数 我不知道如何从另一个函数返回模板类的对象。以及如何使用在一个类中声明的模板转换为另一个类 下面是示例源代码C++:声明、定义和调用返回模板类对象的函数? 我使用模板来实现C++中的一个模式类,它存储任何类型的值。此模式类CConfigPropertytemplate类有两个变量valueDefaultValue和它存储的数据类型值的类型。在另一个类CDefaultConfig中,我有一个std::map,它将存储这个类的对象。为此,我创建了一个返回模板类对象的方法。我在这个实现中遇到两个编译错误。我使用的是Xcode,c++,templates,C++,Templates,1字段的类型“CDefaultConfig::DefaultValue”不完整 2调用“SetStringValueforModal”时没有匹配的成员函数 我不知道如何从另一个函数返回模板类的对象。以及如何使用在一个类中声明的模板转换为另一个类 下面是示例源代码 #include <iostream> #include <map> int main(int argc, const char * argv[]) { return 0; } typedef en
#include <iostream>
#include <map>
int main(int argc, const char * argv[])
{
return 0;
}
typedef enum CONFIG_DATA_TYPE {
TYPE_INT = 0,
TYPE_STRING = 3,
}DataType;
template <class DefaultValue>
class CConfigProperty
{
public:
CConfigProperty(DataType type,
DefaultValue configProperty
);
CConfigProperty();
~CConfigProperty(void);
private:
DataType m_type;
DefaultValue m_configProperty; /**/Field has incomplete type 'CDefaultConfig::DefaultValue'**
};
声明DefaultValue m_configProperty时,字段的类型“CDefaultConfig::DefaultValue”不完整
调用SetStringValueforModal时,没有匹配的成员函数用于调用“SetStringValueforModal”很遗憾,您将无法使用
std::map<std::string, CConfigProperty<class DefaultValue> *> Properties;
就像你想的那样
问题是你需要使用具体的类型,比如@Arcathor在他的回答中写道:
std::map<std::string, CConfigProperty<int> *> Properties;
std::map<std::string, CConfigProperty<std::string> *> Properties;
但是,因为从编译器的角度来看,CConfigProperty与CConfigProperty是完全不同的类型,所以不能在一个std::map中混合使用这两种类型
当您需要运行时多态性时,您正在做的是编译时多态性。
您需要添加一个非模板基类,并从中派生CConfigpProperty,以便可以在映射中使用基类指针
std::map<std::string, CConfigProperty<int> *> Properties;
std::map<std::string, CConfigProperty<std::string> *> Properties;