简体   繁体   中英

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?

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM