简体   繁体   中英

Algorithms as member or non-member functions?

I have a simple data structure, a triangular matrix indexed by k and l , where l runs from 1 to N and k runs from 1 to l :

template<int N> class triangular_matrix {
    std::vector<int> elem;
public:
    int& operator()(int k, int l) {
        return elem[(N * (N + 1) - l * (l + 1)) / 2 + k - 1];
    }
};

I also have several algorithms operating on this data structure. All of them access triangular_matrix only via operator() .

What are the pros and cons of making these algorithms member functions of triangular_matrix instead of making them non-member functions (in a non-global namespace)?

In C++ it's common to put everything that doesn't have to be a member function in a non-member function. Herb Sutter wrote a nice article about it a while back.

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