[英]C const/non-const versions of same function
假設在CI中具有這些功能
type* func (type*);
const type* func_const (const type*);
這樣它們都具有完全相同的內部邏輯。
有沒有辦法可以將兩者合並為一個函數,如果給定一個const類型,它返回一個const類型; 如果給定一個非const類型,它返回一個非const類型? 如果沒有,處理這個問題的好方法是什么? 也許通過顯式鑄造來定義另一個?
你不能自動化它,但你當然可以在一個位置擁有邏輯:
const type* func_const (const type*)
{
/* actual implementation goes here */
}
type* func (type* param)
{
/* just call the const function where the "meat" is */
return (type*)func_const(param);
}
像標准C庫函數那樣做,只需要在返回非const限定結果時獲取const限定參數。 (見strchr
, strstr
等)這是最實用的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.