jeudi 29 octobre 2015

Is there a simpler way to get to a member of a class wrapped in a smart pointer?

Apologies for the cryptic title. Suppose this definition:

struct TestNode {
    using CostType = double;
};

I would like to be able to define a class template like this:

template <typename NodeP,
          typename MyPolicy = /* CostType of the node type corresponding to NodeP */ >
struct TT {
};

In the above definition, NodeP can be either a simple or a smart pointer to a class that defines CostType, such as TestNode. The problem: how can one specify a default value for the MyPolicy template parameter to be the CostType of the node type corresponding to NodeP?

Here is my solution so far:

// like std::remove_pointer, but works with smart pointers as well
template <typename PT> struct my_remove_pointer {
    using type = typename
        std::remove_reference< decltype( *((PT)nullptr) ) >::type;
};

struct TestNode {
    using CostType = double;
};

template <typename NodeP,
          typename MyPolicy = typename my_remove_pointer<NodeP>::type::CostType>
struct TT {
};

Is there a simpler approach to this problem? In particular, am I missing a standard library facility that could make the solution simpler?

Aucun commentaire:

Enregistrer un commentaire