我使用以下代碼從文件加載對象(對象的子類A,B和C)。編譯問題我是從loadObjFromLine使用不帶模板參數的模板化函數
load.h:611:33: erreur: there are no arguments to ‘loadObjFromLine’ that depend on a template parameter, so a declaration of ‘loadObjFromLine’ must be available [-fpermissive]
load.h:611:33: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
當我使用pObj = loadObjFromLine<T>(line);
,我得到
load.h: In function ‘bool loadObjects(const string&, Object<T>*&)’:
load.h:611:13: erreur: ‘loadObjFromLine’ was not declared in this scope
load.h:611:30: erreur: expected primary-expression before ‘>’ token
編輯 我知道我可以使用loadObjFromLine<double>
但我想的類型T是在loadObject中使用相同(Object * &)。也許這不是正確的做法..
任何想法?
template<typename T>
Object<T>* loadObjFromLine(const std::string& line)
{
std::stringstream lineStream(line);
int objType(-1);
lineStream >> objType;
Object<T> *pObj = NULL;
if (objType == 0)
{
A<T> *pO = new A<T>;
if (lineStream >> *pO)
pObj = pO;
}
else if (objType == 1)
{
B<T> *pO = new B<T>;
if (lineStream >> *pO)
pObj = pO;
}
else if (objType == 2)
{
C<T> *pO = new C<T>;
if (lineStream >> *pO)
pObj = pO;
}
return pObj;
}
template <typename T>
bool loadObjects( const std::string &filename, Object<T>*& pObj)
{
std::ifstream fileStream(filename.c_str());
if (fileStream.good())
{
std::string line;
int objType;
// Loading boundary.
while(std::getline(fileStream, line))
{
pObj = loadObjFromLine(line);
// pObj = loadObjFromLine<T>(line);
if (!pObj)
return false;
}
fileStream.close();
return true;
}
return false;
}
pObj = loadObjFromLine(line);'?它乾淨清晰。德國的答案中提供的解決方案不能被推薦(見評論)。 –
Walter
@Walter,正如我的文章所述,它不會編譯。也許我錯過了什麼,但是什麼? – user2287453
@Walter,好吧,如果我把loadObjFromLine()放在loadObject()之前,它就可以工作......這是爲了這裏,它不在我的代碼中... – user2287453