Function template return type deduction

后端 未结 5 732
南旧
南旧 2020-12-11 02:34

I have some class C with const and non-const getters for some generic type Node:

template 

        
5条回答
  •  忘掉有多难
    2020-12-11 03:07

    Since C++14 the return type of a function may be deduced by the compiler:

    template
    decltype(auto) AliasGetNode(CType& cobject) {
        return cobject.getNode();
    }
    

    When you call AliasGetNode on the object of type Node, CType is deduced to Node. But if you call AliasGetNode on the object of type const Node, CType is deduced to const Node.

    It is important to make return type of AliasGetNode as decltype(auto), otherwise you will miss a reference and constness for the returned type.

提交回复
热议问题