check if member exists using enable_if

前端 未结 6 1304
鱼传尺愫
鱼传尺愫 2020-11-28 13:40

Here\'s what I\'m trying to do:

template  struct Model
{
    vector vertices ;

    #if T has a .normal member
    void transform(         


        
6条回答
  •  忘掉有多难
    2020-11-28 13:45

    This isn't an answer to your exact case, but it is an alternative answer to the question title and problem in general.

    #include 
    #include 
    
    struct Foo {
        size_t length() { return 5; }
    };
    
    struct Bar {
        void length();
    };
    
    template length()), size_t>::value>
    constexpr bool hasLengthHelper(int) { 
        return result;
    }
    
    template 
    constexpr bool hasLengthHelper(...) { return false; }
    
    template 
    constexpr bool hasLength() {
        return hasLengthHelper(0);
    }
    
    // function is only valid if `.length()` is present, with return type `size_t`
    template 
    typename std::enable_if(), size_t>::type lengthOf (R r) {
      return r.length();
    }
    
    int main() {
        std::cout << 
          hasLength() << "; " <<
          hasLength>() << "; " <<
          hasLength() << ";" <<
          lengthOf(Foo()) <<
          std::endl;
        // 1; 0; 0; 5
    
        return 0;
    }
    

    Relevant https://ideone.com/utZqjk.

    Credits to dyreshark on the freenode IRC #c++.

提交回复
热议问题