C++模板可以检测特定类型的成员吗
can C++ template detect members of specific type?
C++模板是否可以检测特定类型的成员?如以下代码所示,
template <typename T>
class Element {
};
template <typename T>
class Container {
public:
Container() {
// check if T has member which type is "Element<whatever>"
// how many Element<whatever>s?
// offset?
}
};
我有一个名为Container
的模板类,我想检查一下:
- 如果传入类型
T
具有成员,则哪种类型是Element<whatever>
- 如果是,我能得到
Element<whatever>
的成员数量吗 - 如果是的话,我能把偏移量加到课的开头吗
解释更多关于需求3:的信息
当我得到一段由reinterpret_cast<T>
投射的数据时,我想要访问这些字段(如果存在(
如果Container<T>
的T
是聚合,则这在C++20中是可行的;我使用boost::pfr库,因为它简化了这个习惯用法,但它很容易手动重新实现(boost:;pfr的源代码读起来很简单(
#include <boost/pfr.hpp>
template<typename T, typename Target>
auto count_members_of_type()
{
unsigned int count = 0;
boost::pfr::for_each_field<T>(T{}, [&] <typename U> (U&&) {
count += std::is_same_v<std::remove_reference_t<U>, Target>;
});
return count;
}
给定
struct Foo {
Element<int> a, b;
Element<float> c;
std::string d;
};
然后
count_members_of_type<Foo, Element<int>>() == 2
在gcc.godbolt.org上运行示例:https://gcc.godbolt.org/z/srhn8GfWb
相关文章:
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员