相关疑难解决方法(0)

如何检测类中是否有特定的成员变量?

为了创建算法模板函数,我需要知道类中的x或X(和y或Y)是模板参数.当我的函数用于MFC CPoint类或GDI + PointF类或其他类时,它可能很有用.他们都使用不同的x.我的解决方案可以简化为以下代码:


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 …
Run Code Online (Sandbox Code Playgroud)

c++ templates g++ sfinae visual-studio

62
推荐指数
5
解决办法
3万
查看次数

标签 统计

c++ ×1

g++ ×1

sfinae ×1

templates ×1

visual-studio ×1