dimanche 30 avril 2023

Why std::declval cannot be directly replaced by std::add_rvalue_reference

According to https://en.cppreference.com/w/cpp/utility/declval, the possible implementation of declval is following:

template<typename T>
constexpr bool always_false = false;
 
template<typename T>
typename std::add_rvalue_reference<T>::type declval() noexcept
{
    static_assert(always_false<T>, "declval not allowed in an evaluated context");
}

I am trying to replace the use case of std::declval<T>() with std::add_rvalue_reference<Test>::type but it doesn't compile. Why is that?

Following is my testing code snippet:

#include <iostream>
#include <type_traits>
#include <utility>

struct Test {
    int func() {
        return 1;
    }
};

template<typename T>
constexpr bool always_false = false;
 
template<typename T>
typename std::add_rvalue_reference<T>::type Decltype() noexcept
{
    static_assert(always_false<T>, "declval not allowed in an evaluated context");
}

int main() {
    if (std::is_same_v<decltype(std::add_rvalue_reference<Test>::type.func()),int>) {
        std::cout <<"same\n";
    } else {
        std::cout <<"different\n";
    }
}

Aucun commentaire:

Enregistrer un commentaire