On Sep 26, 4:44 am, Adam Nielsen <adam.niel...@uq.edu.auwrote:
Quote:
Hi Barry,
>
Thanks for your reply!
>
>
>
Quote:
Quote:
However I then tried to extend the class with a second template
parameter, and it stopped working:
>
Quote:
Quote:
template <class C, typename T>
class MyClass
>
Quote:
class MyClass<Type1>
>
>
Quote:
template <class F = void()>
class Func
{
};
>
Quote:
template <class Ret, class Arg>
class Func<Ret(Arg)>
^^^^^^^^^^
{
};
>
Quote:
without "<Ret(Arg)>", the compiler assumes that you're defining another
*primary class template* with the same name, which violates the ODR.
with "<Ret(Arg)>", it's a partial specialization. Be aware the number if
template parameters in the <must be same as the primary class template.
>
Sorry, I don't think I explained myself properly! I'm not after a
second MyClass with different template parameters, I want to remove
MyClass<typename Tand instead have MyClass<class C, typename T>.
>
This works, but when it comes to defining a function in the class, it
doesn't like my syntax:
>
// Works with MyClass<typename T(specialisation when T=std::string)
const std::string& MyClass<std::string>::toString() const
{
return this->data;
}
>
// Does not work with MyClass<class C, typename T>
template <class C>
const std::string& MyClass<C, std::string>::toString() const
{
return this->data;
}
>
I would like the second function to be used for all instances where T =
std::string, regardless of what C might be given as when constructing a
MyClass object.
>
Quote:
Quote:
It would appear to work if I write code for every possible value of C,
but then that's the whole reason for having a template! I'm assuming
I've just gotten the syntax wrong, so if someone would be kind enough
to point out the correct way of doing this it would be much appreciated!
>
Thanks,
Adam.
Hi,
IMVHO in the case you have described you have to partially specialize
the whole class.
Which is something quite boring. You can you something like the
following trick, obviosuly you have to tailor it to your needs... :-)
Bye,
Francesco
#include <iostream>
#include <string>
template< typename T >
class CTypeFromType
{};
template< typename T1, typename T2 >
class A
{
public:
std::string Do( void ) { return Do( CTypeFromType< T2 >() ); }
private:
template< typename T3 >
std::string Do( CTypeFromType< T3 )
{ return "GENERAL"; }
std::string Do( CTypeFromType< std::string )
{ return "SPECIALIZED"; }
};
int main()
{
A< int, double obj1;
std::cout << obj1.Do() << std::endl;
A< int, std::string obj2;
std::cout << obj2.Do() << std::endl;
}