[英]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&
不兼容。
您需要重新考慮一下您的功能。
更新
使用B<int>
而不是B<int*>
在A
可能是你在找什么。
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
是指向某事物的指針; 你必須更多地使用它來為非指針工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.