Function template return type deduction

后端 未结 5 731
南旧
南旧 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:06

    You should write two alias functions, one for non-const instance and the other for const instance:

    template 
    const NodeType& AliasGetNode(const CType* cobject) const;  // for const instance. 
    // The function must be const since the only difference between return type will cause redefinition error.
    
    template 
    NodeType& AliasGetNode(CType* cobject);  // for non-const instance
    

    The instances declared const will call the const functions if there are overload functions. Of course, non-const instances will call the non-const version of the overload function. For example:

    class Aclass {
        public:
           string test() { return "calling non-const function"; }
           string test() const { return "calling const function"; }
    };
    
    int main() {
        Aclass a;
        const Aclass b;
    
        cout << a.test() << endl;
        cout << b.test() << endl;
    
        return 0;
    }
    

    The result will be:

    calling non-const function
    calling const function
    

提交回复
热议问题