問題描述
為了創建算法模板函數,我需要知道作為模板參數的類中是 x 還是 X(以及 y 或 Y).在將我的函數用于 MFC CPoint 類或 GDI+ PointF 類或其他一些類時,它可能很有用.他們都使用不同的 x .我的解決方案可以簡化為以下代碼:
For creating algorithm template function I need to know whether x or X (and y or Y) in class that is template argument. It may by useful when using my function for MFC CPoint class or GDI+ PointF class or some others. All of them use different x in them. My solution could be reduces to the following code:
template<int> struct TT {typedef int type;};
template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; }
struct P1 {int x; };
struct P2 {float X; };
// it also could be struct P3 {unknown_type X; };
int main()
{
P1 p1 = {1};
P2 p2 = {1};
Check_x(p1); // must return true
Check_x(p2); // must return false
return 0;
}
但它不能在 Visual Studio 中編譯,而在 GNU C++ 中編譯.使用 Visual Studio,我可以使用以下模板:
But it does not compile in Visual Studio, while compiling in the GNU C++. With Visual Studio I could use the following template:
template<class P> bool Check_x(P p, typename TT<&P::x==&P::x>::type b = 0) { return true; }
template<class P> bool Check_x(P p, typename TT<&P::X==&P::X>::type b = 0) { return false; }
但它不能在 GNU C++ 中編譯.有通用的解決方案嗎?
But it does not compile in GNU C++. Is there universal solution?
UPD:此處的結構 P1 和 P2 僅用作示例.可能有任何具有未知成員的類.
UPD: Structures P1 and P2 here are only for example. There are could be any classes with unknown members.
附言請不要在此處發布 C++11 解決方案,因為它們很明顯且與問題無關.
P.S. Please, do not post C++11 solutions here because they are obvious and not relevant to the question.
推薦答案
另一種方式是這個,它依賴于 SFINAE 表達式.如果名稱查找導致歧義,編譯器將拒絕模板
Another way is this one, which relies on SFINAE for expressions too. If the name lookup results in ambiguity, the compiler will reject the template
template<typename T> struct HasX {
struct Fallback { int x; }; // introduce member name "x"
struct Derived : T, Fallback { };
template<typename C, C> struct ChT;
template<typename C> static char (&f(ChT<int Fallback::*, &C::x>*))[1];
template<typename C> static char (&f(...))[2];
static bool const value = sizeof(f<Derived>(0)) == 2;
};
struct A { int x; };
struct B { int X; };
int main() {
std::cout << HasX<A>::value << std::endl; // 1
std::cout << HasX<B>::value << std::endl; // 0
}
它基于 usenet 上某人的絕妙想法.
It's based on a brilliant idea of someone on usenet.
注意:HasX 檢查任何名為 x 的數據或函數成員,具有任意類型.引入成員名稱的唯一目的是使成員名稱查找可能存在歧義——成員的類型并不重要.
Note: HasX checks for any data or function member called x, with arbitrary type. The sole purpose of introducing the member name is to have a possible ambiguity for member-name lookup - the type of the member isn't important.
這篇關于如何檢測類中是否存在特定的成員變量?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!