user81993
user81993

Reputation: 6603

Confused over template method specialization

I have been trying to understand this but can't get it to work. My impression is that this should work:-

template <int I> struct banana {
    int getNumber() { return 5; }

    int getNumber<0>() { return 6; }
};

So if I make a new banana with any template parameter other than 0, getNumber() should return 5 and if the parameter is 1, it should return 6. Why is it not working?

Upvotes: 0

Views: 35

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69854

There are 2 ways to get what you want... depending on what you want.

expanding on vsoftco's answer:

#include <iostream>

template <int I>
struct banana {
    int getNumber() { return 5; }
};

template<>
struct banana<0>
{
    int getNumber() { return 6; }
};

struct banana2
{
    template<int I> int getNumber() { return 5; }
};

template<>
int banana2::getNumber<0>() { return 6; }


using namespace std;

auto main() -> int
{
    banana<42> foo;
    banana<0> bar;

    std::cout << foo.getNumber() << std::endl;
    std::cout << bar.getNumber() << std::endl;

    banana2 b2;
    std::cout << b2.getNumber<400>() << std::endl;
    std::cout << b2.getNumber<0>() << std::endl;


    return 0;
}

expected output:

5
6
5
6

Upvotes: 0

vsoftco
vsoftco

Reputation: 56547

Because that's not the way to specialize. What you need is

#include <iostream>

template <int I> struct banana {
    int getNumber() { return 5; }

    //int getNumber<0>() { return 6; } // WRONG
};

template<> int banana<0>::getNumber(){ return 6;} // CORRECT WAY OF SPECIALIZING

int main()
{
    banana<42> foo;
    banana<0> bar;

    std::cout << foo.getNumber() << std::endl; // outputs 5
    std::cout << bar.getNumber() << std::endl; // outputs 6
}

Live on Coliru

Upvotes: 4

Related Questions