【问题标题】:How to return std::string from method of templated class, no matter the type?无论类型如何,如何从模板类的方法返回 std::string?
【发布时间】: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) 的情况相同的错误发生)

【问题讨论】:

    标签: c++ string templates std


    【解决方案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”块中。

    【讨论】:

    • 有趣的观察。请注意,在 constexpr 之外 - 如果代码必须有效,则与之前的任何 returns 无关。它类似于 void foo() { return; asdf; } 无效,即使您可以争辩说永远无法到达 asdf;
    • @foreknownas_463035818 你的评论不应该(也)在问题之下吗?
    • @AKL 是同一个用户。我为什么要评论两次?
    • @foreknownas_463035818 不,我知道。我之所以这么说是因为我第一次在答案下阅读它时感到困惑,但我发现它更适合这个问题。
    • @AKL 对不起,我不明白。我的评论指的是不是问题的答案
    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2011-01-10
    相关资源
    最近更新 更多