2013-02-19 48 views

回答

1

可以幾乎做到這一點(或至少我無法找到一個更好的解決方案至今):

#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"); 
} 
+0

非常地我削減了我的例子太多。我實際上正在尋找的方法是將'some_class '減少到'some_class <&X::x>' – Eric 2013-02-19 17:40:12

+1

@Eric:那麼恐怕你將無法做到這一點。文字沒有相應的「typename」。與「typename」接受任何類類型相同的方式,您需要一個接受任何文字的「文字」,然後您將專門處理這些文字。但不幸的是沒有這樣的事情存在。 – 2013-02-19 17:48:55

+1

@Eric:正如Andy所說,沒有人找到辦法做到這一點。你可以做的最好的辦法是'some_class '並且把它隱藏在宏的後面。 :/另見[這個問題](http://stackoverflow.com/q/5628121/500104)。 – Xeo 2013-02-19 17:59:03

相關問題