Re: Class template member specialization
On 27 Nov., 20:29, anubhav.sax...@wipro.com wrote:
template<class T> class operations{ // generic arithmetic operations
public:
operations(){};
T add(T& t1, T& t2){return t1 + t2;}
T sub(T& t1, T& t2){return t1 - t2;}
Why not:
T add(const T& t1, const T& t2) const {return t1 + t2;}
T sub(const T& t1, const T& t2) const {return t1 - t2;}
In the following I assume this, because otherwise even
my fixed solution of your problem will not lead to
a well-formed program (Instead of non-static member
functions you could consider them to be static member
functions - of course w/o the const-qualifier then).
// specializing the operations for char * type
template<> char *operations<char *>::add(char* t1, char* t2){
char *tmp = NULL;
// logic
return tmp;}
This is an invalid specialization. A valid specialization must
*exactly* match the signature of the primary template, see
[temp.expl.spec]/18. Correct would be:
template<> char *operations<char *>::add(char*& t1, char*& t2){
...
}
given your original code or
template<> char *operations<char *>::add(
char* const & t1, const char* const & t2) const
{
...
}
given my proposed fix.
template<> char *operations<char *>::sub(char* t1, char* t2){
char *tmp = NULL;
// logic
return tmp;
}
Same fix as above required.
int main(){
operations<int> mi;
operations<char *> mcp;
mi.add(2, 3);
mcp.add("test", "te");
Neither of the add instantiations can compile
given your original code, because that would
require the arguments to be either lvalues (1st)
or mutable (2nd).
However the code above gives an error while compiling in VC++ 8.0.
VC8 is correct here.
template<> char *operations<char *>::add(char* t1, char* t2);
template<> char *operations<char *>::sub(char* t1, char* t2)
This is the same approach outlined in section 16.6 of C++ primer, 4th
edition.
I have not this book available to check, but if that
is an exact adaption of code shown there, the author
should be informed about that error (but have a look
into the hopefully existing errata list first!)
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]