问题
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