Todd Burch
Todd Burch

Reputation: 206

Can't import both sstream and iostream in C++20?

Create a new empty C++ Windows console application in Visual Studio 2022.

Add a "main.cppm" file and populate it with this:

import <sstream>;

int main()
{
    std::stringstream ss;
    ss << "Hey world!";
    return 0;
}

It should compile and run fine (though it doesn't do anything useful).

Now comment that out and change the code to this:

//import <sstream>;
import <iostream>;

int main()
{
    std::cout << "Hello world!" << std::endl;
    //std::stringstream ss;
    //ss << "Hey world!";
    return 0;
}

Again, it compiles and runs fine and we see "Hello world!" on the console.

But now uncomment the commented lines:

import <sstream>;
import <iostream>;

int main()
{
    std::cout << "Hello world!" << std::endl;
    std::stringstream ss;
    ss << "Hey world!";
    return 0;
}

This will NOT compile, giving the following errors:

E0070 incomplete type is not allowed

(referring to stringstream)

E0349 no operator "<<" matches these operands

E3365 incomplete class type "std::basic_stringstream<char, std::char_traits<char>, std::allocator<char>>" is not allowed

and the following message:

Local variable is not initialized

(referring to the ss variable)

It compiles fine if I:

  1. #include <sstream> and import <iostream>;, or
  2. #include <iostream> and import <sstream>;, or
  3. #include <iostream> and #include <sstream>;.

But I CANNOT import <iostream>; and import <sstream>; at the same time.

Can anyone explain why, or know how to import both? I suspect this has to do with a dependency between the two, but I'm not sure.

Upvotes: 3

Views: 738

Answers (2)

pascal754
pascal754

Reputation: 189

I tested with MSVC 2022 Version 17.5.4 and 17.6.0 Preview 5.0.

Edit: IDE says that C++ IntelliSense support for C++20 Modules is currently experimental.

The code compiles and runs.

Scan Sources for Module Dependencies needs to be Yes.

You can change this option as follows:

Menu -> Project -> Properties -> Configuration Properties -> C/C++ -> All Options -> Scan Sources for Module Dependencies -> Yes.

Scan Sources for Module Dependencies

Upvotes: 1

vitaut
vitaut

Reputation: 55524

This is clearly a bug in Visual Studio, specifically IntelliSense. Note that module support is still incomplete there so until it is fixed you'll have to use includes. In C++23 you'll also be able to do import std.

Upvotes: 0

Related Questions