Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deducing const from operator T &()

Tags:

c++

c++11

Issue is that different compiler's produces different output (clang/gcc) and so that makes me think that this usage is undefined behavour. However my goal is to deduce const when assigning reference.

Output with:
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;
}
like image 561
Luka Rahne Avatar asked Dec 15 '15 12:12

Luka Rahne


1 Answers

One possibility based on idea of 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;
};
like image 131
Luka Rahne Avatar answered Oct 29 '22 06:10

Luka Rahne