Search code examples
c++c++11typesdecltypeenable-if

how to decide by 'int' type of 'vector<int>' in C++?


I can use enable_if to separate behavior by parameter type such as:

std::vector<int>

Now I want to separate behavior by the inner type of a container:

int of std::vector<int>

what can I do in c++?


Solution

  • I wonder if this is what you mean:

    #include<iostream>
    #include<vector>
    #include<type_traits>
    
    // The following function will display the contents of the provided T
    // only if its value_type trait is of type int.
    template<typename T>
    typename std::enable_if<
      std::is_same<typename T::value_type, int>::value,
      void>::type display(const T& data) {
      std::cout<<"Some ints:"<<std::endl;
      for(int xi : data) {
        std::cout<<xi<<" ";
      }
      std::cout<<std::endl;
    }
    
    int main() {
      std::vector<int> dint = {1, 2, 3, 4, 5, 6};
      display(dint);
    
      std::vector<float> dfloat = {1, 2, 3, 4, 5, 6};
    
      // The following call would lead to compile-time error, because
      // there is no display function activated for float types:
    
      //display(dfloat);
      return 0;
    }
    

    Compiling with g++ example.cpp -std=c++11 -Wall -Wextra (OS X 10.7.4 using GCC 4.8.1) yields:

    $ ./a.out 
    Some ints:
    1 2 3 4 5 6 
    

    As expected, if I uncomment the display(dfloat) line the compiler error message includes:

    error: no matching function for call to ‘display(std::vector<float>&)’