C++模板可以检测特定类型的成员吗

can C++ template detect members of specific type?

本文关键字:类型 成员 检测 C++      更新时间:2023-10-16

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的模板类,我想检查一下:

  1. 如果传入类型T具有成员,则哪种类型是Element<whatever>
  2. 如果是,我能得到Element<whatever>的成员数量吗
  3. 如果是的话,我能把偏移量加到课的开头吗

解释更多关于需求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