wind2412
wind2412

Reputation: 1069

How do I use an alias of the static inner class member?

As following codes, I'd like to use an alias to avoid the tedious writing of the static member of inner class NIL.

//in RBTree.hpp
template <typename T, typename Comp>
class RBTree{
public:
    struct TreeNode{
       ...
       static TreeNode* NIL = new TreeNode();
       ...
    }
}

//in RBTree_IMPL.hpp
template <typename T, typename Comp>
using NIL = ???

I want to use the keyword 'using' to avoid the tedious writing such as :

//in BST.hpp
template <typename T, typename Comp>
class BST{
public:
    struct TreeNode{
        ...
    }
}

//in BST_IMPL.hpp
template <typename T, typename Comp>
using TreeNode = typename BST<T, Comp>::TreeNode;

As the above, it will be simple. So I want to find a way of using static inner member as above. Thx!

Upvotes: 1

Views: 637

Answers (1)

MikeMB
MikeMB

Reputation: 21156

using is used to create an alias for a type. You want to create an alias for a variable, which in c++ is a reference. Thanks to c++14's template variables the following should work:

//in RBTree_IMPL.hpp
template <typename T, typename Comp>
auto& NIL = RBTree<T,Comp>::TreeNode::NIL;

Btw.: I don't think the in-Class initialization of NIL will work as you showed in your example, as it isn't a constexpr. You probably have to define and initialize it outside of the class.

Edit:

If you are stuck with a c++11 compiler, the best you can afaik do is using a function that returns a reference to the pointer:

template <typename T, typename Comp>
auto NIL() -> typename RBTree<T,Comp>::TreeNode*& {
   return RBTree<T,Comp>::TreeNode::NIL;
} 

//usage e.g.:
NIL<int,std::less<int>()-> ...

Upvotes: 1

Related Questions