2013-07-04 17 views
1

誰能告訴我爲什麼通用參考放寬頂級簡歷資格?我期望在下面的代碼中,第二個和第三個函數調用的輸出對於const將返回true。通用參考忽略頂級簡歷資格

#include <iostream> 
#include <type_traits> 

using namespace std; 

template<class T> 
void print(T const &value){ 
    cout << "Printing from const & method: " << value << endl; 
} 

template<class T> 
void print(T const *value){ 
    cout << "Printing from const * method: " << *value << endl; 
} 

template<class T> 
void f(T&& item){ 
    cout << "T is const: " << boolalpha << is_const<decltype(item)>::value << endl; 

    print(std::forward<T>(item)); 
} 


int main(){ 

    f(5); 

    const int a = 5; 
    f(a); 

    const int * const ptr = &a; 

    f(ptr); 

    return 0; 
} 

輸出:

T is const: false 
Printing from const & method: 5 
T is const: false 
Printing from const & method: 5 
T is const: false 
Printing from const * method: 5 
+2

引用永遠不要有頂級常量。 –

+0

Ahhhhh。究竟。謝謝。你可以用const加前綴嗎? –

+0

你指的是哪個函數調用? – 0x499602D2

回答

4

爲R. Martinho指出,引用不具備頂級常量。

要檢查下級常量性,你可以使用std::remove_reference

cout << "T is const: " << boolalpha 
    << is_const<typename remove_reference<decltype(item)>::type>::value 
    << endl; 
+0

:)謝謝大家。真棒。 –