是否可以使用模板类的单个参数将类型和该类型的指针传递给c ++模板类? [英] 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?

查看:76
本文介绍了是否可以使用模板类的单个参数将类型和该类型的指针传递给c ++模板类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用模板类的单个参数将类型和该类型的指针传递给c ++模板类?

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?

我想使用一个指向类型为 UART_HandleTypeDef 的嵌入式硬件地址(一个uart)的指针,并推断出该类型信息,而不是手动声明它。类似于以下内容:

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;
};

更新:
我忘了:编译器支持C ++ 11之前的版本。它支持 一些 C ++ 11功能

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

推荐答案

自C ++ 17起,您可能拥有

Since C++17, you might have

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

在此之前,

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

是必经之路。

自C ++ 11起,MACRO就可以提供帮助

MACRO can help since C++11

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

c<TEMPLATE_AUTO(my_ptr)> v;

这篇关于是否可以使用模板类的单个参数将类型和该类型的指针传递给c ++模板类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆