2013-04-05 36 views
1

为什么这个代码返回值的语法和模板不工作

错误C2893失败:无法专注函数模板'未知类型“ makeAndProcessObject(常量生成器&)”

我使用MSVC2012

class BBuilder 
{ 
public: 
    int makeObject() 
    { 
     return 22; 
    } 
}; 

template <typename Builder> 
auto 
makeAndProcessObject (const Builder& builder) -> decltype(builder.makeObject()) 
{ 
    auto val = builder.makeObject(); 
    // do stuff with val 
    return val; 
} 

int main() 
{ 
    BBuilder myobj; 
    auto retval = makeAndProcessObject(myobj); 

    return 0; 
} 

(住example

回答

8

你的函数makeObject应该是const,因为你试图在constant object上调用这个函数,然后全部工作。 example

2

问题是

makeAndProcessObject (const Builder& builder) receives a const builder 

但makeObject()函数不是const的!!因此它不能推断回报...... 您可以删除const限定符或使makeObject常量,因此它可以找到函数:

int makeObject() const 
{ 
    return 22; 
} 
2

因为makeAndProcessObject功能正在不断的参考对象,因此它不能访问非固定成员函数(builder.makeObject())。无论哪种转换makeObject()以恒定成员函数[例:INT makeObject()const的]或在builder.makeObject()模板函数使用非恒定对象[例如:makeAndProcessObject(生成器&助洗剂)]

问候, Shivakumar宣读