我们如何打印出C++ STL容器的value_type?

Nia*_*ais 14 c++ stl

我知道STL容器有一个value_type参数,我已经看到它如何用于声明一个变量类型,如:

vector<int>::value_type foo;
Run Code Online (Sandbox Code Playgroud)

但是我们可以将它打印value_type到控制台吗?

我想在这个例子中看到"string":

int main() {
    vector<string> v = {"apple", "facebook", "microsoft", "google"};
    cout << v << endl;
    cout << v.value_type << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 15

X::value_type在这方面与任何其他类型别名(aka typedef)没什么不同 - C++没有将类型转换为其源代码字符串表示的本地方式(至少因为它可能是不明确的).你可以做的是使用std::type_info::name:

cout << typeid(decltype(v)::value_type).name() << endl;
Run Code Online (Sandbox Code Playgroud)

生成的文本依赖于编译器(甚至不能保证人类可读).它将在程序的同一构建中保持一致,但您不能指望它在不同的编译器中是相同的.换句话说,它对调试很有用,但不能以持久的方式可靠地使用.


lub*_*bgr 5

除了typeid基于答案的答案之外,我还看到了使用Boost的另一种可能性:

#include <boost/type_index.hpp>

cout << boost::typeindex::type_id_with_cvr<decltype(v)::value_type>().pretty_name() << "\n";
Run Code Online (Sandbox Code Playgroud)

优点是一个可移植的,人类可读的名称,包括const/volatile资格,并且在主要编译器和系统中是一致的.我机器上的输出是

// when compiled with gcc:
std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >
// ... and with clang:
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >
Run Code Online (Sandbox Code Playgroud)

自己决定这个输出是否符合"人类可读"的要求,还要将它与typeid(...).name()我的机器上提供的方法进行比较:

NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE
Run Code Online (Sandbox Code Playgroud)