Is there any way to partially specialize on a class defining a specifictype

P

Pavel

I am trying to make library code use a type specified by the library
user, if he defines it in a typedef, and another type, if s/he doesn't,
something as in the code below (which does not compile as it is).

What's the simplest API for this from the perspective of library user?

Ideally a user that does not need the flexibility of choosing his own
Type does not have to pay for it in terms of API complexity.

Thank in advance,
-Pavel

#include <iostream>

using namespace std;

template<typename T>
struct TC // provided by library
{
static void DefaultF() { cout << "Default F()\n"; }
};

struct Concrete { /*...*/ }; // some Concretes are provided by library,
some by user.

template<>
struct TC<Concrete>
{
static void ConcreteF() { cout << "Concrete F()\n"; }
};


struct HaveTypedef { typedef double Type; /* ... */ }; // provided by user

template<typename T>
struct TC<typename T::Type> {
static void HaveTypedefF() { cout << "Have typedef F(): " <<
T::Type() << '\n'; }
};

int
main()
{
TC<int>::DefaultF();
TC<double>::HaveTypedefF();
TC<Concrete>::ConcreteF();

return 0;
}
 
J

Johannes Schaub (litb)

Pavel said:
I am trying to make library code use a type specified by the library
user, if he defines it in a typedef, and another type, if s/he doesn't,
something as in the code below (which does not compile as it is).

What's the simplest API for this from the perspective of library user?

Ideally a user that does not need the flexibility of choosing his own
Type does not have to pay for it in terms of API complexity.

Sounds like you want to use SFINAE

template<typename> struct tovoid {
typedef void type;
};

template<typename T, typename = void>
struct TC {
/* generic ... */
};

template<typename T>
struct TC<T, typename tovoid<typename T::Type> > {
/* T has Type nested type */
};
 
P

Pavel

Johannes said:
Sounds like you want to use SFINAE

template<typename> struct tovoid {
typedef void type;
};

template<typename T, typename = void>
struct TC {
/* generic ... */
};

template<typename T>
struct TC<T, typename tovoid<typename T::Type> > {
/* T has Type nested type */
};
Thanks Johannes -- this fits perfectly!

-Pavel
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top