Search code examples
c++templatesconstants

Add const to reference


I want to add const to a reference type by typedef const A B;.

Somehow it doesn't work. Is this not possible in c++?

Test:

#include <type_traits>
typedef int& A;
typedef const A B;  // <-- Add const
// typedef std::add_const<A>::type B;  // also doesn't work.
static_assert(std::is_const<typename std::remove_reference<
        B>::type>::value, "is const");
int main() {
    return 0;
}

Compilation Error:

add2.cpp:5:1: error: static assertion failed: is const
 static_assert(std::is_const<typename std::remove_reference<
 ^~~~~~~~~~~~~

Solution

  • Somehow it doesn't work. Is this not possible in c++?

    Not with the way you are doing it. typedef does not work like pre-processor macros.

    typedef int& A;
    typedef const A B;
    

    does not translate to

    typedef int& A;
    typedef const int& B;
    

    The const in

    typedef const A B;
    

    applies to A, not the int part of A. Since references are immutable in C++, const A is the same as A from a type point view.


    You can use:

    typedef int const& B;
    

    If you want to derive it from A, you an use:

    using B = typename std::remove_reference<A>::type const&;
    

    If you are able to use C++14 or a later version, you can simplify that to:

    using B = std::remove_reference_t<A> const&;