c++ - 为什么 std::stringstream 在静态内联时不能默认构造?

标签 c++ c++17

以下编译良好(在 g++ 8.3.0-6 和 --std=c++17 上),std::stringstream 是一个非静态的类(class)成员:

#include <iostream>
#include <sstream>

class Foo {
    public:
        std::stringstream ss;
};

int main() {
    Foo f;
    f.ss << "bar\n";
    std::cout << f.ss.str();
}

但以下不是(相同的编译器,相同的选项),其中 stringstreamstatic inline:

#include <iostream>
#include <sstream>

class Foo {
    public:
        static inline std::stringstream ss;
};

int main() {
    Foo::ss << "bar\n";
    std::cout << Foo::ss.str();
}

我的编译器告诉我 std::stringstream 没有默认构造函数,而实际上它应该:

error: no matching function for call to ‘std::__cxx11::basic_stringstream<char>::basic_stringstream()’
         static inline std::stringstream ss;
                                         ^~

我在这里做错了什么?

最佳答案

这几乎可以肯定是一个编译器错误。编译器在一种情况下知道构造函数重载但在另一种情况下不知道,这有点奇怪,尽管这可能与构造函数是显式有关。

这确实 compile with 8.3 :

#include <iostream>
#include <sstream>

class Foo {
    public:
        static inline std::stringstream ss{};
};                                      //^^ 

int main() {
    Foo::ss << "bar\n";
    std::cout << Foo::ss.str();
}

PS:这个答案也得出结论,explicit 是原因 https://stackoverflow.com/a/47782995/4117728 .

关于c++ - 为什么 std::stringstream 在静态内联时不能默认构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68831096/

相关文章:

c++ - 从字符串执行 Lua 函数

c++ - gcc - 如何在结构定义中组合 __attribute__((dllexport)) 和 [[nodiscard]]?

c++ - 我应该在使用 std::transform 之前检查 vector 是否为空

c++ - constexpr 字符串与 const 字符串

在派生模板类中使用 typedef 时,C++ 虚拟模板参数引发错误

c++ - ofstream - 需要在 close() 操作后删除对象句柄吗?

c++ - 为什么忽略 std::optional 的强制转换运算符?

c++ - 确保模板参数类型与其可变构造函数的类型匹配

c++ - GCC 和 Clang 不在 C++17 中编译 std::hash<std::nullptr_t>

c++ - 如何通过 CRTP 实现修复破坏强封装规则?