具有不同const限定符的两个类型之间的转换
conversion between 2 types with different const qualifiers
这是我想使用的代码的一个简短示例:
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的方法来解决这个问题?
编辑:问题背后的一些信息
B
实际上是我写的一个容器类(让我们说一个列表)A
是一个使用列表的类func1
是一个需要查找元素是否在列表中的函数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
是指向某物的指针;您必须对它进行更多的操作才能用于非指针。
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 可以将两个相同类型的连续数组视为一个数组吗?
- 如何允许模板参数中的类类型,仅当它有两个基类时
- 测试两个类型列表中的所有组合
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 堆栈分配的类类型.为什么两个 ID 实例的地址相同?
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 在C++中组合两个类型为T的数组
- 如何在不实例化两个c++类型的情况下确定这两个类型
- 这两个类型定义有什么区别?
- 使用共享指针在两个类型模板化类之间进行强制转换
- 交换类型列表中的两个类型
- 具有不同const限定符的两个类型之间的转换
- 带有两个类型参数的模板化函数在与错误检查宏一起使用时无法编译
- 如何在编译时推导出两个类型共有的继承树的根(如果存在)
- 检查两个类型在c++中是否相等
- 两个(类型)值和类型(值)有什么区别