具有不同const限定符的两个类型之间的转换

conversion between 2 types with different const qualifiers

本文关键字:两个 类型 转换 之间 const      更新时间:2023-10-16

这是我想使用的代码的一个简短示例:

template <class T>
class B
{
public :
    bool func1(const T& t)
    {
        // do something
    }
};

class A
{
    B<int*> b;
public:
    void func2(const int* a)
    {
        b.func1(a);
    }
};

我得到这个错误:

错误C2664: 'B::func1':无法将参数1从'const int *'转换为'int *const &'

是一种不改变函数声明和不使用const_cast的方法来解决这个问题?

编辑:

问题背后的一些信息

  1. B实际上是我写的一个容器类(让我们说一个列表)

  2. A是一个使用列表的类

  3. func1是一个需要查找元素是否在列表中的函数

  4. func2是接收要从列表中删除的元素的函数

int*被用来实例化B时,

void func1(const T& t) {}

等价于:

void func1(int* const& t) {}

类型为const int*的参数与int* const&不兼容

你需要重新考虑一下你的功能。

A中使用B<int>而不是B<int*>可能是您正在寻找的。

class A
{
      B<int> b;
   public:
      void func2(const int* a)
      {
         b.func1(*a);
      }
};

如果你想要const指针的引用,那么试试这个:

B<const int*> b;

如果您确定您传递的内容最初不是const int *(也就是说,您最初有一个int *,它在途中的某个地方变成了const int *),那么您可以这样做:

b.func1(const_cast<int *>(a));

注意,如果不满足我提到的前提条件,这很容易导致未定义的行为。这很令人困惑,因为函数的用户不希望函数改变指针指向的对象。最好从一开始就传入一个int *:

void func2(int* a) 
{
    b.func1(a);
}

根据你最近的评论,我认为这是你想要的:

template <class T>
class B
{
    typedef typename std::remove_pointer<T>::type base_type;
    typedef typename std::add_const<base_type>::type const_base_type;
    typedef typename std::add_pointer<const_base_type>::type pointer_const_base_type;
public :
    void func1(const pointer_const_base_type& t)
    {
        std::cout << t << std::endl;
    }
};

给定T = base_type *,我费力地构建pointer_const_base_type = const base_type *。现在func1引用了那个const base_type *。注意,这里假设T是指向某物的指针;您必须对它进行更多的操作才能用于非指针。