开发者

How to take pair-like function arguments

I'm writing a class which will be used to perform some calculations on a set of values, with scaling based on a per-value weight. The values and weights are supplied to the class' constructor. The c开发者_开发百科lass will be part of an internal library, and so I want to put as few restrictions as possible on the clients data structures - some clients will use vectors of structs or std::pairs, another separate OpenCV matrixes. During development I've taken start/end iterators and relied on the pair mechanism (val = it->first, weight = it->second).

How could this be done better, without too much hassle for the programmer on the other end? Generally, what is considered best practise when having this sort of multi-dimensional input?


Iterators are fine. However, relying on the types having public members called first and second is a pretty big restriction.

In C++0x, access to std::pair members will be unified with the access patterns of std::tuple, via a get function. This would allow you to overload and specialize the get function for arbitrary types:

#include <iostream>
#include <utility>

template <class T>
void print(const T& data)
{
    using std::get;
    std::cout << get<0>(data) << ' ' << get<1>(data) << '\n';
}

struct Coord
{
    int x, y;
};

template <unsigned>
int get(const Coord&);

template <>
int get<0>(const Coord& c) { return c.x; }

template <>
int get<1>(const Coord& c) { return c.y; }

int main()
{
    print(std::make_pair(1, 2));
    Coord coord = {4, 5};
    print(coord);
}

In case your standard library doesn't have get for pair, then boost's tuple library seems to have it.


That situation is pretty much what templates are in the language for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜