EMo*_*Mon 3 c++ string templates std
我很难解决我认为应该做的一件简单的事情。我有一个模板化的类,看起来像这样(有其他代码,以加载值,等等)。我关心的类型是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};
};
Run Code Online (Sandbox Code Playgroud)
对于不是std :: string的任何类型名称T,上面的选项(1)都会失败。
选项(2)适用于除 std :: string 之外的任何类型名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];
}
Run Code Online (Sandbox Code Playgroud)
除非它专门位于“ else”块内,否则编译器不够聪明,无法忽略“ else”情况。