templated ctor with non-type template argument

J

John Harrison

I want to write a templated constructor with a non-type template argument,
like this.

class X
{
public:
X() : val(0) {}

template <int I>
X(X const&, X const&) : val(I) {}

private:
int val;
};

This compiles but I have no idea how to 'call' this constructor. Is it
possible?

(Essentially I have a single algorithm to construct an X from two other X's
and I would like to customise that algorithm at compile time using an
integer parameter).

john
 
R

Rob Williscroft

John Harrison wrote in in
comp.lang.c++:
I want to write a templated constructor with a non-type template
argument, like this.

class X
{
public:
X() : val(0) {}

template <int I>
X(X const&, X const&) : val(I) {}

private:
int val;
};

This compiles but I have no idea how to 'call' this constructor. Is it
possible?

No.

(Essentially I have a single algorithm to construct an X from two
other X's and I would like to customise that algorithm at compile time
using an integer parameter).

Wrap the integer up in a type, say boost::mpl::int_<> if you have
boost (*)

eg:

template < int I >
struct int_
{
};

your ctor becomes:

tempalte < int I >
X( X const&, X const&, int_< I > const & /* unused */)
: val( I )
{
}


usage:

int main()
{
X a, b, x( a , b, int_< 1 >() );
}

HTH.

*) boost::mpl -> http://www.boost.org/libs/mpl/doc/

Rob.
 
J

John Harrison

Rob Williscroft said:
John Harrison wrote in in
comp.lang.c++:


Wrap the integer up in a type, say boost::mpl::int_<> if you have
boost (*)

eg:

template < int I >
struct int_
{
};

your ctor becomes:

tempalte < int I >
X( X const&, X const&, int_< I > const & /* unused */)
: val( I )
{
}


usage:

int main()
{
X a, b, x( a , b, int_< 1 >() );
}

HTH.

OK, that's clever. Thanks.

john
 

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

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top