badmaash
badmaash

Reputation: 4845

How do i fix conversion error in the following code?

I have a template class:

template<class T>
class A{
  T a, b;
  public:
  A(A<T> const & o) : a(o.a), b(o.b){}
  A(T const & _a, T const & _b) : a(_a), b(_b){}
};

A<double> d(1.2, 4.5);
A<float> f = d; //error: conversion from A<double> to non-scalar type A<float> requested

How do i define a conversion function for my class? My compiler is g++ 4.7.0

Upvotes: 0

Views: 113

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

You could make a template constructor:

template<class T>
class A{
    T a, b;
public:

    template<class U>
    A(A<U> const & rhs) : a(rhs.a), b(rhs.b) {}

    A(T const & _a, T const & _b) : a(_a), b(_b){}
};

Then you should be able to convert any class A<U> to any class A<T> as long as U is convertible to T.

Upvotes: 4

Superman
Superman

Reputation: 3081

What you're trying to do is not a good idea.
However, to get over the compiler error, you can specialize the class -

template <>
class A<float>
{
    public:
    A(A<double> const & o) {}
};

Upvotes: 0

Related Questions