Member function specialization workarounds?

A

Alex Pavloff

Hi folks,

Here's a piece of example code describing the issue I'm having:

struct Foo
{
template<int N>
int Blah()
{
return 1;
}

template<>
int Blah<0>()
{
return 0;
}
};

Microsoft Visual C++ 7.1 compiles and runs this as expected.

Foo f;
int i = f.Blah<1>(); // i == 1
int j = f.Blah<0>(); // j == 0

gcc 3.3.1 however, doesn't like compiling it, giving...

error: explicit specialization in non-namespace scope `struct Foo'

....in addition to numerous other errors resulting because the compiler is
now confused.

Googling for this finds various discussions of what's legal and what's not
when it comes to member function specialization, but I've got a little more
practical question. What sort of workaround can I use to make this code do
pretty much the same thing and run on gcc 3.3.1?

Thanks,

Alex Pavloff
 
V

Victor Bazarov

Alex said:
Here's a piece of example code describing the issue I'm having:

struct Foo
{
template<int N>
int Blah()
{
return 1;
}

template<>
int Blah<0>()
{
return 0;
}
};

Microsoft Visual C++ 7.1 compiles and runs this as expected.

Foo f;
int i = f.Blah<1>(); // i == 1
int j = f.Blah<0>(); // j == 0

gcc 3.3.1 however, doesn't like compiling it, giving...

error: explicit specialization in non-namespace scope `struct Foo'

...in addition to numerous other errors resulting because the compiler is
now confused.

Googling for this finds various discussions of what's legal and what's not
when it comes to member function specialization, but I've got a little more
practical question. What sort of workaround can I use to make this code do
pretty much the same thing and run on gcc 3.3.1?


Move the definition of Blah<0> outside the class:

struct Foo
{
template<int N>
int Blah()
{
return 1;
}
};


template<>
int Foo::Blah<0>()
{
return 0;
}

int main() {

Foo f;
int i = f.Blah<1>(); // i == 1
int j = f.Blah<0>(); // j == 0
}

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top