gpt4 book ai didi

c++ - 如何从模板类的方法返回 std::string,无论类型如何?

转载 作者:太空狗 更新时间:2023-10-29 20:33:16 26 4
gpt4 key购买 nike

我很难解决我认为应该很容易做的事情。我有一个模板类,看起来像这样(有其他代码,加载值等)。我关心的工作类型是 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) 相同的错误)

最佳答案

几乎在我发布后,答案就跳到了我面前......但这也许对将来的其他人有帮助!

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” block 中。

关于c++ - 如何从模板类的方法返回 std::string,无论类型如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56263726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com