-1

I just learn the declval keyword in c++ and I was wondering why in the following code (std::add_rvalue_reference<Foo>::type).constFunc7() x = 3; is not compiling. Isn't it the same thing as decltype(declvalCustom<Foo>().constFunc7()) y = 3; with the template declaration of declvalCustom?

#include <iostream>
#include <utility>

using namespace std;

struct Foo
{
    int constFunc7() { return 7; }
};

template< class T >
typename std::add_rvalue_reference<T>::type declvalCustom();

std::add_rvalue_reference<Foo> helper();

int main()
{
    // decltype(helper().constFunc7()); // not working
    // (std::add_rvalue_reference<Foo>::type).constFunc7() x = 3; // not working
    decltype(declvalCustom<Foo>().constFunc7()) y = 3; // ok
    decltype(std::declval<Foo>().constFunc7()) z = 3; // ok
    return 0;
}
roi_saumon
  • 489
  • 4
  • 13
  • 2
    1. `main` returns `int`, not `void`; 2. `std::add_rvalue_reference::type` is a type, so how can you think you call a member function on it? – Enlico Apr 06 '23 at 08:29
  • Did you mean `decltype` keyword? `std::declval` fundamentally is a function, even if it cannot be called. – Karl Knechtel Apr 06 '23 at 08:35

1 Answers1

1

declval is not a keyword. std::declval is a function template, that can only legally appear in unevaluated contexts. Your declValCustom is also a function template with similar properties.

std::add_rvalue_reference<Foo>::type is a type, not an expression, so you can't use it as a subexpression.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • Thank you for the answer. If the problem is that `std::add_rvalue_reference::type` is a type and not an expression, why doesn't it work with the `helper()` expression? – roi_saumon Apr 06 '23 at 08:54
  • `std::add_rvalue_reference helper();` declares a function of 0 arguments which returns `std::add_rvalue_reference`, so `helper()` is an expression of type `std::add_rvalue_reference`, which is a trait type, not `Foo &&`, in particular it doesn't have a member function `constFunc7`. You are missing `::type` from the declaration of `helper` – Caleth Apr 06 '23 at 12:59