0

I'm using the following code to load objects (A, B and C which are subclasses of Object) from file. The compilation issue I have is from 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)

And when I use pObj = loadObjFromLine<T>(line); , I get

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 ‘&gt;’ token

EDIT I know I could use loadObjFromLine<double> but I'd like the type T to be the same used in loadObject(Object*&). Maybe it's not the right approach..

Any idea ?

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;
}
4

2 回答 2

0

您需要指定类型 loadObjFromLine 应显式实例化,例如:loadObjFromLine<T>("hgjghgj")

在这种情况下,编译器的错误消息非常有用:编译器无法推断出它应该使用的实例化函数的类型(因为它不依赖于函数的参数),因此您需要明确说明它。

于 2013-10-31T10:39:30.727 回答
0

做这个:

LoadObjFromLine<Type>(line);

可以看到,有一个字符串参数和一个模板参数:

template <class T>
Obj<T> * LoadObjFromLine(std::string const & line);

你不能推导出参数。为了推导出参数,签名应该是这样的(注意我将返回类型更改为void也)。

template <class Obj>
void LoadObjFromLine(std::string const & line, Obj * obj);

这样,您可以执行以下操作:

Obj<MyType> * obj;
LoadObjFromLine(line, obj);

并且会推断出 obj 。

在您的情况下,没有参数可以传递给函数以推断T模板参数。

编辑:如下所述,首选签名LoadObjFromLine将是您的程序中使用的签名,而不是void用作返回类型的签名。带有 void 签名的示例只是为了说明何时可以推断出模板参数与何时无法推断出模板参数

于 2013-10-31T10:39:11.770 回答