Template specialization as built-in type

R

Ruben Campos

¿Is there any way -other than reimplementing- to make a partially or totally
specialized template to be equivalent to a built-in type?

I ask this for apply it over class templates implementing mathematical
entities -as polynomes and vectors- where entities of order equal to 1 are
equivalent to scalar types. For example:

template <typename TScalar, unsigned int N>
class CPolynome
{
// ...
};

template <typename TScalar>
class CPolynome <TScalar, 1>
{
// CPolynome <TScalar, 1> is equivalent to TScalar, but ¿how is it
implemented?
};

I've tried two ways, both wrong:

template <typename TScalar> typedef TScalar CPolynome <TScalar, 1>;
template <typename TScalar> class CPolynome <TScalar, 1> : public TScalar
{ /* ... */ };

The only right way I've found is to provide full implementation to CPolynome
<TScalar, 1> in order to work as the built-in type.
 
K

Kanenas

¿Is there any way -other than reimplementing- to make a partially or totally
specialized template to be equivalent to a built-in type?
Type equivalent, no. Automatically convert, yes.
template <typename TScalar>
class CPolynome <TScalar, 1>
{
private:
TScalar _val;
public:
CPolynome(const TScalar& from=TScalar()) : _val(from) {}
operator TScalar&() { return _val; }
/* If TScalar may be an aggregate with an expensive copy
constructor, uncomment the next member, comment
'operator TScalar() const' and a const CPolynome will
create no temporary.
*/
//operator const TScalar& () const { return _val; }
/* Otherwise a const CPolynome will convert to a temporary copy
of _val.
*/
operator TScalar() const { return _val; }
/* operator=(const TScalar&) isn't strictly necessary, but
will cut down on temporaries.
*/
CPolynome& operator=(const TScalar& from) {_val = from;}
};

Consider:

CPolynome<int, 1> a=2, b=3, sum;
sum = a+b;

"sum = a+b" compiles the same as:

sum =static_cast<int>(a)+static_cast<int>(b);

Note "static_cast<int>(a)" will call a.operator const int&().

Without CPolynome<TScalar, 1>::eek:perator=(const TScalar&), the line
would compile to something like:
sum = CPolynome<int, 1>(static_cast<int>(a)+static_cast<int>(b));
which isn't bad. It just involves the creation of a temporary
CPolynome<int, 1>.

Template parameter deduction may be defeated by instances of
CPolynome<TScalar, 1> and TScalar, in which case tempate parameters
must be explicit. For example:

template <typename T> T foo(T a, T b);
...
foo(sum, 1); //error: no foo(CPolynome<int, 1>&, int)
foo<CPolynome<int, 1> >(sum, 1); //good
foo<int>(sum, 1); //good

Kanenas
 

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
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top