How to partially specialize a class but NOT specialize a member function:

M

mrstephengross

Ok, I've got a class with two template parameters (A and B), and a
member function foo(). I want to specialize foo for a particular class
A. Is this possible? The following code shows an example:

=====================================
template<typename A, typename B>
class Foo
{
int foo() { return 5; }
};


template<typename B>
int Foo<int, B>::foo() { return 6; }

int main()
{
return 0;
}
======================================

The above example doesn't compile; g++ reports the following error:

test.cpp:11: error: no `int Foo<int, B>::foo()' member function
declared in class `Foo<int, B>'
test.cpp:11: error: template definition of non-template `int Foo<int,
B>::foo()'

I take it this means I can't write function implementations for class
specializations if the class specialization hasn't been declared...?

Thanks,
--Steve
 
V

Victor Bazarov

mrstephengross said:
Ok, I've got a class with two template parameters (A and B), and a
member function foo(). I want to specialize foo for a particular class
A. Is this possible?

Yes, as soon as you specialise your class template for that particular
class A.
> The following code shows an example:

=====================================
template<typename A, typename B>
class Foo
{
int foo() { return 5; }
};


template<typename B>
int Foo<int, B>::foo() { return 6; }

int main()
{
return 0;
}
======================================

The above example doesn't compile; g++ reports the following error:

test.cpp:11: error: no `int Foo<int, B>::foo()' member function
declared in class `Foo<int, B>'
test.cpp:11: error: template definition of non-template `int Foo<int,
B>::foo()'

I take it this means I can't write function implementations for class
specializations if the class specialization hasn't been declared...?

Yes. To define a member you need to define the class first, of which the
function is a member.

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,011
Latest member
AjaUqq1950

Latest Threads

Top