我可以使用 enable_if 按参数类型分隔行为,例如:
std::vector<int>
现在我想通过容器的内部类型来区分行为:
int of std::vector<int>
我可以在 C++ 中做什么?
我想知道这是不是你的意思:
#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 using 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>