Explicit specialization of inline member functions.

J

jason.cipriani

I have a template class declared in a header, with explicit
specialization of certain member functions defined in a source file.
However, I want to define the specialized member functions in the
header, not a separate source file. They can't be defined outside the
class declaration in the header, as that leads to multiple definitions
of the functions in all the source files that include the header.
However, I don't know the syntax for defining them inside the class
declaration -- and that's my question: is this possible and, if so,
what's the syntax? Right now I have some a test program like this:

=== BEGIN EXAMPLE ===

#include <iostream>
using std::cout;
using std::endl;

template <int N> struct A {
A ();
// <----- I want to put the specialized implementations here.
};

template<> A<1>::A () { cout << "1!" << endl; }

template<> A<2>::A () { cout << "2!" << endl; }

int main () {
A<1> x;
A<2> y;
return 0;
}

=== END EXAMPLE ===

And what I really want to do is define both of those specialized
constructors in the class declaration instead.

Thanks,
Jason
 
V

Victor Bazarov

I have a template class declared in a header, with explicit
specialization of certain member functions defined in a source file.
However, I want to define the specialized member functions in the
header, not a separate source file. They can't be defined outside the
class declaration in the header, as that leads to multiple definitions
of the functions in all the source files that include the header.

They can, just add "inline" to the definition, before the return value
type.
However, I don't know the syntax for defining them inside the class
declaration -- and that's my question: is this possible and, if so,
what's the syntax? Right now I have some a test program like this:

=== BEGIN EXAMPLE ===

#include <iostream>
using std::cout;
using std::endl;

template <int N> struct A {
A ();
// <----- I want to put the specialized implementations here.

No, you can't do that. Put them _after_ the class definiton.
};

template<> A<1>::A () { cout << "1!" << endl; }

template said:
template<> A<2>::A () { cout << "2!" << endl; }

template said:
int main () {
A<1> x;
A<2> y;
return 0;
}

=== END EXAMPLE ===

And what I really want to do is define both of those specialized
constructors in the class declaration instead.

No, not inside. Outside, but "inline">

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

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top