Have a template parameter that can be pointer type or non-pointer type

后端 未结 3 1151
北海茫月
北海茫月 2021-01-17 16:38

Suppose I have something like:

template 
void do_something(T t){
  pass_it_somewhere(t);
  t->do_something();
}

Now it wo

3条回答
  •  臣服心动
    2021-01-17 17:16

    You could create a dereference mechanism as below:

    template
    std::enable_if_t::value, std::remove_pointer_t&> dereference(T& t) { 
      return *t; 
    }
    
    template
    std::enable_if_t::value, T&> dereference(T& t) {
      return t;
    }
    

    and use it in your function as:

    template 
    void do_something(T t){
      pass_it_somewhere(dereference(t));
      dereference(t).do_something();
    }
    

    Live Demo

    This way you'll have to do only with concrete versions of T.

提交回复
热议问题