从模板化基类取消隐藏模板化的强制转换操作符

时间:2021-11-09 23:00:34

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.

有没有办法做到这一点?上面的代码不起作用,因为它告诉我我不能模板使用声明。

2 个解决方案

#1


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.

using声明不能引用模板ID,命名空间,范​​围枚举器,基类的析构函数或用户定义转换函数的成员模板的特化。

#2


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 :

模板化转换运算符将通过参数相关查找提供。本质上,因为你总是使用B实例进行转换,所以不会隐藏A的强制转换运算符:

#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

演示

#1


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.

using声明不能引用模板ID,命名空间,范​​围枚举器,基类的析构函数或用户定义转换函数的成员模板的特化。

#2


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 :

模板化转换运算符将通过参数相关查找提供。本质上,因为你总是使用B实例进行转换,所以不会隐藏A的强制转换运算符:

#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

演示