确定结构体是否具有特定类型的成员
determine if struct has a member of specific type
假设我有一个结构体Foo
,我想确定Foo
里面是否有一个int
。
struct Foo { int a; char c; };
has_int<Foo>::value; // should be true
这是我实际想要的最基本的形式,检查特定的类型:
has_type<Foo, int>::value;
如果我知道怎么做,我可以把它转换成我的最终目标:
has_pointer<Foo>::value; // false
struct Bar { int a; void *b; };
has_pointer<Bar>::value; // true
至于我所尝试的,很难开始,我能想到的最好的是,如果我能得到一个结构体中包含的类型包,我可以写剩下的:
template <typename... Ts>
constexpr bool any_is_pointer() noexcept {
return (... || std::is_pointer_v<Ts>);
}
我所要求的似乎是不可能的。我找不到副本,但我很惊讶我找不到,所以它可能在那里。
就像其他人说的那样,现在你想要的东西是不可能用普通的c++实现任意类型的。但是,如果您能够提供特定的编译时信息以及您需要在其定义中操作的类型,那么您可以做您想做的事情。
您可以使用boost fusion库的适配器来实现这一点,它允许您调整现有结构以成为融合容器或定义新的结构来建模融合容器。然后,您可以使用任何boost::mpl算法来执行您想要执行的编译时检查类型。
考虑这个示例,使用struct foo
和所需的has_type
编译时算法:
#include <boost/fusion/adapted/struct/define_struct.hpp>
#include <boost/mpl/contains.hpp>
BOOST_FUSION_DEFINE_STRUCT(
(your_namespace), foo,
(int, a)
(char, c))
template<typename source_type, typename search_type>
struct has_type
{
typedef typename boost::mpl::contains<source_type, search_type>::type value_type;
static const bool value = value_type::value;
};
#include <iostream>
int main()
{
bool foo_has_int_pointer = has_type<your_namespace::foo, int*>::value;
bool foo_has_int = has_type<your_namespace::foo, int>::value;
std::cout << "foo_has_int_pointer: " << foo_has_int_pointer << "n";
std::cout << "foo_has_int: " << foo_has_int << "n";
your_namespace::foo my_foo;
my_foo.a = 10;
my_foo.c = 'x';
std::cout << "my_foo: " << my_foo.a << ", " << my_foo.c;
}
查看输出或使用这里的示例:http://ideone.com/f0Zc2M
可以看到,您使用BOOST_FUSION_DEFINE_STRUCT宏来定义struct
,您希望在编译时对其成员进行操作。Fusion提供了其他几个用于定义此类结构的宏,以及用于调整已定义结构的宏。点击这里查看。
当然,你可能已经知道它的缺点了。has_type
将只工作,如果source_type
是一个boost::mpl/boost::融合序列。对于您来说,这意味着您希望在编译时以这种方式推断的任何类型,都需要使用宏定义或调整。如果您正在编写的库旨在为任意库用户定义的类型工作,那么这可能是不可接受的。
相关文章:
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员