Search code examples
c++c++11generic-programming

Is it possible to use generic programming without templates?


Say for example I have a function that returns a value from a 2-dimensional array:

float get_2d_noise(const point& p)
{
    return map2D[p.x][p.y];
}

The point is a class that I've defined as part of my library:

struct point
{
    int x;
    int y;
}

Aside from doing this:

template<typename T>
float get_2d_noise(const T& p)
{
    return noisemap[p.x][p.y];
}

Is it possible to get the same effect? I.e., create get_2d_noise in such a way that anything with an x and y member will work? (preferably catching errors at compile time, rather than runtime).


Solution

  • You could write a macro that takes the name of the type as parameter and then creates the desired function. Something like

    CREATE_2D_NOISE_FOR(someType)
    

    that gets expanded to

    float get_2d_noise(const someType& p) {
        return noisemap[p.x][p.y];
    }
    

    However, this is highly not recommended, as you loose all the expressiveness of templates and gain all the problems that come with macros.