2014-03-06 73 views
7

在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); 
} 
+1

您可以專門指針到部件上暴露了一個類型等同於類的類型特徵。 – 0x499602D2

回答

5

這其實是一種簡單的鍛鍊模板特殊化:

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

@ 0x499602D2我不清楚OP究竟想要做什麼。無論如何,希望這個答案足以說明他適應自己的目的。 – Brian

+2

你可能會提到'template 使用remove_member_pointer_t = typename remove_member_pointer < t > :: type;否則這只是「僅僅」C++ 03。 – Potatoswatter

+0

@Potatoswatter:'std :: remove_member_pointer'在類型特徵中不存在吧?也許它應該。 –