【问题标题】:std::string type lost in tuplestd::string 类型在元组中丢失
【发布时间】:2016-07-13 10:39:29
【问题描述】:

有人能解释一下这里发生了什么吗? GCC 5.2 的输出:

#include <iostream>
#include <tuple>
#include <string>
#include <typeinfo>

template <typename... Args>
void foo (Args&&... args) {
    std::tuple<Args...> t = std::tie(args...);
    std::cout << std::is_same<int, std::tuple_element_t<0, decltype(t)>>::value << '\n';  // true
    std::cout << std::is_same<std::string, std::tuple_element_t<1, decltype(t)>>::value << '\n';  // false
    std::cout << typeid(std::tuple_element_t<1, decltype(t)>).name() << '\n';  // A3_C (what's this???)
}

int main() {
    foo (5, "hi");
}

为什么 std::string 类型丢失了,它变成了什么?

【问题讨论】:

    标签: string templates c++11 tuples


    【解决方案1】:

    "string" - 是 const char[N] 数组,不是 std::string。在这种情况下,const char[] = {'h', 'i', '\0'} -&gt; const char[3] -&gt; Array3char (A3_C) 类型的元素组成。 使用std::string("hi") 制作字符串或启用用户文字并写入"hi"s

    【讨论】:

      【解决方案2】:

      "hi"(字符串字面量)的类型是 const char[3],而不是 std::string

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        • 1970-01-01
        • 1970-01-01
        • 2020-02-05
        • 1970-01-01
        相关资源
        最近更新 更多