简体   繁体   中英

Why does std::boolalpha ignore field width when using clang?

The following code gives different results with the g++ 7 compiler and Apple clang++. Did I run into a bug in clang in the alignment of bool output when std::boolalpha is used, or did I make a mistake?

#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>

template<typename T>
void print_item(std::string name, T& item) {
    std::ostringstream ss;
    ss << std::left << std::setw(30) << name << "= " 
       << std::right << std::setw(11) << std::setprecision(5) 
       << std::boolalpha << item << " (blabla)" << std::endl;

    std::cout << ss.str();
}

int main() {
    int i = 34;
    std::string s = "Hello!";
    double d = 2.;
    bool b = true;

    print_item("i", i);
    print_item("s", s);
    print_item("d", d);
    print_item("b", b);

    return 0;
}

The difference is:

// output from g++ version 7.2
i                             =          34 (blabla)
s                             =      Hello! (blabla)
d                             =           2 (blabla)
b                             =        true (blabla)
// output from Apple clang++ 8.0.0
i                             =          34 (blabla)
s                             =      Hello! (blabla)
d                             =           2 (blabla)
b                             = true   (blabla)

At TC mentioned, this is LWG 2703 :

No provision for fill-padding when boolalpha is set

N4582 subclause 25.4.2.2.2 [facet.num.put.virtuals] paragraph 6 makes no provision for fill-padding in its specification of the behaviour when (str.flags() & ios_base::boolalpha) != 0 .

As a result I do not see a solution to this with Clang. However, notice that:

  • libc++ implements this exactly.
  • libstdc++ and MSVC apply padding and alignment.

PS: LWG stands for Library Working Group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM