Я могу использовать enable_if для разделения поведения по типу параметра, например:
std::vector<int>
Теперь я хочу разделить поведение по внутреннему типу контейнера:
int of std::vector<int>
что я могу сделать в с ++?
Интересно, это то, что вы имеете в виду:
#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>&)’
Что-то вроде следующего, где вы можете заполнить int
, double
и т. д. для S
?
std::vector<std::enable_if<std::is_same<T, S>::value, S>::type>