您的位置:首页 > 其它

vc 鲜为人知的 __if_exists

2009-04-15 12:48 232 查看
msdn 中有这样一个示例:

// the__if_exists_statement.cpp
    // compile with: /EHsc
    #include <iostream>
    
    template<typename T>
    class X : public T {
    public:
       void Dump() {
          std::cout << "In X<T>::Dump()" << std::endl;
    
          __if_exists(T::Dump) {
             T::Dump();
          }
    
          __if_not_exists(T::Dump) {
             std::cout << "T::Dump does not exist" << std::endl;
          }
       }   
    };
    
    class A {
    public:
       void Dump() {
          std::cout << "In A::Dump()" << std::endl;
       }
    };
    
    class B {};
    
    bool g_bFlag = true;
    
    class C {
    public:
       void f(int);
       void f(double);
    };
    
    int main() { 
       X<A> x1;
       X<B> x2;
    
       x1.Dump();
       x2.Dump();
    
       __if_exists(::g_bFlag) {
          std::cout << "g_bFlag = " << g_bFlag << std::endl;
       }
    
       __if_exists(C::f) {
          std::cout << "C::f exists" << std::endl;
       }
    
       return 0;
    }




但是不能检测某个变量是否有某个成员,象下面这样的代码是不能编译的:



template<class TA>
void foo(TA& a)
{
   __if_exists(a.x)
   {
     printf("a has a.x/n");
   }
   // 上面不能编译无所谓可以转化成
    __if_exists(TA::x)
   {
     printf("a has a.x/n");
   }
   // 但是这个就不是很容易了:
   __if_exists((complex expression).a)
   {
   }
}




或许是因为本质上,可以通过其它方法实现这个功能,也就是依据目前的这种机制,也可以达到目的,但是繁琐一些,需要加一个中间层,例如:

template<class TA>
void foo1(TA& a, true_type)
{
  printf("a has a.x/n");
}
template<class TA>
void foo1(TA& a, false_type)
{
  printf("a has not a.x/n");
}

template<class TA>
void foo(TA& a)
{
   __if_exist(TA::x)
   {
      foo1(a, true_type());
   }
   __if_not_exist(TA::x)
   {
      foo1(a, false_type());
   }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: