2015-12-15 6 views
9

問題は、異なるコンパイラが異なる出力(clang/gcc)を生成するので、この使用法が未定義の動作であると考えることができます。しかし私の目標は、参照を割り当てる際にconstを推測することです。演算子からconstを引くT&()

出力で:
打ち鳴らす - 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

私はあなたが読んで聞かせて次の投稿:http://stackoverflow.com/questions/32515183/const-auto-stdinitializer-list-difference-between-clang-and-gcc –

+3

「オペラT& 'と'演算子const T& '? –

+0

@Ben Voigtいいえ私はしませんでしたが、それは素晴らしい解決策です!それは期待どおりに動作します。 –

答えて

2

一つの可能​​性ベン・ボイトの考えに基づいて

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; 
}; 
関連する問題