gpt4 book ai didi

C++11/14 : How to remove a pointer-to-member from a type?

转载 作者:可可西里 更新时间:2023-11-01 16:37:35 37 4
gpt4 key购买 nike

在 C++11 或 C++1y/14 中:给定一个 T C::* 形式的指向成员类型的值,我想得到指向类型

例如:

#include <iostream>
using namespace std;

struct T1 { static void f() { cout << "T1" << endl; } };
struct T2 { static void f() { cout << "T2" << endl; } };

struct U1 { T1 x; };
struct U2 { T2 x; };

template<class C> struct V;
template<> struct V<U1> { static constexpr T1 U1::* pm = &U1::x; };
template<> struct V<U2> { static constexpr T2 U2::* pm = &U2::x; };

template<class W>
void f(W pm)
{
typedef ??? T;
T::f();
}

int main()
{
f(V<U1>::pm);
f(V<U2>::pm);
}

有没有办法做到这一点?上面的 ??? 是什么?

更新:

这是 std::remove_pointer 的 libstdc++ 实现的净化版本:

template<typename T, typename>
struct remove_pointer_helper
{
typedef T type;
};

template<typename T, typename U>
struct remove_pointer_helper<T, U*>
{
typedef U type;
};

template<typename T>
struct remove_pointer
: public remove_pointer_helper<T, typename remove_cv<T>::type>
{};

更新 2:

这是最终的解决方案,谢谢:

#include <iostream>
using namespace std;

template<typename T, typename>
struct remove_member_pointer_helper
{
typedef T type;
};

template<typename T, typename U, typename C>
struct remove_member_pointer_helper<T, U C::*>
{
typedef U type;
};

template<typename T>
struct remove_member_pointer
: public remove_member_pointer_helper<T, typename remove_cv<T>::type>
{};

template<typename T>
using remove_member_pointer_t = typename remove_member_pointer<T>::type;

struct T1 { static void f() { cout << "T1" << endl; } };
struct T2 { static void f() { cout << "T2" << endl; } };

struct U1 { T1 x; };
struct U2 { T2 x; };

template<class C>
struct V;

template<> struct V<U1> { static constexpr T1 U1::* pm = &U1::x; };
template<> struct V<U2> { static constexpr T2 U2::* pm = &U2::x; };

template<class W>
void f(W pm)
{
remove_member_pointer_t<W>::f();
}

int main()
{
f(V<U1>::pm);
f(V<U2>::pm);
}

最佳答案

这实际上是模板特化的一个简单练习:

template<class T> struct remove_member_pointer {
typedef T type;
};
template<class C, class T> struct remove_member_pointer<T C::*> {
typedef T type;
};

关于C++11/14 : How to remove a pointer-to-member from a type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22213523/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com