Re: template specialization by another templated type
On 29 Jun., 23:29, Aston Martin <masoom.sha...@gmail.com> wrote:
I am trying to specialize a templatized method with another type which
itself takes template parameters.
say e.g i have
template<typename T> void foo() {}
this can be used as foo<int>() or foo<std::vector<int> >, right ?
right.
then consider I want to do something 'special' only when T happens to
be std::vector<T> which itself is template parameterized. how do i do
that without changing the method names ? can i specialize foo<>() on
std::vector<T>
Not directly so, but it is possible to do that in an indirect way,
see below.
is something like below legal ?
template<typename T> void foo<std::vector<T> >() {}
No, because this would be an invalid attempt to
define a partial template specialization for a function
template.
consider the code below
*********************************** START
**********************************
#include <iostream>
#include <complex>
class Junk
{
public:
template<typename T>
void fooMeth()
{
// so something for T, straight forrward
std::cout << "fooMeth<" << typeid(T).name() << ">()" <<
std::endl;
}
template<typename T>
void fooMeth()
{
// do something specific to std::complex but common to all
std::complex<T>
std::cout << "fooMeth<std::complex<" << typeid(T).name() << ">
()" << std::endl;
}
};
int main( int argc, char* argv[])
{
Junk j;
j.fooMeth<int>();
j.fooMeth<std::complex<int> >();
return 0;}
*********************************** END
**********************************
while i try to compile above code i get this error. I wonder if am i
wrong ?
Yes, because you violated the one-definition-rule
in class Junk by trying to provide two definitions
of the same member function fooMeth() in the same
translation unit.
is my compiler under powered ? or is it language short
coming ?
Neither of.
To realize what you want to do you could take advantage
of partial specialization of class templates, e.g.
#include <typeinfo>
#include <iostream>
#include <complex>
template<typename T>
struct FooImpl {
static void call() {
std::cout << "fooMeth<" << typeid(T).name() <<
">()" << std::endl;
}
};
template<typename T>
struct FooImpl<std::complex<T> > {
static void call() {
// do something specific to std::complex but common
// to all std::complex<T>
std::cout << "fooMeth<std::complex<" <<
typeid(T).name() << ">>()" << std::endl;
}
};
class Junk
{
public:
template<typename T>
void fooMeth()
{ FooImpl<T>::call(); }
};
int main()
{
Junk j;
j.fooMeth<int>();
j.fooMeth<std::complex<int> >();
return 0;
}
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! ]