有没有任何方法可以从C++中的成员指针类型派生对象类型
Is there any way to derive the object type from a member pointer type in C++
是否可以编写一个C++模板owner_of<...>
,使得给定以下代码:
struct X { int y; }
owner_of<&X::y>::type
是X
?
你几乎可以这样做(或者至少到目前为止我找不到更好的解决方案):
#include <string>
#include <type_traits>
using namespace std;
template<typename T>
struct owner_of { };
template<typename T, typename C>
struct owner_of<T (C::*)>
{
typedef C type;
};
struct X
{
int x;
};
int main(void)
{
typedef owner_of<decltype(&X::x)>::type should_be_X;
static_assert(is_same<should_be_X, X>::value, "Error" );
}
如果你介意使用decltype
,也许宏可以做到:
#define OWNER_OF(p) owner_of<decltype( p )>::type
int main(void)
{
typedef OWNER_OF(&X::x) should_be_X;
static_assert(is_same<should_be_X, X>::value, "Error" );
}
一种基于decltype:
的替代方案
template<typename T, typename C>
auto owner(T (C::*p)) -> typename owner_of<decltype(p)>::type { }
int main(void)
{
typedef decltype(owner(&X::x)) should_be_X;
static_assert(is_same<should_be_X, X>::value, "Error" );
}
相关文章:
- 访问C++中的类型成员
- 具有 STL 向量类型成员的类的复制内存
- 重载具有 2 个相同数据类型成员的构造函数
- std::void_t 和嵌套的非类型成员
- 返回对常量结构(指针类型)成员的引用:明显的左值到右值转换
- 使用各种数据类型成员创建对象的简便方法
- 将类类型成员定义为公共和私有之间有什么区别?
- 结构类型成员的默认构造函数中的默认参数
- 如何传递模板模板非类型成员函数指针
- 文本类类型成员函数约束
- 给定仅包含布尔类型成员的结构的两个对象 s1 和 s2,只要 s1 的成员为 true,请检查 s2 的每个成员是否为真
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C++:将模板参数的模板类型成员加为好友的语法正确吗
- C++静态结构类型成员初始化
- C++:作为引用或指针的基类型成员变量
- 左值引用类型成员的用户定义移动构造函数
- 具有指针类型成员的类在 MSVS2012@debug 下销毁时失败.程序错误或错误源
- CRTP -- 访问不完整的类型成员
- 为什么C++默认初始化不对非类类型成员进行零初始化
- 请求非类类型成员