是否有更简单的方法来获取包含在智能指针中的类的成员?

Alw*_*ing 11 c++ c++11

为神秘的标题道歉.假设这个定义:

struct TestNode {
    using CostType = double;
};
Run Code Online (Sandbox Code Playgroud)

我希望能够像这样定义一个类模板:

template <typename NodeP,
          typename MyPolicy = /* CostType of the node type corresponding to NodeP */ >
struct TT {
};
Run Code Online (Sandbox Code Playgroud)

在上面的定义中,NodeP可以是指向定义的类的简单指针或智能指针CostType,例如TestNode.问题:如何指定MyPolicy模板参数的默认值为CostType对应的节点类型NodeP

这是我到目前为止的解决方案:

// 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 {
};
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法解决这个问题?特别是,我错过了一个标准的库设施,可以使解决方案更简单吗?

Анд*_*кий 7

标准库中有一个名为的辅助类pointer_traits.看起来它正是你想要的.

在线运行

#include <iostream>
#include <memory>
#include <typeinfo>

struct TestNode {
    using CostType = double;
};

template <typename NodeP,
          typename MyPolicy = typename std::pointer_traits<NodeP>::element_type::CostType>
struct TT {
    typedef MyPolicy xxx;
};

int main () {
    TT<TestNode*>::xxx a = 2.8;
    TT<std::unique_ptr<TestNode>>::xxx b = 3.14;
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)