Search code examples
c++option-typedecltype

Decltype of optional member


I'm trying to get the type from struct member that is in a std::optional<> that is the return type of a member function.

This is a simplified example:

struct Result
{
    int tag;
    int pos;
};

class Dict
{
public:
    std::optional<Result> search(const char *word)
    {
        return Result{ 1,2 };
    }
};

I'd like to be able to do something like this:

int main()
{
    Dict abc;
    decltype(abc.search(const char*)->pos) position;

    return 0;
}

Solution

  • If you pass an actual parameter to search, it will work (along with making search public):

    https://wandbox.org/permlink/0Q3mLW7SmQW4QshE

    #include <optional>
    
    struct Result
    {
        int tag;
        int pos;
    };
    
    class Dict
    {
    public:
        std::optional<Result> search(const char *word)
        {
            return Result{ 1,2 };
        }
    };
    
    int main()
    {
        Dict abc;
        decltype(abc.search("")->pos) position;
    
        return 0;
    }
    

    The parameter to search doesn't have to be valid (in terms of what your function expects - because it won't actually call it), it just has to be the correct type.

    If you want to deal directly with types, and not instances, as your comment suggests, then @Jarod42 points out you can use the following line for your variable declaration:

    decltype(std::declval<Dict>().search(std::declval<const char*>())->pos) position;

    https://wandbox.org/permlink/kZlqKUFoIWv1m3M3

    Though I probably don't need to point out how unreadable a ~70 character variable type is. I think if it were me I would either just use an int, or I would create a type alias for pos, e.g. using ResultPositionType = int; then use that within your Result struct, and again in main.