1

ユニバーサル参照がトップレベルの cv 資格を失う理由を誰か教えてもらえますか? 次のコードの 2 番目と 3 番目の関数呼び出しで、出力が 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
4

1 に答える 1

4

R. Martinho が指摘したように、参照にはトップレベルの const がありません。

低レベルの const-ness をチェックするには、以下を使用できますstd::remove_reference

cout << "T is const: " << boolalpha
     << is_const<typename remove_reference<decltype(item)>::type>::value
     << endl;
于 2013-07-04T14:31:20.107 に答える