具有不同const限定符的2种类型之间的转换

Ada*_*dam 3 c++ pointers const const-cast template-classes

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

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);
    }
};
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

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

是一种解决这个问题的方法,而无需更改函数声明和不使用const_cast?

编辑:

问题背后的一些信息

  1. B 实际上是我写的容器类(比如列表)

  2. A 是使用该列表的类

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

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

R S*_*ahu 6

int*用于实例化时B,该函数

void func1(const T& t) {}
Run Code Online (Sandbox Code Playgroud)

相当于:

void func1(int* const& t) {}
Run Code Online (Sandbox Code Playgroud)

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

您需要重新考虑一下您的功能.

更新

使用B<int>而不是B<int*>in A可能是你正在寻找的.

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