3

I have a templated base class with a templated conversion operator. I would like to unhide this templated conversion operator in a derived class (because of dependent-name lookup).

template <class T>
class A
{
public:
  template <class U>
  operator A<U>() const { ... }
};

template <class T>
class B : public A<T>
{
public:
  template <class U>
  using A<T>::operator A<U>;
};

Is there a way to do this? The above code doesn't work, because it tells me I cannot template a using declaration.

Stijn Frishert
  • 1,543
  • 1
  • 11
  • 32
  • How are you trying to use the operator? – TartanLlama Nov 20 '15 at 14:51
  • To cast to a different representation of B with the same semantic value. Using it for a practice project in scientific units (like boost::units) and T is a std::ratio (like with std::chrono::duration). I'd like to see if I can abstract away the casting behaviour into a base class. – Stijn Frishert Nov 20 '15 at 14:53

2 Answers2

2

A using-declaration cannot refer to a template-id, to a namespace, to a scoped enumerator, to a destructor of a base class or to a specialization of a member template for a user-defined conversion function.

101010
  • 41,839
  • 11
  • 94
  • 168
1

The templated conversion operator will be available through argument dependent lookup. In essence since you're always going to the conversion with a B instance, A's cast operator won't be hidden :

#include <iostream>


template <class T>
class A
{
public:
  template <class U>
  operator A<U>() const { 
      std::cout << "The cast operator becomes availble through ADL\n";
      return {}; 
  }
};

template <class T>
class B : public A<T>
{
};

int main()
{
    A<double> a1; 
    A<int> a2;

    B<double> b1; 
    B<int>    b2; 

    a1 = b2; 
    a2 = b1; 
}

Demo

Lorah Attkins
  • 5,331
  • 3
  • 29
  • 63