tags:

views:

116

answers:

2

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 class 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?

A: 

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

T.E.D.
+4  A: 

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.

UncleBens
Maybe I'm dense, but I really fail to see how `get<0>(p)` and `get<1>(p)` are an improvement over `p.first` and `p.second`.
sbi
Because they can be implemented for any class without changing that class? Because they abstract away the difference between pair and tuple? Because you don't have to know English numerals?
UncleBens
@UncleBens: The last two I understand (although I don't see much of an advantage in that). The first I don't get.
sbi
@sbi: The example code shows, how an arbitrary `Coord` struct would be made to function as "a pair", as far as the `print` function template is concerned.
UncleBens
@UncleBens: Ah, Ok, I see what you mean now. However, I fail to see how `get<0>(coord)` is better than `coord.x`. I consider the latter far more readable.
sbi
@sbi: The same *template* would work both for `coord.x` (or `coord.get_x()` should it not be public) and `pair.first`. It's just another level of abstraction.
UncleBens
@UncleBens: I think I understood that. `:)` It's just that sometimes abstractions improve readability and sometimes they don't. I agree that they might then improve other things (like code re-usability) and are thus still an improvement. (Otherwise there would be no excuse for doing TMP, after all.)
sbi