Matouš Vrba
Matouš Vrba

Reputation: 174

Metafunction returning element type using decltype

I have the following MWE:

#include <memory>

template<typename T>
class Foo
{
    public:
        using message_type = T;
};

int main()
{
    std::shared_ptr<Foo<int>> ptr;
    decltype(ptr)::element_type::message_type number = 5;

    return 0;
}

and I would like to have a shorthand way to access the message_type type of a variable (such as ptr) without having to write out the whole decltype(ptr)::element_type::message_type part. I.e. have some alias to decltype(ptr)::element_type::message_type along the lies of message_type(ptr), which would have the same result.

My first idea was along the lines of

template<typename T>
using message_type = decltype(T)::element_type::message_type;

which seems logical at first, but it's actually mixing concepts of types and variables, so it does not even compile. My only working solution so far is

#define MSG_TYPE(x) decltype(x)::element_type::message_type

however I'd like to avoid using macros.

Is this even possible with current C++ metaprogramming? If so, what is the correct syntax?

Upvotes: 0

Views: 189

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36379

This works:

#include <memory>

template<typename T>
using message_type = typename T::element_type::message_type;

template<typename T>
class Foo
{
    public:
        using message_type = T;
};

int main()
{
    std::shared_ptr<Foo<int>> ptr;
    message_type<decltype(ptr)> number = 5;

    return 0;
}

I don't think you can do much better as you aren't allowed to use std::shared_ptr as a non-type template parameter so you have to do message_type<decltype(ptr)>, message_type<ptr> is not possible to implement (yet).

Upvotes: 4

Related Questions