2015-12-15 29 views
9

Sorun, farklı derleyicilerin farklı çıktılar üretmesidir (clang/gcc) ve bu nedenle bu kullanımın tanımlanmamış bir davranış olduğunu düşünmemi sağlar. Ancak amacım referans atarken const sonucunu çıkarmaktır.Operatörden const (const) algılama T &()

Çıktı ile:
clang-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

sana okuyalım Bu gönderiyi takip edebilirsiniz: http://stackoverflow.com/questions/32515183/const-auto-stdinitializer-list-difference-between-clang-and-gcc –

+3

Her iki operayı da sağlamayı düşündünüz mü tor T & 've' operatör yapısı T & '? –

+0

@Ben Voigt Hayır Yok, ama bu harika bir çözüm! Beklendiği gibi çalışır. –

cevap

2

Bir olasılık Ben Voight fikrine dayalı

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; 
}; 
İlgili konular