【发布时间】:2017-01-08 15:48:11
【问题描述】:
我试图实现一个将泛型类型转换为字符串的函数。整数类型需要使用 std::to_string() 转换,字符串和字符使用 std::string() 和向量,逐个元素地转换为使用其他方法之一的字符串(取决于它们的内容)。
这就是我所拥有的:
//Arithmetic types
template<class T>
typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type convertToString(const T& t){
return std::to_string(t);
}
//Other types using string ctor
template<class T>
typename std::enable_if<std::__and_<std::__not_<std::is_arithmetic<T>>::type,
std::__not_<std::is_same<T, <T,
std::vector<typename T::value_type, typename T::allocator_type>>::value
>>>::value, std::string>::type convertToString(const T& t){
return std::string(t);
}
//Vectors
template<class T>
typename std::enable_if<std::is_same<T, std::vector<typename T::value_type,
typename T::allocator_type>>::value, std::string>::type convertToString(const T& t){
std::string str;
for(std::size_t i = 0; i < t.size(); i++){
str += convertToString(t[i]);
}
return str;
}
问题是第二个函数没有编译。如何设计第二个函数,使其能够编译(和工作)并且不会产生歧义问题?
【问题讨论】:
标签: c++ templates c++14 sfinae enable-if