Template default constructor possible?

I

Ian Collins

I've never had cause to try this before, but is it possible to have a
template default constructor?

I wish to pass the type of a singleton to a class and use the static
methods of that singleton object in the class, for example:

template <typename Item>
bool getItemValue() {
return Item::getValue();
}

struct Item { static bool getValue(); };

struct X
{
typedef bool (*GetFn)();

const GetFn getFn;

template <typename T> X( const T& )
: getFn( getItemValue<T> ) {}
};

works, but requires a public default constructor for T.
 
A

Alf P. Steinbach

* Ian Collins:
I've never had cause to try this before, but is it possible to have a
template default constructor?

I wish to pass the type of a singleton to a class and use the static
methods of that singleton object in the class, for example:

template <typename Item>
bool getItemValue() {
return Item::getValue();
}

struct Item { static bool getValue(); };

struct X
{
typedef bool (*GetFn)();

const GetFn getFn;

template <typename T> X( const T& )
: getFn( getItemValue<T> ) {}
};

works, but requires a public default constructor for T.

There's no way to call a templated constructor with no arguments. So
you can have that templated constructor, but not use it. However, it's
no big deal create an argument type that can carry a type for you, e.g.

template< typename T > struct UseMethodsOf {};
template< typename T >
UseMethodsOf<T> useMethodsOf(){ return UseMethodsOf<T>(); }

struct X
{
...
template< typename T >
X( UseMethodsOf<T> ): getFn( &getItemValue<T> ) {}
};

...
X foo( useMethodsOf<Whatever>() );


Cheers, & hth.,

- Alf
 
I

Ian Collins

Alf said:
* Ian Collins:

There's no way to call a templated constructor with no arguments. So
you can have that templated constructor, but not use it. However, it's
no big deal create an argument type that can carry a type for you, e.g.

template< typename T > struct UseMethodsOf {};
template< typename T >
UseMethodsOf<T> useMethodsOf(){ return UseMethodsOf<T>(); }
Thanks Alf, I forgot the good old "use another level of indirection" rule!
 

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,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top