Check at compile-time is a template type a vector

后端 未结 5 1639
死守一世寂寞
死守一世寂寞 2020-12-24 03:17

I can imagine the following code:

template  class X
{
  public:
   T container;

   void foo()
   {
      if(is_vector(T))
         contain         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-24 03:30

    If you use constexpr if, you were doing it right. This C++17 code compiles:

    #include 
    #include 
    #include 
    #include 
    
    template struct is_vector : public std::false_type {};
    
    template
    struct is_vector> : public std::true_type {};
    
    
    template 
    class X
    {
      public:
       T container;
    
       void foo()
       {
          if constexpr(is_vector::value){
            std::cout << "I am manipulating a vector" << std::endl;
            // Can access container.push_back here without compilation error
          }
          else {
             std::cout << "I am manipulating something else" << std::endl;
          }
       }
    };
    
    int main() {
        X> abc;
        abc.foo(); // outputs "I am manipulating a vector"
    
        X> def;
        def.foo(); // outputs "I am manipulating something else"
    }
    

提交回复
热议问题