Misinterpretation of operator precedence when using ostream and ostringstream - c++

The following code has different compile results. From the error message I'm receiving it seems there's a confusion about operators precedence () and <<. I can easily overcome this issue by using a function. However I would like to understand and to know:
a) Which compiler it's evaluating correctly the expression? MSVC2017 seems more logical to me.
b) Is there an workaround still using MACROs?
Full sample code I used.
#include <cstdlib>
#include <typeinfo>
#include <sstream>
#include <iostream>
#ifndef NDEBUG
#define EXPR_INSPECT(param_)\
( (std::ostringstream{} << "< " #param_ " [" << typeid(param_).name() << "] > : " << param_).str() )
#else
#define EXPR_INSPECT(param_)\
(param_)
#endif //NDEBUG
int main(int argc, char *argv[])
{
auto ull_x {99LLU};
std::string string_x {"Checking..."};
std::cout << EXPR_INSPECT( ull_x) << std::endl;
std::cout << EXPR_INSPECT(string_x) << std::endl;
return EXIT_SUCCESS;
}
MSVC2017 works perfectly!
G++ 8.2.0 (MSYS2/MINGW) issues the following error: 'std::basic_ostream::__ostream_type' {aka 'class std::basic_ostream'} has no member named 'str' Attempts to call str() on ostream instead of ostringstream.
EDIT:
The problem here can also be reproduced by clang using Wandbox. Here is a minimal example:
#include <sstream>
#include <iostream>
int main()
{
auto s = std::ostringstream{};
decltype(((std::ostringstream{}) << "< "))::nothing;
decltype((s << "< "))::nothing;
}
In wandbox, clang found the second type std::basic_ostream, while the first type std::basic_ostringstream. That's very strange.

Related

std::filesystem example not compiling on c++ 17

I cant compile this official cpp filesystem reference example using c++ 17 clang:
https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::current_path(fs::temp_directory_path());
fs::create_directories("sandbox/a/b");
std::ofstream("sandbox/file1.txt");
fs::create_symlink("a", "sandbox/syma");
// Iterate over the `std::filesystem::directory_entry` elements explicitly
for (const fs::directory_entry& dir_entry :
fs::recursive_directory_iterator("sandbox"))
{
std::cout << dir_entry << '\n';
}
std::cout << "-----------------------------\n";
// Iterate over the `std::filesystem::directory_entry` elements using `auto`
for (auto const& dir_entry : fs::recursive_directory_iterator("sandbox"))
{
std::cout << dir_entry << '\n';
}
fs::remove_all("sandbox");
}
The compiler is returning:
/main.cpp:17:19: error: invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream') and
'const fs::directory_entry')
std::cout << dir_entry << std::endl;
Can anyone help?
There was a defect in C++17 standard that didn't allow operator<< to be called with std::filesystem::directory_entry, reported in LWG 3171. It's now fixed as defect report, but it seems clang only fixed it in version 14: https://godbolt.org/z/3arTcGYvY. gcc seems to have backported the fix to all versions that support std::filesystem (that is, gcc9.1 and up): https://godbolt.org/z/fh7cdMxso

Eclipse c++11 // vector

This is really driving me crazy:
#include <iostream>
#include <vector>
#include <string.h>
#include <thread>
using namespace std;
void test() {
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
}
int main() {
thread(test).join();
return 0;
}
The code compiles fine with the -std=c++11 flag to the compiler and the -pthread flag to the linker.
BUT: Eclipse does either know the std::thread or the myvector.begin()->length(), even if the code runs fine eclipse warns me "Method 'length' could not be resolved".
I tried every possible solution in here: Eclipse CDT C++11/C++0x support without any success. This took me so many hours now, what am I doing wrong?!
Is there anybody getting a project setup without problems with this code?
EDIT: Other code example - same problem:
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
class TestClass {
public:
void test() {
cout << "test" << endl;
}
};
void test() {
vector<TestClass> testClassVector;
TestClass x;
testClassVector.push_back(x);
testClassVector.begin()->test();
}
int main() {
thread(test).join();
return 0;
}
Compiles and runs correct, but returns in eclipse: Method 'test' could not be resolved
EDIT:
working versions:
((TestClass)*(testClassVector.begin())).test();
TestClass foo2 = *(testClassVector.begin());
foo2.test();
still not working:
testClassVector.begin()->test();
The last compiles and works like the two above, but eclipse still claims:
Method 'test' could not be resolved
Maybe I'm wrong, but I think your problem don't come from Eclypse. Juste, begin() on a vector return a std::vector<T>::iterator first, this is not a pointer and there is no method length, but you can ask for the vector size with myvector.size(); if this is what you want.
The problem could come from your #include <string.h> that is not the same as #include <string>, string.h is for string operation like strcmp, strstr, etc... juste string will define the std::string object.
I don't have Eclipse set up but the problem appears to be around std::string. Does the problem go away if you remove the threading from the example? (I also changed to #include <string> instead of string.h)
#include <iostream>
#include <vector>
#include <string>
#include <thread>
using namespace std;
#if 0
void test() {
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
}
#endif
int main() {
//thread(test).join();
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
return 0;
}
That should hopefully print out 10.
Update from comment:
Does this generate the Eclipse warning?
auto tmp = *(myvector.begin());
std::cout << tmp.length() << std::endl;
What about this?
std::string foo("abc123");
std::cout << foo.length() << std::endl;
I guess one more too:
std::string foo2 = *(myvector.begin());
std::cout << foo2.length() << std::endl;
The solution found:
I downloaded eclipse kepler Kepler
Created a new project and tried to compile this source code (like above):
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
class TestClass {
public:
void test() {
cout << "test" << endl;
}
};
void test() {
vector<TestClass> testClassVector;
TestClass x;
testClassVector.push_back(x);
testClassVector.begin()->test();
}
int main() {
thread(test).join();
return 0;
}
On the first run eclipse told me, thread belongs to the new c++11 standard and I have to add -std=c++11 to the compiler flags. To use thread I also added -pthread to the linker flags. With this steps the code could be compiled, but eclipse marks the thread still as unknown. To fix this I proceeded the following step:
Under C/C++ Build (at project settings), find the Preprocessor Include Path and go to the Providers Tab. Deselect all except CDT GCC Builtin Compiler Settings. Then untag Share settings entries … . Add the option -std=c++11 to the text box called Command to get compiler specs.
Found here.
Now - unbelievable but true - it works, even without any errors marked by eclipse. The solution is using the (beta) version of eclipse, wich seems to handle this in a better way.
Thanks for all your help!

Why is strcmp unknown to clang?

I have a basic program that compares two strings :
#include <string>
#include <iostream>
using namespace std;
int main (int argc, char *argv[]) {
if(strcmp (argv[0],"./test") != 0) {
cout << "not equal" << endl;
} else {
cout << "equal" << endl;
}
return 0;
}
it compiles with gcc but not with clang :
> clang -o test test_clang.cpp
test_clang.cpp:7:6: error: use of undeclared identifier 'strcmp'
if(strcmp (argv[0],"./test") != 0) {
^
1 error generated.
Why doesn't it compile with clang ?
EDIT: People are getting harsh on stack overflow, up to the point that I am hesitating to post a question. The question above has a simple answer, fine, but is it normal to down-vote questions (twice in the first minute!) because they have a simple, yet non obvious, answer ?
Use
#include <string.h>
or
#include <cstring>
instead of
#include <string>
The string header is for the std::string from C++. string.h is for C zero terminated char* strings. cstring is like string.h but for C++.
The reason it worked with gcc is probably different warning/error level settings. It is possible to compile the code without #including the header and having the declaration of strcmp. The compiler will not be able to do type checking but the symbol still gets resolved by the linker.
You can also avoid using strcmp completely and write
#include <string>
#include <iostream>
int main (int argc, char *argv[]) {
std::string command = argv[0];
if( command != "./test" ) {
std::cout << "not equal" << endl;
} else {
std::cout << "equal" << endl;
}
return 0;
}
Using a std::string on one side of the comparison will cause the "./test" string to be converted into a std::string as well and the comparison will be done by the == operator of the std::string class.
You're not including the correct header file
#include <cstring>
You need to #include <cstring> (or possibly #include <string.h>.)
Many compilers include extra standard headers when you include another. The Standard allows this; it's your responsibility to use the headers that guarantee declarations for what you use, not just headers that happen to have the declarations for your compiler.
You have to include <cstring>. <string> is the header for C++ strings.

Does boost::variant work with std::string?

I've written a simple program in C++ with use of boost::variant. Program's code is presented below.
#include <string>
#include <iostream>
#include <boost/variant.hpp>
int main (int argc, char** argv)
{
boost::variant<int, std::wstring> v;
v = 3;
std::cout << v << std::endl;
return 0;
}
But when I try to compile this with command
g++ main.cpp -o main -lboost_system
i get
/usr/include/boost/variant/detail/variant_io.hpp:64: error: no match for ‘operator<<’ in ‘((const boost::detail::variant::printer<std::basic_ostream<char, std::char_traits<char> > >*)this)->boost::detail::variant::printer<std::basic_ostream<char, std::char_traits<char> > >::out_ << operand’
followed by a bunch of candidate functions.
What I'm missing? The funny thing is When I use std::string instead of std::wstring everything works great.
Thanks in advance.
The problem is that wstring cannot be << in cout. Try using wcout instead. This is not a problem with the variant.
Use wcout, not cout. Because you're using wstring, not string.
std::wcout << v << std::endl;
//^^^^ note
Demo : http://ideone.com/ynf15

typeinfo / typeid output

I'm currently trying to debug a piece of simple code and wish to see how a specific variable type changes during the program.
I'm using the typeinfo header file so I can utilise typeid.name(). I'm aware that typeid.name() is compiler specific thus the output might not be particularly helpful or standard.
I'm using GCC but I cannot find a list of the potential output despite searching, assuming a list of typeid output symbols exist. I don't want to do any sort of casting based on the output or manipulate any kind of data, just follow its type.
#include <iostream>
#include <typeinfo>
int main()
{
int a = 10;
cout << typeid(int).name() << endl;
}
Is there a symbol list anywhere?
I don't know if such a list exists, but you can make a small program to print them out:
#include <iostream>
#include <typeinfo>
#define PRINT_NAME(x) std::cout << #x << " - " << typeid(x).name() << '\n'
int main()
{
PRINT_NAME(char);
PRINT_NAME(signed char);
PRINT_NAME(unsigned char);
PRINT_NAME(short);
PRINT_NAME(unsigned short);
PRINT_NAME(int);
PRINT_NAME(unsigned int);
PRINT_NAME(long);
PRINT_NAME(unsigned long);
PRINT_NAME(float);
PRINT_NAME(double);
PRINT_NAME(long double);
PRINT_NAME(char*);
PRINT_NAME(const char*);
//...
}