Is it possible to pass a type and a pointer of that type to a c++ template class using a single parameter of a template class?

流过昼夜 提交于 2019-12-25 01:44:29

问题


Is it possible to pass a type and a pointer of that type to a c++ template class using a single parameter of a template class?


I want to take a pointer to a embedded hardware address (an uart) which has the type UART_HandleTypeDef and deduce that type information instead of manually declaring it. Something akin to:

template<typename T> class serial{
public:
    T::value_type* uart = T;
};

I want to get away from the normal notation which would require me to state the type and then pass a pointer:

template<typename T,T* ptr> class c{
public:
  T* _ptr = ptr;
};

update: I forgot to mention: pre C++11 is supported by my compiler. It supports some C++11 features


回答1:


Since C++17, you might have

template <auto* ptr> class c
{
public:
    auto _ptr = ptr;
};

Before that,

template <typename T, T* ptr> class c
{
public:
    T* _ptr = ptr;
};

is the way to go.

MACRO can help since C++11

#define TEMPLATE_AUTO(...) decltype(__VA_ARGS__), __VA_ARGS__

c<TEMPLATE_AUTO(my_ptr)> v;


来源:https://stackoverflow.com/questions/57891624/is-it-possible-to-pass-a-type-and-a-pointer-of-that-type-to-a-c-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!