Class template with both pointer type and regular type

前端 未结 2 917
说谎
说谎 2020-12-28 23:15

I define a Node class with template for its value type

template
class Node {
  T val;
  public:
    Node (T & v) : val (v) {}
    ...
             


        
相关标签:
2条回答
  • 2020-12-28 23:59

    Well, there is one more way of doing this. You should use type traits, they are evaluated at compile time. This is how you can modify.

    template<class T>
    class Node {
      T val;
      public:
        Node (T & v) : val (v) {}
        ...
        void print() { 
          if(std::is_pointer<T>::value)
            cout << *v << endl;
          else
            cout << v << endl;
        }
    }
    
    0 讨论(0)
  • 2020-12-29 00:00

    See this: C++ template specialization, calling methods on types that could be pointers or references unambiguously

    The same technique should work here, allowing you to deal with the val as a reference (or a pointer) uniformly in both cases.

    CRTP may help reduce code duplication, allowing for common code for two specializations without any overhead, as well.

    Note that ownership semantics get tricky when you sometimes use a pointer and sometimes an instance -- what is the lifetime of val if sometimes it is a pointer of an argument, and other times it is a copy of the argument, and how to you enforce it?

    0 讨论(0)
提交回复
热议问题