如何从模板获取类型和值信息

How to get type and value information from a template

本文关键字:取类型 信息 获取      更新时间:2023-10-16

目前我有一个看起来像这样的模板类:

template<typename T, T value>
struct MyStruct{
/* Stuff */
};

为了实例化它,我目前做了这样的事情:

typedef MyStruct<int, 123> struct_def;

我想做这样的事情:

typedef typename MagicTemplate<123>::type struct_def;

这将解决MyStruct<int,123>....

所以我的问题是我如何从模板参数中获取类型和值信息?

编辑

如果该解决方案可以与指针、成员指针、函数指针等一起使用,那也很好......

例如:

struct OtherStruct{
int memberA;
long memberB;
void foo(void);
};
static OtherStruct instance;

//Expands to MyStruct<memberA OtherStruct::*, &OtherStruct::memberA>
typedef typename MagicTemplate<&OtherStruct::memberA>::type struct_defA;
//Expands to MyStruct<OtherStruct*,&instance>
typedef typename MagicTemplate<&instance>::type struct_defB;
//Expands to MyStruct<void (OtherStruct::*)(void),&OtherStruct::foo>
typedef typename MagicTemplate<&OtherStruct::foo>::Type struct_defC;

你可以等C++17。

或者你平底船;拿一个类型TT应该与std::integral_constant兼容。 这使罐子在路上更进一步;但是,制作特定类型integral_constant的快捷方式比制作某些定制模板实例的快捷方式更干净。

例如,我可以123_k设置为std::integral_constant<int,123>类型。 做MyStruct<decltype(123_k)>.

作为奖励,您的MyStruct现在与template<class...>匹配,这使得某些元编程更容易。