[英]How to return std::string from method of templated class, no matter the type?
我有一段时间解决我认为应该是一件容易的事。 我有一个模板化的类,看起来像这样(有其他代码,加载值等)。 我关心的类型是char,int,bool和std :: string。
template <typename T>
class MyVector
{
public:
std::string get()
{
return m_vector[m_current_index]; // 1
return std::to_string(m_vector[m_current_index]); // 2
// 3
if constexpr (!std::is_same_v<T, std::string>) {
return std::to_string(m_vector[m_current_index]);
}
return m_vector[m_current_index];
}
private:
std::vector<T> m_vector;
int m_current_index{-1};
};
对于任何不是std :: string的typename T,上面的选项(1)都会失败。
选项(2)适用于除 std :: string 之外的任何typename T.
选项(3)似乎没有在编译时实际处理(与选项(1)的情况相同的错误发生)
几乎在我发布的时候,答案就跳出来了......但也许这对未来的其他人有帮助!
if constexpr (!std::is_same_v<T, std::string>) {
return std::to_string(m_vector[m_current_index]);
} else {
return m_vector[m_current_index];
}
编译器不够聪明,不能忽略'else'情况,除非它特别在'else'块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.