2015-12-15 14 views
9

Problem polega na tym, że inny kompilator generuje różne wyniki (clang/gcc), co sprawia, że ​​myślę, że to użycie jest niezdefiniowane. Jednak moim celem jest wydanie const podczas przypisywania referencji.Deducing const z operatora T &()

wyjściowa:
dzyń-3.6 ->not const
gcc-4.8.4 ->const

#include <iostream> 
#include <type_traits> 

struct AnyReference { 

    template <typename RT> AnyReference(RT &a_var) : _ptr(&a_var) {} 

    template <typename T> operator T &() const 
    { 
     if (std::is_const<T>::value) { 
      std::cout << "const\n"; 
     } 
     else { 
      std::cout << "not const\n"; 
     } 
     return *reinterpret_cast<T *>(_ptr); 
    } 
    void *_ptr; 
}; 

int main() 
{ 
    int i(5); 
    AnyReference a(i); 
    const int &c = a; 
} 
+0

I niech czytasz ten post: http://stackoverflow.com/questions/32515183/const-auto-stdinitializer-list-difference-between-clang-and-gcc –

+3

Czy rozważałeś zapewnienie zarówno opery? tor T & 'i' operator const T & '? –

+0

@Ben Voigt Nie, nie, ale to świetne rozwiązanie! Działa zgodnie z oczekiwaniami. –

Odpowiedz

2

Jedna z możliwości opiera się na idei Ben Voight

struct AnyReference { 

    template <typename RT> AnyReference(RT &a_var) : _ptr(&a_var) {} 

    template <typename T> operator T &() const { return operatorTand<T>(); } 

    template <typename T> operator const T &() const 
    { 
     return operatorTand<const T>(); 
    } 

    private: 
    template <typename T> T &operatorTand() const 
    { 
     if (std::is_const<T>::value) { 
      std::cout << "const\n"; 
     } 
     else { 
      std::cout << "not const\n"; 
     } 
     return *reinterpret_cast<T *>(_ptr); 
    } 

    void *_ptr; 
}; 
Powiązane problemy