samedi 1 juillet 2023

Why does the correct implementation of std::addressof require compiler support?

From possible implementation of std::addressof on https://en.cppreference.com/w/cpp/memory/addressof, it states that "correct implementation of std::addressof require compiler support". Why is it the case?

I tried out the implementation on https://godbolt.org/z/vnzbs9aTG and it worked as expected.

#include <iostream>
#include <string>
#include <type_traits>

template<class T>
typename std::enable_if<std::is_object<T>::value, T*>::type addressof_impl(T& arg) noexcept
{
    return reinterpret_cast<T*>(
               &const_cast<char&>(
                   reinterpret_cast<const volatile char&>(arg)));
}
 
template<class T>
typename std::enable_if<!std::is_object<T>::value, T*>::type addressof_impl(T& arg) noexcept
{
    return &arg;
}

struct Student {
    std::string name{};
    int age{};
};

int main() {
    Student s;
    std::cout << addressof_impl(s);
    return EXIT_SUCCESS;
}

Aucun commentaire:

Enregistrer un commentaire