> VB: There are no partial specialisations of function templates ....
When you say this you do not mean any function, right? 'cause non-member
function templates *can* be specialized. And I should admit that partial
specialization of member function w/o partial spec of full class is
somewhat ill-conditioned design (can't explain why, just fells like that
way...).
However, I came up with a workaround: Use non-member friend template
functions.
Before listing the code that does this I want to note a gotcha of
VC++7.1 (actually this is somewhat the reason I am posting this
follow-up) which probably is a good example of how unreliable this
compiler is.
Here is how I implemented non-member friend template (tried to trim as
much as I can):
================================================== =
#include <iostream>
using namespace std;
template<class T, unsigned N> class Foo;
template<class T, unsigned N> void print(Foo<T,N> &f);
template<class T, unsigned N>
class Foo {
int i;
public:
friend void print<>(Foo &);
Foo(int i_) :i(i_) {};
};
template<class T, unsigned N>
void print(Foo<T,N> &f) {
cout << "Foo<" << typeid(T).name() << ", " << N << ">"
<< ".i=" << f.i << endl;
}
template<class T>
void print(Foo<T,4> &f) {
cout
<< "Specialized for N=4: "
<< "Foo<" << typeid(T).name() << ", " << 4 << ">"
<< ".i=" << f.i << endl;
}
int main() {
Foo<int,4> a(9); // specialized <> instantiation
// Foo<double,4> b(9); // another specialized <> instantiation
Foo<double,5> c(10); // primary <> instantiation
print(a);
// print(b);
print(c);
return 0;
}
================================================== ===
This compiles (and runs) fine with gcc 3.3.3 and intel 8.1.
However, with VC++7.1, it gives `print cannot access private member'
compile error.
Even worse happens: Commentting out the 1st and 4th lines of main() and
uncommenting 2nd and 5th, VC++ _does_ compile... But very wrong things
happen during run: c acts as if Foo<double,5> !!!
can anyone confirm that this is the case?
Victor Bazarov wrote:
Levent wrote:
Why doesn't this work? (tried with gcc 3.3.3 and VC++ 7.1):
[..]
Because you have to first define the partial specialisation of the
enclosing class template.
On the other hand, full specialization of the member works (without
specializing the whole class). (try replacing `template<class T>
void Foo<T,3>::func()' with `template<> void Foo<double,3>::func()')
If this behaviour is how it is defined in the standard, what may be a
possible workaround to achieve partial specialization on member
functions?
This is as specified. There are no partial specialisations of function
templates, and to partially specialise a member you need to first
partially specialise the class template.
V