2010-07-24 90 views
2

假設在C非const版本我有功能Ç常量/相同功能

type* func (type*); 
const type* func_const (const type*); 

,使得它們都具有完全相同的內部邏輯。

有沒有辦法我可以將兩個合併成一個函數,如果給定一個const類型,它會返回一個const類型;如果給定一個非const類型,它會返回一個非const類型?如果不是,處理這個問題的好方法是什麼?也許通過顯式投射定義另一個?

+0

你可以改爲C++嗎? – Anycorn 2010-07-24 17:42:46

+0

沒有(fillllller) – 2010-07-24 17:44:05

回答

10

你不能自動執行它,但你肯定可以在單個位置的邏輯:在返回非

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); 
} 
2

做這樣的標準C庫函數做,只是把一個const限定參數符合條件的結果。 (見strchr,strstr等)這是最實用的。

+1

但打破了類型安全。 – 2010-07-24 17:55:15