Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does decltype fail with static member function returning auto in C++? [duplicate]

Tags:

c++

c++17

I'm trying to define a type alias inside a class using the return type of a static private member function that returns a tuple. However, the compiler throws an error when I try to use decltype on the function.

Here's a minimal reproducible example:

#include <tuple>
#include <string>

struct S {
    std::string name;
    int birthdate;
};

class Foo {
private:
    static inline auto keyFor(const S& s) {
        return std::make_tuple(s.name, s.birthdate);
    }

    using Key = decltype(keyFor(std::declval<S>()));  // <----- fails here

public:
    // ...
};

Compiler error:

error: use of 'static auto Foo::keyFor(const S&)' before deduction of 'auto'

I thought this would work because keyFor is static, and I'm calling it with std::declval<S>() to simulate an S instance. But it seems the compiler can't deduce the return type at the point where decltype is used.

Moving keyFor into a detail namespace out of the class works, but is there a way to keep it where it is?

like image 634
user3612643 Avatar asked Sep 03 '25 04:09

user3612643


1 Answers

This can be solved by specifying the return type of KeyFor:

#include <tuple>
#include <string>

struct S {
    std::string name;
    int birthdate;
};

class Foo {
private:
    static inline auto keyFor(const S& s) -> decltype(std::make_tuple(s.name, s.birthdate)){
        return std::make_tuple(s.name, s.birthdate);
    }

    using Key = decltype( keyFor(std::declval<S>()) );  

public:
    // ...
};
like image 132
Patricio Loncomilla Avatar answered Sep 04 '25 20:09

Patricio Loncomilla