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

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)的情况相同,发生了错误)

EMo*_*Mon 5

几乎在我发布信息时,答案就跳到了我身上……但这也许将来会对其他人有所帮助!

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”情况。

  • 有趣的观察。请注意,在constexpr之外-如果代码必须有效,则与之前的任何return无关。类似于`void foo(){return; asdf; }`即使您可能认为`asdf;`从未达到过也无效。 (3认同)