2015-06-12 8 views
18

Si consideri il codice:Qual è l'equivalente di std :: is_const per i riferimenti a const?

int const x = 50; 
int const& y = x; 
cout << std::is_const<decltype(x)>::value << endl; // 1 
cout << std::is_const<decltype(y)>::value << endl; // 0 

Questo ha senso, perché y non è un riferimento const, è un riferimento a un const.

C'è un foo tale che std::foo<decltype(y)>::value è 1? Altrimenti, come sarebbe definire il mio?

+1

Does 'std :: aiuto remove_reference'? –

+3

Sicuramente vuoi dire 'std :: is_const :: value'? E 'std :: is_const :: type> :: value' produce il valore che stai cercando. – Andrew

risposta

16

Uso remove_reference:

#include <string> 
#include <iostream> 
#include <type_traits> 
using namespace std; 

int main() 
{ 
    int const x = 50; 
    int const& y = x; 
    cout << std::is_const<std::remove_reference<decltype(x)>::type>::value << endl; // 1 
    cout << std::is_const<std::remove_reference<decltype(y)>::type>::value << endl; // 1 

    return 0; 
} 

See on coliru

+0

Perché rimuovere il riferimento a un numero intero non di riferimento? – Adam

+0

@WhyCry Per mostrare che funziona indipendentemente dal fatto che la cosa sottostante sia o meno un riferimento. Suppongo che OP cercasse una soluzione generale. – Borgleader

+0

'Cout << std :: :: is_const valore << endl;' // 1 'Cout << std :: is_const tipo> :: valore << endl;' Quindi questi sono essenzialmente gli stessi in un senso meno generale. (Le mie conclusioni) – Adam

Problemi correlati