【发布时间】:2019-05-22 19:30:56
【问题描述】:
我正忙着解决我认为应该很容易做的事情。我有一个模板类,看起来像这样(有其他代码,加载值等)。我关心的类型是 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};
};
上述选项 (1) 对于任何不是 std::string 的类型名 T 都失败。
选项 (2) 适用于任何类型名 T except for std::string
选项 (3) 似乎没有在编译时得到实际处理(与选项 (1) 的情况相同的错误发生)
【问题讨论】: