我正在使用模板在 C++ 中实现一个模态类,它存储任何类型的值。所有实现都在同一个文件中。此模式类 CConfigProperty
(模板类)有两个变量值 DefaultValue
和它存储的值类型 DataType
。在另一个类 CDefaultConfig
中,我有一个 std::map 将存储此类的对象。为此,我创建了一个返回模板类对象的方法。我在这个实现中遇到了两个编译错误。我正在使用 Xcode。
1 Field has incomplete type 'CDefaultConfig::DefaultValue'
2 No matching member function for call to 'SetStringValueforModal'
我不确定如何从另一个函数返回模板类的对象。还有如何将一个类中声明的模板用于另一个类。
下面是示例源代码。
#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;
template <class DefaultValue>
CConfigProperty<DefaultValue>::CConfigProperty(DataType type, DefaultValue configProperty)
:m_type(type),
m_configProperty(configProperty)
{
}
template <class DefaultValue>
CConfigProperty<DefaultValue>::CConfigProperty()
{
}
template <class DefaultValue>
CConfigProperty<DefaultValue>::~CConfigProperty(void)
{
}
class CDefaultConfig
{
public:
CDefaultConfig();
~CDefaultConfig(void);
private:
void PopulateDefaultConfigForAllKeys(void);
void printText();
template <class DefaultValue>
CConfigProperty<DefaultValue> *SetStringValueforModal(std::string theValue);
};
CDefaultConfig::CDefaultConfig(void)
{
PopulateDefaultConfigForAllKeys();
}
CDefaultConfig::~CDefaultConfig(void)
{
}
template <class DefaultValue>
CConfigProperty<DefaultValue> * CDefaultConfig::SetStringValueforModal(std::string theValue)
{
CConfigProperty<std::string> *theConfigProperty = new CConfigProperty<std::string>(TYPE_STRING,theValue);
return theConfigProperty;
}
void CDefaultConfig::PopulateDefaultConfigForAllKeys(void)
{
printText();
std::map<std::string, CConfigProperty<class DefaultValue> *> Properties;
Properties["Test"]=SetStringValueforModal("10"); //No matching member function for call to 'SetStringValueforModal
}
在调用 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<int>
是与 CConfigProperty<std::string>
完全不同的类型从编译器的角度来看,您将无法将两种类型混合使用 std::map
.
当您需要运行时多态性时,您正在做的是编译时多态性。
您需要添加一个非模板化基类,并派生 CConfigProperty<>
从它,这样你就可以在 map
中使用基类指针.
关于C++:声明、定义和调用返回模板类对象的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29516165/