I have an incredibly exciting library that can translate points: it should work with any point types
template
auto translate_point(T &p, int x
If you want to give precedence to the case having public x
/y
, you can do this:
template
auto translate_point_impl(int, T &p, int x, int y) -> decltype(p.x, p.y, void())
{
p.x += x;
p.y += y;
}
template
auto translate_point_impl(char, T &p, int x, int y) -> decltype(p[0], void())
{
p[0] += x;
p[1] += y;
}
template
void translate_point(T &p, int x, int y) {
translate_point_impl(0, p, x, y);
}
It goes without saying that the opposite configuration is given by switching the types of the first parameter.
If you have three or more options (says N
), you can use a trick based on templates.
Here is the example above once switched to such a structure:
template
struct choice: choice {};
template<>
struct choice<0> {};
template
auto translate_point_impl(choice<1>, T &p, int x, int y) -> decltype(p.x, p.y, void()) {
p.x += x; p.y += y;
}
template
auto translate_point_impl(choice<0>, T &p, int x, int y) -> decltype(p[0], void()) {
p[0] += x;
p[1] += y;
}
template
void translate_point(T &p, int x, int y) {
// use choice as first argument
translate_point_impl(choice<1>{}, p, x, y);
}
As you can see, now N
can assume any value.