在C++ 11或C++ 1Y/14:給定指針到構件型的形式T C::*
的值我想獲得被指向的型T.C++ 11/14:如何從類型中刪除指向成員的指針?
例如:
#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);
}
有沒有辦法做到這一點?上面的???
是什麼?
更新:
這裏是的libstdc的消毒版本++實現的std::remove_pointer
:
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);
}
您可以專門指針到部件上暴露了一個類型等同於類的類型特徵。 – 0x499602D2