c ++ 11 — как определить тип int для вектора & lt; int & gt; в С ++?

Я могу использовать enable_if для разделения поведения по типу параметра, например:

std::vector<int>

Теперь я хочу разделить поведение по внутреннему типу контейнера:

int of std::vector<int>

что я могу сделать в с ++?

0

Решение

Интересно, это то, что вы имеете в виду:

#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;
}

Компилирование с g++ example.cpp -std=c++11 -Wall -Wextra (OS X 10.7.4 с использованием GCC 4.8.1) приводит к:

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

Как и ожидалось, если я раскомментирую display(dfloat) строка сообщения об ошибке компилятора включает в себя:

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

Другие решения

Что-то вроде следующего, где вы можете заполнить int, doubleи т. д. для S?

std::vector<std::enable_if<std::is_same<T, S>::value, S>::type>
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector