How can I select a member function at compile time based on the non-type template parameter?

Say I have the following struct

template <int size>
struct Foo
{
    ...

    int GetValue()
    {
        if (size == 1)
        {
            return -3;
        }
        return 4;
    }
};

This seems a bit wasteful since size is known at compile time. What I would like to do is something like this

template <int size>
struct Foo
{
    ...

    // Should be used if size is 1
    int GetValue()
    {
        return -3;
    }

    // Should be used if size is not 1
    int GetValue()
    {
        return 4;
    }
};

I assume there is a way to do this but I don't know how.


Solution 1:

In C++17, you might use if constexpr to avoid suntime branching (which might be optimized anyway):

template <int size>
struct Foo
{
    // ...

    int GetValue()
    {
        if constexpr (size == 1)
        {
            return -3;
        }
        return 4;
    }
};