2015-03-19 109 views
6

存在關於重載函數的問題。看看這個代碼:通過函數指針重載函數

#include<iostream> 

void fv(int){} 
void fc(const int){} 
void fvr(int&){} 
void fcr(const int&){} 

void fm(void(*fun)(const int)) 
{ 
    std::cout << "Constant called" << std::endl; 
} 

//void fm(void(*fun)(int)) 
//{ 
// std::cout << "non Constant called" << std::endl; 
//} 

void fm(void(*fun)(const int&)) 
{ 
    std::cout << "Constant ref called" << std::endl; 
} 

void fm(void(*fun)(int&)) 
{ 
    std::cout << "non Constant ref called" << std::endl; 
} 

int main() 
{ 
    fm(&fc); 
    fm(&fv); 
    fm(&fvr); 
    fm(&fcr); 
    return 0; 
} 

,如果你取消註釋void fm(void(*fun)(int))功能你會發現編譯器不能靜態地指針上,關於接受常量的值由函數值和指針接受參數的函數重載功能。此外,如果您取消void(*fun)(const int)的註釋並評論void(*fun)(const int),則所有編譯成功。但是,如果我們使用引用它編譯好。不明白爲什麼,請你解釋一下嗎?這是否意味着通過值和const值接受參數的函數指針是相同的類型?

UPD: Top-level const doesn't influence a function signature 有一個很好的解釋,爲什麼頂級const應該被刪除。

回答

3

是的,頂級常量將被丟棄。從GCC錯誤

的「無效FM(無效(*)(INT))」

正如你看到的常量重新定義被丟棄。從N3376 8.3.5

報價/ 5

生產參數類型的列表後,任何頂級 cv修飾符修改的參數類型形成 函數類型時被刪除。

+0

爲什麼它的價值下降,而不是參考下降? – brachistochron 2015-03-19 09:11:41

+0

@brachistochron只是因爲引用中的const不是頂級const。 – ForEveR 2015-03-19 09:21:46

+0

是的,明白了,謝謝。但仍然無法理解爲什麼它以這種方式工作=) – brachistochron 2015-03-19 09:24:37

2

是的,你不能超載基於非指針/非引用參數的常量內斯功能,請參閱: Functions with const arguments and Overloading

這反過來又意味着,指針的值和常量的值函數接受參數是同一類型。