简体   繁体   中英

Two functions having same body different name

Is it possible to have two functions with the different function name but the same functionality share the function body? And how can we do it?

template<typename _T>
class array {
public:
    _T operator+(_T concatinate_operand); // concatinate to the array
    _T append(_T concatinate_operand);
};

Yes, this is quite easy to accomplish. You just call the function the you do the actual implementation in from the other one. That would look like

template<typename _T>
class array {
public:
    _T operator+(_T concatinate_operand) { return append(concatinate_operand); } // concatinate to the array
    _T append(_T concatinate_operand) { /*actual logic here*/ }
};

Do note that if T is large then passing it by value and getting a copy will hurt the performance. If you use references like

template<typename _T>
class array {
public:
    _T& operator+(const _T& concatinate_operand) { return append(concatinate_operand); } // concatinate to the array
    _T& append(const _T& concatinate_operand) { /*actual logic here*/ }
};

You will avoid unnecessary copies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM