question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,118,484
73,118,668
CMake Compiler not set
CMake Error: CMAKE_Project_COMPILER not set, after EnableLanguage I Get this Error after writing cmake .. This is my CMakeLists.txt set(CMAKE_CXX_COMPILER "C:/mingw64/bin/g++") set(CMAKE_C_COMPILER "C:/mingw64/bin/gcc") project(CXX Project) add_subdirectory(glfw/) add_executable(${PROJECT_NAME} Main.cpp) target_include_directories(${PROJECT_NAME} PUBLIC glfw) target_link_libraries(${PROJECT_NAME} PUBLIC glfw)``` And this is my Complete Error PS C:\Users\david\Documents\Idle\Project\build> cmake .. CMake Error at CMakeLists.txt:6 (project): Running 'nmake' '-?' failed with: Das System kann die angegebene Datei nicht finden CMake Error: CMAKE_Project_COMPILER not set, after EnableLanguage -- Configuring incomplete, errors occurred! See also "C:/Users/david/Documents/Idle/Project/build/CMakeFiles/CMakeOutput.log".
You're using the project command in the wrong way. It should be project(Project CXX) That's why CMake is looking for CMAKE_Project_COMPILER instead of CMAKE_CXX_COMPILER.
73,118,892
73,118,972
How to set a specific size to the QPixmap and keep content in the same position and the same size?
I only want to resize the QPixmap, not the content.
QPixmap newPixmap(newWidth, newHeight); newPixmap.fill(Qt::black); // or the color you like... maybe you want Qt::transparent? QPainter painter(&newPixmap); painter.drawPixmap(0, 0, oldPixmap);
73,119,206
73,123,827
Proof that user compressed public key corresponds the curve equation (secp256k1)
I am trying to check if some compressed public key corresponds to an elliptic curve equation (secp256k1). As far as I know it should be valid once the following equation is fulfill y^2 = x^3 + ax + b or y^2 % p = (x^3 +ax +b) % p. Supposing that I have the following key: pubkey = 027d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c60d074d7d60ef I am able to extract x-coordinate (do to it in this case I strip 02), in theory to calculate y without sqrt operation (due to losing precision) we can do in this case: y = (x^exp) % p, where exp = (p+1)/4 based on https://crypto.stackexchange.com/questions/101142/proof-that-user-compressed-public-key-corresponds-the-curve-equation-secp256k1 Now based on how I calculate y: bmp::uint1024_t const y = bmp::powm(x, pp, p); //or bmp::uint1024_t const yy = (x^pp) % p; I have other results, which impact later computations, generally the second example gives correct final result, but it seems, that for some reasons it doesn't work as it should... for power operation it gives the following result: bmp::pow(x, pp): 5668936922878426254536308284732873549115769122415677675761389126416312181579**1** x^pp: 5668936922878426254536308284732873549115769122415677675761389126416312181579**0** Even in python3 code for x^pp I have the same result as the second one, so should I use something other than boost::multiprecision ? or do these computation in other way ? Code can be test here: https://wandbox.org/permlink/JQ3ipCq6yQjptUet #include <numeric> #include <iostream> #include <string> #include <boost/multiprecision/cpp_int.hpp> namespace bmp = boost::multiprecision; bool verify(std::string const& address, std::size_t const stripped_prefix_size) { auto is_address_correct{false}; bmp::uint1024_t const p = bmp::uint1024_t{"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"} % 4;//3 % 4;//{"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"}; bmp::uint1024_t const a{"0x0000000000000000000000000000000000000000000000000000000000000000"}; bmp::uint1024_t const b{"0x0000000000000000000000000000000000000000000000000000000000000007"}; bmp::uint1024_t x{std::string{"0x"} + address.substr(2, address.size() - stripped_prefix_size)}; auto const right = (bmp::pow(x, 3) + (a * x) + b) % p; //bmp::uint1024_t const y = bmp::sqrt(right) % p; bmp::uint1024_t pp = (p + 1) / 4; bmp::uint1024_t const y = bmp::powm(x, pp, p); bmp::uint1024_t const yy = (x^pp) % p;//bmp::powm(x, pp, p); auto const left = bmp::powm(y, 2, p); auto const left2 = bmp::powm(yy, 2, p); std::cout << "x: " << x << std::endl; std::cout << "y pow pp: " << bmp::pow(x, pp.convert_to<int>()) << std::endl; std::cout << " y^pp: " << bmp::uint1024_t{x^pp} << std::endl; std::cout << "yy mod p: " << yy << std::endl; std::cout << " y mod p: " << y << std::endl; std::cout << "yy: " << yy << std::endl; std::cout << "right: " << right << std::endl; std::cout << " left: " << left << std::endl; std::cout << "left2: " << left2 << std::endl; is_address_correct = (left == right); return is_address_correct; } int main() { auto const res = verify("027d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c60d074d7d60ef", 2); std::cout << "\nis valid: " << res << std::endl; return 0; } Output: x: 56689369228784262545363082847328735491157691224156776757613891264163121815791 y pow pp: 56689369228784262545363082847328735491157691224156776757613891264163121815791 y^pp: 56689369228784262545363082847328735491157691224156776757613891264163121815790 yy mod p: 2 y mod p: 0 yy: 2 right: 1 left: 0 left2: 1 is valid: 0
For the compressed key 027d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c60d074d7d60ef the uncompressed representation is 047d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c60d074d7d60effbb6217403fe57ff1b2f84f74086b413c7682027bd6ddde4538c340ba1a25638 i.e. x = 0x7d550bc2384fd76a47b8b0871165395e4e4d5ab9cb4ee286d1c60d074d7d60ef = 56689369228784262545363082847328735491157691224156776757613891264163121815791 y = 0xfbb6217403fe57ff1b2f84f74086b413c7682027bd6ddde4538c340ba1a25638 = 113852322045593354727100676608445520152048120867463853258291211042951302108728 This is also confirmed by the following code using the Boost library: bool verify(std::string const& address, std::size_t const stripped_prefix_size) { auto is_address_correct{false}; bmp::uint1024_t const p = bmp::uint1024_t{"0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"}; bmp::uint1024_t const a{"0x0000000000000000000000000000000000000000000000000000000000000000"}; bmp::uint1024_t const b{"0x0000000000000000000000000000000000000000000000000000000000000007"}; bmp::uint1024_t x{std::string{"0x"} + address.substr(2, address.size() - stripped_prefix_size)}; bmp::uint1024_t right = (bmp::powm(x, 3, p) + (a * x) + b) % p; bmp::uint1024_t y = bmp::powm(right, (p + 1) / 4, p); // even, i.e. equals the searched y value because of leading 0x02 byte bmp::uint1024_t left = bmp::powm(y, 2, p); std::cout << "x: " << x << std::endl; // x: 56689369228784262545363082847328735491157691224156776757613891264163121815791 std::cout << "y: " << y << std::endl; // y: 113852322045593354727100676608445520152048120867463853258291211042951302108728 std::cout << "right: " << right << std::endl; // right: 33769945388650438579771708095049232540048570303667364755388658443270938208149 std::cout << "left: " << left << std::endl; // left: 33769945388650438579771708095049232540048570303667364755388658443270938208149 is_address_correct = (left == right); return is_address_correct; } The code contains the following fixes/considerations: When calculating y, not x but right must be applied. The solution has two values -y and +y, s. here. Because of the leading 0x02 byte, that value must be used which has an even parity in the positive, and this is true here for +y. The value for p must not be taken modulo 4 (see comment by President James K. Polk). The congruence of the modulus to 3 modulo 4 is only relevant for finding the correct solution path. A more detailed explanation can be found here.
73,119,624
73,120,236
Want to create a variable of datatype "Struct", and control (Array Size) of its sub element from outside
I want to feed SIZE externally while declaring a variable of datatype "Struct" . Basically I want to use this datatype with different size. struct ArrStruct final { std::array<float32_t, SIZE> Arr1; std::array<float32_t, SIZE> Arr2; }; struct Type1 final { ArrStruct var4; float32_t var5; }; struct StructData final { Type1 var1; float32_t var2; float32_t var3; }; struct Struct final { StructData Data; };
You can make SIZE a template argument: template <size_t SIZE> struct ArrStruct final { std::array<float32_t, SIZE> Arr1; std::array<float32_t, SIZE> Arr2; }; template <size_t SIZE> struct Type1 final { ArrStruct<SIZE> var4; float32_t var5; }; template <size_t SIZE> struct StructData final { Type1<SIZE> var1; float32_t var2; float32_t var3; }; template <size_t SIZE> struct Struct final { StructData<SIZE> Data; }; Struct<42> is then a Struct with a StructData<42> which in turn has a member of type Type1<42> and that has a member of type ArrStruct<42> which contains arrays of size 42.
73,119,625
73,135,342
How to signal a class that some HTTPServer request was received?
I want to extend an existing application with a simple REST server and a dedicated UDP client for streaming data to a UDP server. The REST server should manage the UDP client based on the API requests and have access to classes in the hosting application. I want to create a new class in the hosting application so I can have access to the data. I saw Poco::Net::HTTPServer and it seems a good candidate. I want to start and stop HTTPServer from that class methods. Thing is, this class should know of the API requests types so that it can react accordingly. Is it a good practice to inherit HTTPServer and extend it with the above behavior (that way I may have simple access to the requests)? Or should it only be a member of the main class? I also thought of POCO events/notifications but not sure if it is a good idea or how to subscribe my new class to events from different short-living objects (of class HTTPRequestHandler), or to events from the HTTPRequestHandlerFactory object (which HTTPServer owns upon creation). P.S. The new REST server and UDP socket should serv a single connection. Also, the expected frequency of API requests is very low. Any help or alternative ideas are highly appreciated!
Is it a good practice to inherit HTTPServer and extend it with the above behavior (that way I may have simple access to the requests)? I don't recommend that. Create a standalone class, hold a reference to it in the request handler factory, pass the reference to each request handler, and do the required work at the request handling time. As for using notifications, from the description it sounds like simply calling back your new object methods from request handlers would do the job. But perhaps having a NotificationQueue in the new class and process notifications in a separate thread would make sense.
73,119,847
73,128,154
Qt attribute(property) binding to QLabel
Hi I'm pretty new in Qt. Can I binding class attribute(or property) to QLabel text? For example, class Dog{ string name; } QLabel lbl; When I change dog's name, I'd like to change lbl.text
In Qt things that you are talking about are the territory of signals and slots. Good way to do: Dog.h: #ifndef DOG_H #define DOG_H #include "QObject" class Dog: public QObject { Q_OBJECT public: void setDogsName(const QString &name) { m_Name = name; emit dogsNameChanged(name); } signals: void dogsNameChanged(const QString &name); private: QString m_Name; }; #endif // DOG_H Q_OBJECT macro is needed for signal/slot connections to work (and it's got to be in private section, e.g. above public: here). Code's got to be in a separate .h file (!). main: int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel lbl; Dog dog; QObject::connect(&dog, &Dog::dogsNameChanged, &lbl, &QLabel::setText); dog.setDogsName("TEST"); lbl.show(); return a.exec(); } Result: here. Read about connections in Qt here.
73,119,852
73,120,182
New C++11 for loop causes "error: ‘begin’ was not declared in this scope" using it for an struct with array
I'm having a struct with an array which is static and want to access the data in that array. Tried to use the new C++11 for loops and also do it without the for loop and just print array[1]. See the second cout in the main function. I already know that the problem have to do something with the fact that the array in the struct tCalcAngularEstimationFromComplexData_32 is adjusted as a pointer type. Therefore I tried to use for (const auto &arr : &test_data_1) but wasn't able to solve it. Thanks. typedef struct tComplex_R { float real; float imag; }tComplex_R; typedef struct tOutputVRx_R { float range; float vel; tComplex_R AmpLinRx[1]; } tOutputVRx_R; typedef struct tCalcAngularEstimationFromComplexData_32{ int antennas_azimuth; int antennas_elevation; tOutputVRx_R dataset1[32]; //Range Velocity and Complex Data for 32 Antennas } tCalcAngularEstimationFromComplexData_32; static tCalcAngularEstimationFromComplexData_32 tCalcAngEstComplexData_dataset_1 = { 5, 90, {{1, 3, {10, 15}}, {2, 4, {11, 16}} } }; int main(){ tCalcAngularEstimationFromComplexData_32 test_data_1 = tCalcAngEstComplexData_dataset_1; cout << "Range 1: " << test_data_1.dataset1->range << endl; cout << "Range 2: " << test_data_1.dataset1[1]->range << endl; //Not working for (const auto &arr : test_data_1) { cout << "Range: " << arr.dataset1->range << endl; } }
Range-based for loops need to have access to the bounds of what you're iterating. As noted on the relevant cppreference page, there are three ways: It is an array of known size (which is the case for your dataset1 member) my_struct::begin() and my_struct::end() are defined begin(my_struct&) and end(my_struct&) are defined As for this line: cout << "Range 2: " << test_data_1.dataset1[1]->range << endl; //Not working It is because dataset1[1] is not a pointer but a reference, so you don't use -> but . instead. See a working example on godbolt
73,120,076
73,131,517
C linkage function cannot return c++ class when converting cpp to dll
After following some simple tutorial, I want to convert my cpp program to a dll file, however, it return several errors, like C2526'split':c linkage function cannot return c++ class 'std::vector<std::string,std::allocator<std::string>>' C2371'split':redefinition;different basic types C2491 'split':definition of dllimport function not allowed C2065 'split':undeclared identifier in pch.h #ifndef PCH_H #define PCH_H #include "framework.h" #endif //PCH_H #ifdef IMPORT_DLL #else #define IMPORT_DLL extern "C" _declspec(dllimport) //I follow tutor, but I doubt it cannot works if you use cpp when define extern "C" #endif #include <iostream> #include <string> #include <fstream> #include <vector> #include <algorithm> IMPORT_DLL std::vector<std::string> split(std::string s, std::string delimiter); IMPORT_DLL std::string removespaces(std::string str); IMPORT_DLL std::string findevent(std::string str); in pch.cpp #include <iostream> #include <string> #include <fstream> #include <vector> #include <algorithm> std::vector<std::string> split(std::string s, std::string delimiter) {} std::string removespaces(std::string str) {} std::string findevent(std::string str) {} I am sorry, I am a novice in cpp and dll,so any suggestion is helpful! Need I rewrite all program to c, not cpp?
About C calling C++ DLL, you need to pay attention to the following points: 1.The C++ function interface for C calls cannot contain C++-specific things. 2.When compiling a dll called by c code, extern "C" should be added before the function declaration in the header file to tell the compiler to process the function name according to the c specification. 3.After the compilation is completed, the header file provided for c cannot contain extern "C", which can be solved by using the macro switch, or by rewriting a header file.
73,120,143
73,121,228
Recompile C++ binary from debug info
This is more out of curiosity than productive need but I have been asking myself if it is possible to extract the C++ source of a binary such that it can be recompiled to produce a working clone of the binary. If have tried to: compile the binary with "-g -Og" to include dwarf info, used objdump with "-S" and "--source-comment" to interleave the sources into the dump grepped out all the commented source lines removed the comment and formatted with clang-format The output is pretty decent C++ but there is quite some confusion with the order of the source lines and with sources lines that have no real effect (such as a function's closing "}"). Example: bool UsartHal1::isTransmitRegisterEmpty() { return USART1->SR & USART_SR_TXE; bool Usart1::write(uint8_t data) { if (UsartHal1::isTransmitRegisterEmpty()) { USART1->DR = data; UsartHal1::write(data); return true; } else { return false; } } return USART1->SR & USART_SR_RXNE; } bool Usart1::read(uint8_t & data) { if (UsartHal1::isReceiveRegisterNotEmpty()) { data = USART1->DR; UsartHal1::read(data); return true; } else { return false; } } return USART1->SR & USART_SR_RXNE; I can of course imagine that what I am trying to do is simply not possible - not all source lines have an effect that will make it to the binary and there is no real reason for the compiler to guarantee that the code placement will adhere to the order of lines in the sources. Still I am wondering if there are perhaps some options/esoteric compiler-flags that will make this possible? After all, coverage analysis tools face the same problems.
Debug symbols contain a lot of information that allows you to map stuff from the binary back to the source code (assuming you have access to both) especially in unoptimized builds. But extracting/recreating the original source exactly from the compiled binary is simply not possible.
73,120,244
73,120,374
passing an object as a parameter to a constructor of another class C++
I'm trying to make a user interface class for display the weather forecast retrieve from an API, using a Nokia5110 LCD, but I'm getting an error when I try to pass a reference to an Adafruit_PCD8544 Object from the .ino to the constructor of the class. Some help will be highly appreciated. The error i get: "error: no matching function for call to Adafruit_PCD8544::Adafruit_PCD8544()" this is the main.ino file: // Nokia 5110 LCD pinout connections to nodeMCU8266 #define CLK_PIN D1 // Serial clock out (SCLK) #define DIN_PIN D2 // Serial data out (DIN) #define DC_PIN D5 // Data/Command select (D/C) #define CS_PIN D6 // lCD chip select (CS) #define RST_PIN D4 // LCD reset (RST) Adafruit_PCD8544 display = Adafruit_PCD8544(CLK_PIN, DIN_PIN, DC_PIN, CS_PIN, RST_PIN); UI_Nokia5110 UI(display); this is the header file for the UI.h: #ifndef UI_WEATHER_API_H #define UI_WEATHER_API_H #include <Arduino.h> #include <SPI.h> #include <Adafruit_GFX.h> #include <Adafruit_PCD8544.h> class UI_Nokia5110{ private: Adafruit_PCD8544 display ; public: UI_Nokia5110(){} UI_Nokia5110(Adafruit_PCD8544 &display); }; #endif here, the implementation UI.cpp #include "UI_Nokia5110.h" UI_Nokia5110::UI_Nokia5110(Adafruit_PCD8544 &display){ this->display = display; }
Members are initialized before the constructor body is executed. The constructor body is not the place to initialize members. If you do not provide an initializer, the member display will be default constructed. The error says Adafruit_PCD8544 has no default constructor. Use the member initializer list: UI_Nokia5110::UI_Nokia5110(Adafruit_PCD8544 &display) : display(display) { // nothing to be done here, members are already initialized } For more details I refer you to https://en.cppreference.com/w/cpp/language/constructor
73,120,702
73,162,413
Why DACL entries of a file printed via win32 API is not matching up with DACL information in the file properties?
Here is the minimal code for reference ULONG result = GetSecurityInfo(Hfile , SE_FILE_OBJECT , OWNER_SECURITY_INFORMATION |GROUP_SECURITY_INFORMATION| DACL_SECURITY_INFORMATION , &sidowner , &sidgroup , &pdacl , NULL , &psd); This is how I extracted the access control entries from DACL BOOL b = GetAce(pdacl, i, (LPVOID*)&ace); if (((ACCESS_ALLOWED_ACE*)ace)->Header.AceType == ACCESS_ALLOWED_ACE_TYPE) { sid = (PSID)&((ACCESS_ALLOWED_ACE*)ace)->SidStart; LookupAccountSid(NULL, sid, oname, &namelen, doname, &domainnamelen, &peUse); wcout << "domianName/AccoutName : " << doname << "/" << oname << endl; mask = ((ACCESS_ALLOWED_ACE*)ace)->Mask; cout << "Allowed" << endl; } output: domianName/AccoutName : BUILTIN/Administrators Allowed DELETE FILE_GENERIC_READ FILE_GENERIC_WRITE FILE_GENERIC_EXECUTE READ_CONTROL WRITE_DAC WRITE_OWNER SYNCHRONIZE domianName/AccoutName : BUILTIN/Administrators Allowed DELETE FILE_GENERIC_READ FILE_GENERIC_WRITE FILE_GENERIC_EXECUTE READ_CONTROL WRITE_DAC WRITE_OWNER SYNCHRONIZE domianName/AccoutName : BUILTIN/Administrators Allowed DELETE FILE_GENERIC_READ FILE_GENERIC_WRITE FILE_GENERIC_EXECUTE READ_CONTROL SYNCHRONIZE domianName/AccoutName : BUILTIN/Users Allowed FILE_GENERIC_READ FILE_GENERIC_WRITE FILE_GENERIC_EXECUTE READ_CONTROL SYNCHRONIZE As we can see from the above output Administrators have multiple entries and ACE of "System" and "Authenticated users" are not found. "Users" only have read rights in file properties but in the output, it is printed that the "Users" have "Write access" as well. I did a lot of research and read through many books but nothing seems to give a clear-cut answer edit: Here's the output using the CACLS command. C:\Users\Administrator>cacls e:/hello.txt e:\hello.txt BUILTIN\Administrators:F NT AUTHORITY\SYSTEM:F NT AUTHORITY\Authenticated Users:C BUILTIN\Users:R
The first part of the question: The reason why the program prints the name same account name repeatedly is because the LookupAccountSid function does not have enough data area. since the namelen and domainlen are IN\OUT arguments the function returns the size of the domain name and account name every time after execution. So to solve this the namelen and domainlen have to be reassigned every time. LookupAccountSid(NULL, sid, oname, &namelen, doname, &domainnamelen, &peUse); wcout << "domianName/AccoutName : " << doname << "/" << oname << endl; namelen = 100; domainnamelen = 100; //This should solve the problem Here is the link to the docs for the LookupAccountSid function The second part of the question The reason why the output from the program shows the users have FILE_GENERIC_WRITE permission even though the CACLS seem to show that users only have read and execute permission to the given file path is that in the program the code that checks if the users have the write permissions is done by the following. if (FILE_GENERIC_WRITE & ace->Mask) { wcout << " FILE_GENERIC_WRITE" << "\n"; } The problem is the FILE_GENERIC_WRITE consists of multiple permissions like STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE and when the code is written like this (FILE_GENERIC_WRITE & ace->Mask) it only checks if at least one of the permissions is present or not. A special thanks to @user253751 and @Werner Henze for patiently explaining the solution
73,121,138
73,122,039
C++ string dynamic 2D array cause memory leak
When I use a string type dynamic 2D array, there is memory leak after deleting the array. Please view the following code: #include <string> using namespace std; #define NEW2D(H, W, TYPE) (TYPE **)new2d(H, W, sizeof(TYPE)) void* new2d(int h, int w, int size) { register int i; void **p; p = (void**)new char[h*sizeof(void*) + h*w*size]; for(i = 0; i < h; i++) { p[i] = ((char *)(p + h)) + i*w*size; } return p; } If I use the following code: string** pstr = NEW2D(2, 4, string); memset(pstr[0], 0, sizeof(string)*2*4); delete [] pstr; There is no memory leak; however, if I use the following code: string** pstr = NEW2D(2, 4, string); memset(pstr[0], 0, sizeof(string)*2*4); for (int j = 0; j < 2; j++) for (int i = 0; i < 4; i++) pstr[j][i] = "test"; for (int j = 0; j < 2; j++) for (int i = 0; i < 4; i++) pstr[j][i].clear(); delete [] pstr; The memory leak is happened, even if I have called pstr[j][i].clear(). What should I do to avoid memory leak after having for (int j = 0; j < 2; j++) for (int i = 0; i < 4; i++) pstr[j][i] = "test"; in my code?
The problem with your code because it treats non-trivial types like std::string as if they were trivial. Probably you could create something using placement new that was legal C++ and worked in a similar way to the code you've written But here's an simple alternative that (hopefully) works template <typename T> T** new2d(int h, int w) { T** p = new T*[h]; T* q = new T[h*w]; for (int i = 0; i < h; i++) p[i] = q + i*w; return p; } And to delete template <typename T> void free2d(T** p, int h) { if (h > 0) delete[] p[0]; delete[] p; } Untested code.
73,121,385
73,123,246
How to pass std::index_sequence param to an nested-template struct according to function traits
Here is my simple code and it did work (I passed single integer to argument): #include <iostream> #include <tuple> #include <string> #include "boost/variant.hpp" using TObjList = std::vector<boost::variant<std::string, int>>; template<typename> struct FTrait; template<typename R, typename... A> struct FTrait<R(A...)> { using RetType = R; using ArgsTuple = std::tuple<A...>; static constexpr std::size_t arity = sizeof...(A); template<size_t N> struct argument { static_assert( N < arity , "error: invalid argument index"); typedef typename std::tuple_element_t<N, std::tuple<A...>> type; }; }; void Show(const std::string& s, int a) { std::cout << s << "\n" << a << "\n"; } int main() { TObjList list; list.emplace_back("hello"); list.emplace_back(567); Show(boost::get<FTrait<decltype(Show)>::argument<0>::type>(list[0]), boost::get<FTrait<decltype(Show)>::argument<1>::type>(list[1])); } But the following code did not work (Maybe I passed a sequence to argument): #include <iostream> #include <tuple> #include <string> #include "boost/variant.hpp" using TObjList = std::vector<boost::variant<std::string, int>>; template<typename> struct FTrait; template<typename R, typename... A> struct FTrait<R(A...)> { using RetType = R; using ArgsTuple = std::tuple<A...>; static constexpr std::size_t arity = sizeof...(A); template<size_t N> struct argument { static_assert( N < arity , "error: invalid argument index"); typedef typename std::tuple_element_t<N, std::tuple<A...>> type; }; }; // here is new code template<typename T> struct ConvertOne { T operator () (const TObjList& List, size_t Index) { if ( Index < List.size() ) { return boost::get<T>(List[Index]); } } }; template<typename F, size_t... Index> void MyCall(const F& Func, const TObjList& List, const std::index_sequence<Index...>&) { // This code not work: Func(ConvertOne<typename FTrait<F>::argument<Index>::type>{}(List, Index)...); // These code would work: // using ArgsTuple = typename FTrait<F>::ArgsTuple; // Func(ConvertOne<std::decay_t<typename std::tuple_element_t<Index, ArgsTuple>>>{}(List, Index)...); } // new code done void Show(const std::string& s, int a) { std::cout << s << "\n" << a << "\n"; } int main() { TObjList list; list.emplace_back("hello"); list.emplace_back(567); // new invoke MyCall(Show, list, std::make_index_sequence<FTrait<decltype(Show)>::arity>{}); } This code would raise a compile error: ftrait.cpp: In function ‘void MyCall(const F&, const TObjList&, std::index_sequence<Index ...>&)’: ftrait.cpp:34:62: error: template argument 1 is invalid Func(ConvertOne<typename FTrait<F>::argument<Index>::type>{}(List, Index)...); I hope to use std::index_sequence and function_traits to make the program automatically identify the type and number of parameters of a function, like std::tuple_element<Index, ArgsTuple>::type. boost::function_traits cannot satisfy me, so I try to implement by myself. What should I do? Thanks :)
In your case, typename FTrait<F>::argument<0>::type is const std::string&. std::get<const std::string&>(list[0]) won't compile you need std::get<std::string>(list[0]). It might be solved with std::decay: template<typename F, size_t... Index> void MyCall(const F& Func, const TObjList& List, const std::index_sequence<Index...>&) { Func(ConvertOne< typename std::decay< typename FTrait<F>::template argument<Index>::type >::type >{}(List, Index)...); } Demo
73,121,967
73,122,245
How to remove an item from a list of tuples in c++?
I'm iterating over my list of tuples : list<tuple<int,int>> edges, and want to remove some elements in it. This is necessary for me to reduce the total overhead as I am working with huge data. std::list<tuple<int, int>>::iterator it; for (it = edges.begin(); it != edges.end(); ++it) { if (get<0>(*it) == 0 || get<1>(*it) == 0){ edges.remove(*it); } } As I know, remove(element) works, but here edges.remove(*it) does not. How can I do this correctly?
In C++20, you can simply use a specialization of std::erase_if for std::list to do this. #include <list> #include <tuple> int main() { std::list<std::tuple<int, int>> l; std::erase_if(l, [](const auto& elem) { auto& [first, second] = elem; return first == 0 || second == 0; }); } Demo However, since std::list itself has a remove_if member function, it is more appropriate to use it directly, since it applies to any C++ standard.
73,122,040
73,122,076
C++ Is it safe to modify a int64_t when reading it from another thread?
I have 2 threads, A and B. Thread A want to let B know how many records of data it has received. In modern C++, we can use Atomic or CAS or Mutex to modify the counter. How ever, neither of them is fast enough for me. I am thing about, use a int64_t without a lock to share data counter between threads. Only thread A can modify it, other threads can only read it. I don't know whether it is safe to do so. I know in x86-64 machines, a 64 bit int can be written with one single asm store. So I think it should be safe. And I write the following code to check it. If the method is not safe, cnt will not always increase because we will read wrong values from that 64bit memory. #include <iostream> #include <vector> #include <thread> using namespace std; int main() { int64_t cnt = 0; vector<thread> threadVec; for (int i=0; i<10; i++){ threadVec.emplace_back(move(thread([&cnt](){ int64_t prev = 0, tmp = 0; while(prev != INT64_MAX){ tmp = cnt; // If it is not safe, tmp will not increase all the time. if (tmp < prev) cout << "Error cnt declined" << endl; // if (tmp % 1000000 == 0) cout << tmp << endl; prev = tmp; } }))); } this_thread::sleep_for(chrono::seconds(1)); while(cnt < INT64_MAX) cnt++; for (auto& t : threadVec) t.join(); return 0; } So is the idea correct?
No, it's undefined behavior. Make it a std::atomic<int64_t>, instead. This is what std::atomic is for.
73,122,400
73,122,845
How to make a template class that force it's child class to extends itself?
I would like to know the C++ equivalent of the following Java code. public Class MyClass <T extends MyClass<T>> {...} I have tried the following but failed using C11: template <class T> class Parent { static_assert(std::is_base_of<Parent<T>, T>::value); public: T* next; }; class Child: public Parent<Child> { public: Child* next; }; Which results in: incomplete type `Child` used in type trait expressions
Unfortunately, within CRTP, T is an incomplete type (so most traits won't work on it). You might add the check in a member instead (type would be complete at that point). Good candidates are constructor and destructor: template <class T> class Parent { // T is incomplete here. public: ~Parent() noexcept { // T is complete here. static_assert(std::is_base_of<Parent<T>, T>::value); } public: T* next; };
73,122,595
73,122,807
Visualize the Result of a Hough Transformation
I am currently programming a laser 3D-sensor which provides me with edge points (X,Y,Z) in a 2D array as a result. The coordinates are used to perform a Hough-transform. The result in Rho and Theta is output to my console.My question now is whether I can visualise this result, to check for correctness. I have thought of the library OpenCV, but I am not familiar with its programming and have only seen functions and examples that have transformed and visualised images specified by a file path. Maybe someone can tell me if OpenCV supports a function that allows the visualisation of the Rho and Theta values as raw input, or if there are other possibilities. Many thanks in advance With kind regards Simon
You can draw your points in an OpenCv image as a contour , then apply Hough transform as follow: cv::Mat dst; cv::drawContours(dst, contours, -1, cv::Scalar(0, 255, 0), 2); // contours is your 2D vector) vector<Vec2f> lines; // will hold theta and rho HoughLines(dst, lines, 1, cv::CV_PI/180, 150, 0, 0 ); for( size_t i = 0; i < lines.size(); i++ ) { float rho = lines[i][0], theta = lines[i][1]; std::cout << "rho = " << rho << " theta = " << theta << '\n'; }
73,122,646
73,122,779
Initializing a std::shared_ptr<std::random_device>
I understand that std::random_device is non-copyable. In this scenario, I have a std::shared_ptr<std::random_device> that I want to init in one of the member functions of the class. I assumed std::move would work. I was wrong. Would somebody explain what the 'proper' way to init the same is ? Note : std::random_device rng = std::make_shared<std::random_device> (std::random_device) doesn't work either. Class.h class SomeClass { private: std::shared_ptr<std::random_device> rng; std::shared_ptr<std::mt19937> uniform_rng; }; Class.cpp SomeClass::ctor() { //rng = std::make_shared<std::random_device>(std::random_device); -> faulty //rng = std::make_shared<std::random_device>(std::random_device()); -> also faulty uniform_rng = std::make_shared<std::mt19937> (*rng); }
You seem confused about the syntax. This is not valid C++: std::random_device rng = std::make_shared<std::random_device> (std::random_device); It looks somewhat like you were trying to do this: std::shared_ptr<std::random_device> rng = std::make_shared<std::random_device> (std::random_device{}); That would build a random_device, then call make_shared with it, which effectively tries to invoke a move constructor while building a new random_device in that shared object. That indeed only works with a copy or move constructor and is unnecessarily inefficient. What you want is simply this: std::shared_ptr<std::random_device> rng = std::make_shared<std::random_device>(); That simply constructs (via its default constructor), a new random device together with the shared pointer state. Note that whatever you pass to make_shared is passed to the constructor of the contained object. In this case, nothing because it is the default constructor. EDIT: And for the edited question, the last line should be uniform_rng = std::make_shared<std::mt19937>((*rng)()); to draw a single number from the random device and pass it to the mt19937 constructor. The usual caveats of initializing a mersenne twister with its enormous internal state from a single random integer apply but that is not relevant to the question.
73,122,708
73,125,400
cmake generator expression for target architecture?
Is there a modern approach to use target architecture within a condition for a generator expression in CMake? There are some answers that are somewhat outdated. I am looking for a modern or at least very robust and reliable custom script for using target architecture within a generator expression. The docs do not seem to contain that kind of info. One of the ideas for a workaround I see is to use $<<STRING:MY_DETECTED_ARCH:ARCH_ARM>:src_for_arm.cpp>
I checked a solution from this answer and it worked. cmake_minimum_required(VERSION 3.14.2 FATAL_ERROR) project(cmake_target_arch) set(CMAKE_CXX_STANDARD 17) include(TargetArch.cmake) target_architecture(TARGET_ARCH) message(STATUS "target_architecture: ${TARGET_ARCH}") add_executable(cmake_target_arch main.cpp $<$<STREQUAL:"${TARGET_ARCH}","x86_64">:x86_64.cpp> $<$<STREQUAL:"${TARGET_ARCH}","i386">:i386.cpp> $<$<STREQUAL:"${TARGET_ARCH}","armv7">:armv7.cpp> ) main.cpp #include <iostream> #include <string> extern std::string hello_message(); int main() { std::cout << hello_message() << std::endl; return 0; } i386.cpp #include <string> std::string hello_message() { return "Hello i386!"; } Example output for i386 binary: C:\Users\serge\dev\repos\cmake_target_arch\cmake-build-release-visual-studio-win32\cmake_target_arch.exe Hello i386! I guess one can come up with a CMake Macro to wrap strings comparison
73,122,891
73,126,434
How to pass structure with template variable as an argument inside member function of class in c++?
I would like to pass 'structure with template variable' as an argument inside member function of class. I am getting error "no matching function for call to". Can anyone help me? I am doing some mistake either in declaration / definition / while passing argument from the main. template <typename T> struct msg_1{ int var_1; int var_2; T *var_3; }; template<typename T> struct msg_2{ int var_1; int var_2; T *var_3; }; class A { public: int a; int b; template <typename T> void test(T *, T *); }; template <typename T> void A::test(T *t1, T *t2) { cout<<"Inside test @todo Do something"; } int main() { A ob; ob.a=10; ob.b=20; msg_1<int> *ob_1 = new msg_1<int>; msg_2<int> *ob_2 = new msg_2<int>; ob.test(ob_1,ob_2); return 0; } ======== I have accepted the given suggestion and modified the code, but getting some error while implementing. Kindly have a look. I have passed the structure as a parameter in test method like below template <typename T> struct msg1{ … }; template<typename U> struct msg2{ … }; struct msg3 { uint16_t var_4; }; class A { public: int a; int b; template <typename T, typename U> void test(msg1<T> *t1, msg2<U> *t2); }; template <typename T, typename U> void A::test(msg1<T> *t1, msg2<U> *t2) { cout<<"Inside test @todo Do something"; } int main() { A ob; ob.a=10; ob.b=20; msg_1<msg3> *ob_1 = new msg_1<msg3>; msg_2<msg3> *ob_2 = new msg_2<msg3>; ob.test(ob_1,ob_2); return 0; } When I am running above code in online compiler then it’s running fine but when I am implementing it in actual code to do testing then I am getting compile time error “undefined reference to ‘void A::test< msg3, msg3 > ( msg1 *, msg2 * )’. Can anyone please tell me what possibly I am doing wrong.
Your template function A::test is only templated with one type T and requires that both parameters have the same type T*. In your example you pass different parameters: msg_1<int> * and msg_2<int> *. If you really want test to only accept two parameters with identical type, then you can't pass ob_1 and ob_2. If you want test to accept two parameters of different type, then you can change your class A and function A::test as follows. class A { public: int a; int b; template <typename T1, typename T2> void test(T1 *, T2 *); }; template <typename T1, typename T2> void A::test(T1 *t1, T2 *t2) { cout<<"Inside test @todo Do something"; }
73,123,672
73,148,315
Is it possible to cross-compile C++ applications from Linux for Windows XP?
I have a simple console application which I already ported to Windows. I also cross-compile it using mingw. However the problem is applications compiled like this only run on Windows Vista or newer. How would I go about compiling it for XP using Linux? Also, I don't know if this is necessary, but here are my compiler flags: x86_64-w64-mingw32-windres src/icon.rc src/icon.o x86_64-w64-mingw32-g++ -o cli-mg-64bit-windows.exe src/main.cpp src/icon.o -static i686-w64-mingw32-windres src/icon.rc src/icon.o i686-w64-mingw32-g++ -o cli-mg-32bit-windows.exe src/main.cpp src/icon.o -static
You to use a version of MinGW-w64 that was built with configure flags --with-default-msvcrt=msvcrt-os and --with-default-win32-winnt=0x0501. These flags will result in MinGW-w64 libraries that will only use Windows features available up to Windows XP.
73,124,077
73,124,390
Why do DLLs have a private section?
Based on what I've read about exporting symbols from a DLL in Microsoft's documentation, you can tell the linker to not include a symbol in the .lib import file by appending the PRIVATE keyword to the export. This, in effect, hides that symbol from application code that uses the library. My question is, doesn't the C++ keyword static already make variables/functions invisible to any external translation units?
static and PRIVATE (wrt. DLLs, similar to -fvisibility=hidden for Linux DSOs) are two different concepts. The C++ standard as such is agnostic to DLLs and its implementations on different operating systems. static is applied on a translation unit (TU) level, i.e. it restricts the visibility of a symbol (function/variable) to the file it was defined in. So if you have two files a.cpp and b.cpp, neither can see the static symbols of the other. Say you define a function static void foo() in a.cpp. There is no way b.cpp (or any other TU) can see foo(), because you've restricted its visibility to the file it was defined in. On the contrary, PRIVATE restricts visibility on the DLL level, i.e. what is accessible when using the DLL. Meaning that the function void bar() (note: non-static) defined in a.cpp can be used by b.cpp, either by an extern declaration or by including some header a.h. However if you declare bar() as PRIVATE in your .DEF file, users of your DLL won't be able to call bar(), because the respective symbol won't be exported. In that respect, static is a bit more restrictive than PRIVATE, because it already restricts visibility on TU level.
73,124,165
73,124,234
How to convert a char16_t into a stringstream divided with 2 bytes
I made a utf8 to utf16 conversion where i get the code units for the utf16 char16_t. { std::string u8 = u8"ʑʒʓʔ"; // UTF-8 to UTF-16/char16_t std::u16string u16_conv = std::wstring_convert< std::codecvt_utf8_utf16<char16_t>, char16_t>{} .from_bytes(u8); std::cout << "UTF-8 to UTF-16 conversion produced " << u16_conv.size() << " code units:\n"; for (char16_t c : u16_conv) std::cout << std::hex << std::showbase << c << ' '; } Output : TF-8 to UTF-16 conversion produced 4 code units: 0x291 0x292 0x293 0x294 I now need to pass the code units to a stringstream if possible and I don't know how to convert this into a 2 bytes like so : 0x02,0x91,0x02,0x92,0x02,0x93,0x02,0x94 Any suggestions ? Maybe converting it first to a uint8_t vector?
A straightforward way is adding each bytes to std::stringstream using a loop. std::stringstream ss; for (char16_t c : u16_conv) { ss << (char)(c >> 8); ss << (char)c; } std::string str = ss.str(); for (char c : str) { std::cout << std::hex << std::showbase << (int)(unsigned char)c << ' '; }
73,124,199
73,129,656
static object calls constructor at wrong time
I have an opengl batch renderer, which has a static vao, vbo, ebo etc. problem is, int the constructor of those are opengl methods. now, because they are static the opengl methods like glGenBuffers get called before opengl has been initialized. so you can get a better picture, this is how it looks: class renderer2d { private: static vertex_array vao; static vertex_buffer vbo; static index_buffer ibo; public: static void draw(); static GLuint create_quad(glm::vec2 position, glm::vec2 size, GLfloat angle, glm::vec4 color); } and int the constructor of e.g. vao: vao() { //some sort of opengl method, that gets called without opengl being initialized glGenVertexArrays(1, &id); } btw, i dont only want to "solve" the problem while keeping the "static solution", if you have different ideas on how to do this, please tell me
One trick is to delay initialisation of the object like this: renderer2d& get_renderer() { static renderer2d renderer; return renderer; } This method works for any class, it does not require the renderer itself to have static data. The function can also be a static member of the class, as part of the Meyers singleton design.
73,124,745
73,124,795
Convert integer to binary string with variable size
Suppose I want to get every combination of 1's and 0's with length n. For example, if n = 3, then I want 000 001 010 011 100 101 110 111 My initial thought was to use something like: #include <iostream> #include <bitset> #include <cmath> int main() { int n = 3; for (int i = 0; i < pow(2, n); i++) std::cout << std::bitset<n>(i).to_string() << '\n'; } but this does not work since std::bitset takes a const, whereas I need n to be variable (for example if I am in a loop). How can I do this?
A straightforward way: Extract each bits using bitwise shift operation. #include <iostream> int main() { int n = 3; for (int i = 0; i < (1 << n); i++) { for (int j = n - 1; j >= 0; j--) { std::cout << ((i >> j) & 1); } std::cout << '\n'; } return 0; } Note that this method will work only if n is small enough not to cause an integer overflow (1 << n doesn't exceed INT_MAX). To generate larger sequence, you can use recursion: #include <iostream> #include <string> void printBits(int leftBits, const std::string& currentBits) { if (leftBits <= 0) { std::cout << currentBits << '\n'; } else { printBits(leftBits - 1, currentBits + "0"); printBits(leftBits - 1, currentBits + "1"); } } int main() { int n = 3; printBits(n, ""); return 0; }
73,124,815
73,149,655
Elegantly switching template arguments for a set of functions
I am writing some code that uses an external library, where several functions are defined approximately like this: // Library.h template<typename T> void foo(int arg1, bool arg2); template<typename T> int bar(float arg); (examples are given to illustrate that both argument lists and return value types are diverse, but do not contain the template type T). In my code, I want to be able to call different template instances offoo and bar, depending on some internal mapping logic. This can be e.g. a mapping from an enum representing data types, but, importantly, this logic is the same for foo, bar, or anything else form this library. A simple way to achieve this would be something like // MyCode.h enum class MyType { BOOL, CHAR }; void foo_wrapper(MyType type, int arg1, bool arg2) { if (type == MyType::BOOL) return foo<bool>(arg1, arg2); else if (type == MyType::CHAR) return foo<char>(arg1, arg2); else throw std::runtime_error("oops"); } int bar_wrapper(MyType type, float arg) { if (type == MyType::BOOL) return bar<bool>(arg); else if (type == MyType::CHAR) return bar<char>(arg); else throw std::runtime_error("oops"); } However, this is a lot of logic duplication and correcting the arg names, etc., when it would be needed for another function, leaving plenty of possibilities for missing something. My current solution is to have a static map of relevant template instantiations in each wrapper function: void foo_wrapper(MyType type, int arg1, bool arg2) { using FunctionType = std::function<void(int, bool)>; static const std::unordered_map<MyType, FunctionType> functionMap{ {BOOL, foo<bool>}, {CHAR, foo<char>} }; if (!functionMap.count(type)) throw std::runtime_error("oops"); return functionMap.at(type)(arg1, arg2); } int bar_wrapper(MyType type, float arg) { using FunctionType = std::function<int(float)>; static const std::unordered_map<MyType, FunctionType> functionMap{ {BOOL, bar<bool>}, {CHAR, bar<char>} }; if (!functionMap.count(type)) throw std::runtime_error("oops"); return functionMap.at(type)(arg); } Upside: Arguments are passed only in one place in code, the mapping is "centralized" at the beginning of each wrapper instead of distributed in wrapper function code. Also, less code of the choice logic is being copied around. But: We still need to duplicate the mapping correspondencies - now in the shape of a map declaration - across multiple wrappers (imagine a dozen library functions used in this way...). Ideally, I would like to have a magic switch_type_for_func implemented that would allow doing something like void foo_wrapper(MyType type, int arg1, bool arg2) { return switch_type_for_func<foo>(type, arg1, arg2); } int bar_wrapper(MyType type, float arg) { return switch_type_for_func<bar>(type, arg); } I see that this cannot work because foo is a template, but it intuitively feels as if there should be some solution that would eliminate code duplication in this case. I can almost imagine a macros doing the job (because what I need is just the name of the function, not much more), but AFAIU these are not exactly best practice... Maybe I am just stuck in my way of thinking about it and there is something more appropriate. Any feedback/advice is appreciated!
First of all, it's clear that there is no 100% elegant solution because you can't really do anything with function templates except instantiating them. You can't abstract over them whatsoever. So at least a small amount of boilerplate code for every function template is required. But I think lambdas provide a neat way to accomplish this with the least amount of typing overhead possible. In C++20, you can do this: template <class F> auto dispatcher(F&& f, MyType t) { switch (t) { case MyType::BOOL: return f.template operator()<bool>(); case MyType::CHAR: return f.template operator()<char>(); }; } auto foo_wrapper(MyType type, int arg1, bool arg2) { return dispatcher([&]<class T>() { return foo<T>(arg1, arg2); }, type); } auto bar_wrapper(MyType type, float arg) { return dispatcher([&]<class T>() { return bar<T>(arg); }, type); } https://godbolt.org/z/796xETr3o That's two lines per new MyType value, and one lambda (inside the wrapper function you were going to write anyway) per function you want to wrap. I don't think you'll get much better than this. The default by-reference capture should be perfectly fine - it would only fail if you were to take something by value in the wrapper which the original function takes by ref (and even then it would have to store the reference in global state to cause danger), which you obviously shouldn't do. FWIW, you can emulate this before C++20 (but with C++14) using polymorphic lambdas instead, it's just more ugly (if you don't want to go all crude): // ... case MyType::BOOL: return f(std::type_identity<bool>{}); // ... return dispatcher([&](auto ti) { return foo<decltype(ti)::T>(arg1, arg2); }, type); https://godbolt.org/z/7cjdzx681 Quite a bit more awkward to type/decipher, but doesn't require templated lambdas.
73,124,846
73,133,536
Month auto increment using mktime and timegm functions in C++
I'd like to convert a string date (UTC) to a timestamp using C++. It works fine except for the month, which is auto incremented by one. If the string is 20221222074648, for 2022-12-22 07:46:48, the timestamp will be 1674373608, which is the timestamp of 2023-01-22 07:46:48. I don't understand the reason of this auto-increment, because there's no changes of the month's variable in the code below. cout << "date : " << receivedDate << endl; struct tm t; time_t timestamp; size_t year_size = 4; size_t other_size = 2; t.tm_year = stoi(receivedDate.substr(0, 4), &year_size, 10) - 1900; t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10); t.tm_mday = stoi(receivedDate.substr(6, 2), &other_size, 10); t.tm_hour = stoi(receivedDate.substr(8, 2), &other_size, 10); t.tm_min = stoi(receivedDate.substr(10, 2), &other_size, 10); t.tm_sec = stoi(receivedDate.substr(12, 2), &other_size, 10); t.tm_isdst = -1; cout << "year : " << t.tm_year + 1900 << "\nmonth : " << t.tm_mon << "\nday : " << t.tm_mday << "\nhour : " << t.tm_hour << "\nminutes : " << t.tm_min << "\nseconds : " << t.tm_sec << endl; timestamp = timegm(&t); cout << "timestamp : " << timestamp << endl; cout << "asctime timestamp : " << asctime(&t);
Your problem is pretty simple ! the tm.tm_mom goes from 0 to 11, You need to add -1 on your month value t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10) - 1;
73,125,259
73,142,379
Need advice on adding test framework (GoogleTest) to a .cpp file having main() function
I am a beginner at testing in CPP and this is my first testing project. I have written a code in CPP and I have to add test cases using any test framework, for which I have decided to use GoogleTest after learning on the internet that it is the most popular and beginner friendly. My .cpp file looks like this... #inlcude<bits/stdlib.h> using namespace std; //fn definitions and declarations read_input(){ //reads input from the user } calculate(){ //processes the input and does calculations } print_output(){ //prints the output } int main() { read_input(); calculate(); print_putput(); return 0; } In the googleTest tutorials, I have seen that the test.cpp is created and there a header file is included and the .cpp file never has a main(), only functions (in this context it would be just the caclculate() function without main() function in cpp... see this example). I want to ask how can I add tests with google test to a .cpp file that I described above having main(), reads input, and prints output.
One way is to create these files: func.h: in which you just put declarations of your functions. Example: // Only function declarations: void read_input(); void print_output(); func.cpp: in which you put the implementation of your functions. This would be similar to what you have but without the main function. This file should include func.h. main.cpp: in which you only put the main function without anything else. This file should include func.h and can call those functions. func_test.cpp: in which you put your tests. This file should include func.h and can call and test those functions. Your build system should be set such that main.cpp and func_test.cpp do not depend on each other, but they each should depend on func.cpp and get linked with it. For examples on using VSCode and Bazel build system with google test, you can check this tutorial. If you use Cmake, you can use this one.
73,125,275
73,125,474
Why do I get this error in Clang? "constexpr if condition is not a constant expression"
I am trying to compile a class using Clang: #include <string> #include <type_traits> #include <cstdlib> struct foo { template <class T, class... Ts> struct is_any: std::disjunction <std::is_same <T, Ts>... >{}; template<typename T, std::size_t N> static constexpr bool is_pointer_to_const_char(T(&)[N]) { return std::is_same_v<const char, T>; } template<typename T> static constexpr bool is_pointer_to_const_char(T &&) { return std::is_same_v<const char *, T>; } template <class T> static constexpr bool is_str( const T& obj ) { return is_pointer_to_const_char( obj ) || is_any<T, std::string, std::string_view>::value; } static constexpr bool is_escape_v( const std::string_view& str ) { return ! str.rfind( "\033", 0 ); } template <class T> inline bool is_escape( const T& str ) const { if constexpr ( is_str( str ) ) return is_escape_v( str ); return false; } }; int main() { foo obj; obj.is_escape( "test" ); } But I get the following error: prove.cpp:36:28: error: constexpr if condition is not a constant expression if constexpr ( is_str( str ) ) return is_escape_v( str ); ^ prove.cpp:44:7: note: in instantiation of function template specialization 'foo::is_escape<char [5]>' requested here obj.is_escape( "test" ); ^ 1 error generated. It seems that it doesn't like the constexpr qualifier I used in the if condition in the is_escape() method. Did I do something wrong in the class method's definition? My Clang version is 10.0.0-4.
Did I do something wrong in the class method's definition? The problem is that function parameters (like str) are not constant expressions. For example, we cannot use str as a template non-type parameter, or as a size of a built-in array. This means the expression is_str( str ) that contains the subexpression str is itself not a constant expression, either. Moreover, the code is rejected by all the three major compilers, if you're using their latest versions. Demo A simpler way of doing this would be as shown below: template <typename T> bool is_escape(const T& str) { if constexpr(std::is_convertible_v<T, std::string>) { return ! std::string(str).rfind( "\033", 0 ); } else { return false; } } Working demo Or just return is_escape_v(str): template <class T> inline bool is_escape( const T& str ) const { if constexpr (std::is_convertible_v<T, std::string_view>) { return is_escape_v( str ); } else { return false; } } Demo
73,125,825
73,126,069
Is it correct to define a global static const std::string in a header file
Is it correct to define a global std::string in a header file like this : namespace Colors { static const std::string s_blue = "Blue"; }
Correct? Yes. static here means that each translation unit (TU) that includes this header will have a unique object. So there isn't 1 s_blue object for the whole project, but one for each TU. However since it's const all objects will be equal, so for the user it doesn't make a difference. Recommended? Maybe, depends. The big downside is that you create multiple objects and all of them are initialized at program startup. Another possible downside is the access pattern. If the program assesses s_blue from multiple TUs in quick succession it could trash the cache. However for certain programs and scenarios this could be the best option or at least "good enough". For instance (spoiler for next paragraph) in a header only library or before C++17. Are there better alternatives? Yes, but they cannot always be used. extern Make it an extern declaration in the header and in just 1 TU have the definition. // constants.hpp extern const std::string k_blue; // constants.cpp #include "constants.hpp" const std::string k_blue = "Blue"; This is clearly superior in terms of performance over OP. However you can't use it in a header only lib. Even in a normal program static could be preferred as the ease of declaring and defining the constants in just one place could be seen as outweighing the performance downsides in specific projects. constexpr inline string_view C++17 A clearly better alternative if it's available (since C++17) is string_view. It's very light weight but has all the amenities of a modern container (unlike raw const char[]). And since you already are in C++17 you should make it constexpr inline: constexpr inline std::string_view k_blue = "Blue"; inline const std::string c++17 If for whatever reason you need std::string over std::string_view you can inline the variable for better optimization: inline const std::string k_blue = "Blue";
73,125,934
73,126,171
Binary files: write with C++, read with MATLAB
I could use your support on this. Here is my issue: I've got a 2D buffer of floats (in a data object) in a C++ code, that I write in a binary file using: ptrToFile.write(reinterpret_cast<char *>(&data->array[0][0]), nbOfEltsInArray * sizeof(float)); The data contains 8192 floats, and I (correctly ?) get a 32 kbytes (8192 * 4 bytes) file out of this line of code. Now I want to read that binary file using MATLAB. The code is: hdr_binaryfile = fopen(str_binaryfile_path,'r'); res2_raw = fread(hdr_binaryfile, 'float'); res2 = reshape(res2_raw, int_sizel, int_sizec); But it's not happening as I expect it to happen. If I print the array of data in the C++ code using std::cout, I get: pCarte_bin->m_size = 8192 pCarte_bin->m_sizel = 64 pCarte_bin->m_sizec = 128 pCarte_bin->m_p[0][0] = 1014.97 pCarte_bin->m_p[0][1] = 566946 pCarte_bin->m_p[0][2] = 423177 pCarte_bin->m_p[0][3] = 497375 pCarte_bin->m_p[0][4] = 624860 pCarte_bin->m_p[0][5] = 478834 pCarte_bin->m_p[1][0] = 2652.25 pCarte_bin->m_p[2][0] = 642077 pCarte_bin->m_p[3][0] = 5.33649e+006 pCarte_bin->m_p[4][0] = 3.80922e+006 pCarte_bin->m_p[5][0] = 568725 And on the MATLAB side, after I read the file using the little block of code above: size(res2) = 64 128 res2(1,1) = 1014.9659 res2(1,2) = 323288.4063 res2(1,3) = 2652.2515 res2(1,4) = 457593.375 res2(1,5) = 642076.6875 res2(1,6) = 581674.625 res2(2,1) = 566946.1875 res2(3,1) = 423177.1563 res2(4,1) = 497374.6563 res2(5,1) = 624860.0625 res2(6,1) = 478833.7188 The size (lines, columns) is OK, as well as the very first item ([0][0] in C++ == [1][1] in MATLAB). But: I'm reading the C++ line elements along the columns: [0][1] in C++ == [1][2] in MATLAB (remember that indexing starts at 1 in MATLAB), etc. I'm reading one correct element out of two along the other dimension: [1][0] in C++ == [1][3] in MATLAB, [2][0] == [1][5], etc. Any idea about this ? Thanks! bye
Leaving aside the fact there seems to be some precision difference (likely the display settings in MATLAB) the issue here is likely the difference between row major and column major ordering of data. Without more details it will be hard to be certain. In particular MATLAB is column major meaning that contiguous memory on disk is interpreted as detailing sequential elements in a column rather than a row. The likely solution is to reverse the two sizes in your reshape, and access the elements with indices reversed. That is, swap the int_size1 and int_size2, and then read elements expecting pCarte_bin->m_p[0][0] = res2(1,1) pCarte_bin->m_p[0][1] = res2(2,1) pCarte_bin->m_p[0][2] = res2(3,1) pCarte_bin->m_p[0][3] = res2(4,1) pCarte_bin->m_p[1][0] = res2(1,2) etc. You could also transpose the array in MATLAB after read, but for a large array that could be costly in itself
73,126,558
73,126,835
How should I use thread_pool in this case?
for example: when I write this code I recieve right result. boost::asio::thread_pool t(3); std::vector<int> vec = {10,20,30}; boost::asio::post(t, [&]{ foo(vec[0]);}); boost::asio::post(t, [&]{ foo(vec[1]);}); boost::asio::post(t, [&]{ foo(vec[2]);}); t.join(); but when i want use boost::asio::post in for-cicle i recieve error Microsoft Visual C++ Runtime Library: "Expression: vector subscript out of range" boost::asio::thread_pool t(3); std::vector<int> vec = {10,20,30}; for (int i = 0; i < 3; ++i) { boost::asio::post(t, [&]{ foo(vec[i]);}); } t.join(); what can i do to make my last way return the correct answer?
You are capturing i by reference for a lambda that is used asynchronously. When t.join(); is reached, i is a dangling reference. Capture it by value so it doesn't change or expire. boost::asio::post(t, [&,i]{ foo(vec[i]);});
73,126,584
73,127,017
Writing single-char vs. char const* to buffer
When writing single characters to an output stream, the purist in me wants to use single quotes (e.g.): unsigned int age{40}; std::ostringstream oss; oss << "In 2022, I am " << age << '\n'; // 1. Single quotes around \n oss << "In 2023, I will be " << age + 1u << "\n"; // 2. Minor ick--double quotes around \n Because I'm writing a single character and not an arbitrary-length message, it doesn't seem necessary to have to provide a null-terminated string literal. So I decided to measure the difference in speed. Naively, I'd expect option 1, the single-character version, to be faster (only one char, no need to handle \0). However, my test with Clang 13 on quick-bench indicates that option 2 is a hair faster. Is there an obvious reason for this? https://quick-bench.com/q/3Zcp62Yfw_LMbh608cwHeCc0Nd4 Of course, if the program is spending a lot of time writing data to a stream anyway, chances are the program needs to be rethought. But I'd like to have a reasonably correct mental model, and because the opposite happened wrt what I expected, my model needs to be revised.
As you can see in the assembly and in the libc++ source here, both << operations in the end call the same function __put_character_sequence which the compiler decided to not inline in either case. So, in the end you are passing a pointer to the single char object anyway and if there is a pointer indirection overhead it applies equally to both cases. __put_character_sequence also takes the length of the string as argument, which the compiler can easily evaluate at compile-time for "\n" as well. So there is no benefit there any way either. In the end it probably comes down to the compiler having to store the single character on the stack since without inlining it can't tell whether __put_character_sequence will modify it. (The string literal cannot be modified by the function and also would have the same identity between iterations of the loop.) If the standard library used a different approach or the compiler did inline slightly differently, the result could easily be the other way around.
73,126,697
73,128,568
Getting error outputs due to using ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); in the code
In this code below the ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); statement seems to be causing some problems. I tried with different variation like ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); or ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); For these test cases : 5 5 apple 15 schtschurowskia 6 polish 5 tryst 3 cry The expected output should be : YES NO YES NO YES But due to this line ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); I'm getting NO YES YES YES YES Note that: these results I'm getting from online judges but in reality I'm getting the output as expected but all at once after finishing all my test cases, which was unexpected. So my question is why this delay is happening and how come the online judges are giving a wrong output. #include "bits/stdc++.h" using namespace std; int main() { ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int t; cin >> t; while(t-- > 0){ int n, cnt = 0, rem = 0; cin >> n; char str[n]; scanf("%s", str); for (int i = 0; i < n; i++){ if (str[i] != 'a' && str[i] != 'e' && str[i] != 'i' && str[i] != 'o' && str[i] != 'u'){ cnt++; rem = max(cnt, rem); } else cnt = 0; } cout << (rem < 4 ? "YES" : "NO") << '\n'; } return 0; }
You're explicitly unsyncing the standard C++ streams and the standard C streams, but then mixing them in your code. Switch the scanf with cin.
73,126,760
73,127,141
Initializing distributions for use across class methods (C++)
I am trying to make a class that has a set of rng distributions as class attributes, with class methods having access to these distributions. Trying to follow the example in the documentation, I've distilled the problem to the following mwe. The code returns the errors member "A::rd" is not a type name and no instance of overloaded function "std::uniform_real_distribution<_RealType>::operator() [with _RealType=double]" matches the argument list. #include <random> #include <iostream> using namespace std; class A{ private: // Declaration of variables... // Declare random number generators and distributions random_device rd; mt19937 gen(rd()); uniform_real_distribution<> zero_five_real_dist{0,5}; public: A(){ // Initialization of variables... // Use distribution, here to print numbers for (int i; i<6; i++) cout << zero_five_real_dist(gen) << " "; cout << endl; } void print_nums(){ for (int i; i<6; i++) cout << zero_five_real_dist(gen) << " "; cout << endl; } }; int main(){ A a_obj; a_obj.print_nums(); return 0; } I've found two possible work-arounds, but I'm not sure if they're any good. The first is to just skip the use of the Mersenne twister engine, class A{ private: mt19937 gen; uniform_real_distribution<> zero_five_real_dist{0,5}; public: A(){ for (int i; i<6; i++) cout << zero_five_real_dist(gen) << " "; cout << endl; } void print_nums(){ for (int i; i<6; i++) cout << zero_five_real_dist(gen) << " "; cout << endl; } }; and the other one is to seed the rng engine in every function call. class A{ private: random_device rd; uniform_real_distribution<> zero_five_real_dist{0,5}; public: A(){ mt19937 gen(rd()); for (int i; i<6; i++) cout << zero_five_real_dist(gen) << " "; cout << endl; } void print_nums(){ mt19937 gen(rd()); for (int i; i<6; i++) cout << zero_five_real_dist(gen) << " "; cout << endl; } }; I'd greatly appreciate any input on how to make a good working implementation.
The code line: mt19937 gen(rd()); is ambiguous. I get that error message with GNU C++ v11.3: q73126760.cpp:14:17: error: 'rd' is not a type 14 | mt19937 gen(rd()); | ^~ q73126760.cpp: In constructor 'A::A()': q73126760.cpp:22:59: error: invalid use of non-static member function 'std::mt19937 A::gen(int (*)())' 22 | for (int i; i<6; i++) cout << zero_five_real_dist(gen) << " "; | ^~~ Trouble is, one of the possible interpretations is that gen could be a member function of class A, returning some mt19937 object. Your code is a new victim of the parsing rule known under the sulfurous name of C++ Most Vexing Parse: the interpretation as a function declaration takes priority. And as rd is not a proper type, the interpretation as a function declaration ultimately fails, and the parser is unable to backtrack. This can be fixed, for example, by forcing the compiler to take rd() as an initializer, using curly braces, like this: mt19937 gen{rd()};
73,126,915
73,126,965
Iterating through a 2D vector using one use case of for loop gives segmentation fault
I needed to write a simple method that calculates the highest element in a matrix data (implemented in this case using a 2D vector). Inside the method, initially, I was accessing each element in the 2D vector using the one form (the most common one) of for loop which gave a "segmentation fault". Unfortunately, I could not find a good reason that it should happen. Eventually, I resolved the issue using for loop in a different manner. However, I would still like to know the cause for the "segmentation fault" in the initial us case of for loop. I believe it is also a correct method to iterate through a 2D vector. Can someone explain the reason for this? Thanks in advance! Initial(giving the error): class customers { public: int maximumWealth(vector<vector<int>>& accounts) { int richest_customer_wealth = 0; int sum; for(int i=0;i<accounts.size();++i){ sum = 0; for(int j=0;i<accounts[i].size();++j){ sum += accounts[i][j]; } if(sum > richest_customer_wealth) richest_customer_wealth = sum; } return richest_customer_wealth; } }; After modifying the for loop: class customers{ public: int maximumWealth(vector<vector<int>>& accounts) { int richest_customer_wealth = 0; int sum; for(vector<int> row: accounts){ sum = 0; for(int val: row){ sum += val; } if(sum > richest_customer_wealth) richest_customer_wealth = sum; } return richest_customer_wealth; } };
I believe it may be because in the inner loop you have for(int j=0;i<accounts[i].size();++j) when it should be for(int j=0;j<accounts[i].size();++j){
73,127,178
73,173,302
How to force GDB to start number breakpoints at 1
How can I force GDB to start its numbering of newly added breakpoints at 1, after I have deleted all breakpoints with the delete command? I'm using this version of GDB: GNU gdb (GDB) 8.0.50.20171024-git TL;DR Rationale During complicated debug sessions, I have a separate command file that I use the source command to source back in, with the first line of that command being delete br. That does clear the breakpoints as it should. Then, in subsequent lines, I add the complicated breakpoints, but does not restart with breakpoint 1. That means that, during a the same debug session, and without exiting and restarting the whole GDB session again, GDB will continue numbering the breakpoints at the next integer after the last one that was added before, but then was deleted. Yes, I could restart the GDB session, sure, and that is a workaround, but that is suboptimal because it forces me to wait for GDB to reload the executable into core, and the executable is quite large (yes, that is indeed a problem, but is not the droids we are discussing right now). Then, I want to add, to that command file, commands to disable all breakpoints except the first one, then manually use continue to continue to the first breakpoint, and only then re-enable the subsequent breakpoints. Then once those are added in, I want to execute specifically the command (which shall be hardcoded into my wetware and never ever be changed): enable 2-20. Because then I want to discover some code, then use the disable 2-20 command (also hardcoded in my wetware) followed by the run command, and repeat ad infinitum, all without having to restart GDB. Side note: Please do not ask me to program in GDB's Python. Yes, I know how. But I don't wanna. This should be something built-into plain 'ole GDB without any extra Python coding chores/requirements. But if you do have a Python based approach, I will reluctantly listen and so too maybe even accept it as the answer.
Given your use-case described in your rationale, you're probably best off not trying to get the breakpoints assigned to specific numbers and instead use convenience vars to keep track of the breakpoint numbers. Whenever you set a breakpoint, gdb will set $bpnum to the number of the breakpoint. You can save that value to another convenience var for later use. So your script would end up with something like: break foo # the first breakpoint you always want active break bar # the first you want to enable/disable set $first_interesting = $bpnum break baz # some more interesting ones break box break bap set $last_interesting = $bpnum define ei enable $first_interesting-$last_interesting end document ei enable the interesting breakpoints end define di disable $first_interesting-$last_interesting end document di disable the interesting breakpoints end Now you just need to remember the commands ei/di in your wetware...
73,127,253
73,128,313
Does split_regex support group?
Can I setting split_regex working based on groups instead of using lookbehind? The code I'm using is as follows: string data = "xyz: 111.222: k.44.4: 12345"; vector<string> data_vec; boost::algorithm::split_regex( data_vec, data, boost::regex("(:\s*)\d")); my expected result is: xyz 111.222: k.44.4 12345
In case you are open to other solutions, one using std::regex would be: Loop searching for a :\s* separator. Keep a vector of tokens. Push back the first token and any token that starts with a digit. For tokens not starting with a digit (other than first one), add them to the last element of the container (together with, and after, the separator). Remember to treat the token after the last separator as well. [Demo] #include <cctype> // isdigit #include <fmt/ranges.h> #include <regex> #include <string> #include <vector> void add_token(std::vector<std::string>& tokens, const std::string& token, const std::string& separator) { if (not token.empty()) { if (tokens.empty() or std::isdigit(token[0])) { tokens.push_back(token); } else { tokens.back() += separator; tokens.back() += token; } } } auto split_regex(std::string data) { std::vector<std::string> tokens{}; std::regex pattern{R"(:\s*)"}; std::smatch matches{}; std::string last_separator{}; while (std::regex_search(data, matches, pattern)) { last_separator = matches[0]; add_token(tokens, matches.prefix(), last_separator); data = matches.suffix(); } add_token(tokens, data, last_separator); return tokens; } int main() { std::string data{ "xyz: 111.222: k.44.4: 12345" }; fmt::print("{}", fmt::join(split_regex(data), "\n")); } // Outputs: // // xyz // 111.222: k.44.4 // 12345
73,127,302
73,127,412
Append vector to itself?
I'm trying to cloning the vector itself, for example if the vector is [2,3] it will become [2,3,2,3]. This is my program: #include <iostream> #include <vector> using namespace std; int main() { vector<int> a; a.push_back(2); a.push_back(3); for(int i: a) { a.push_back(i); } for(int i: a) cout << i << " "; return 0; } So I'm just pushing the elements to the vector itself but the output is [2,3,2,0]. I don't understand why. Help me with this problem.
Range-for is syntactic sugar for an iterator-based for-loop, and std::vector::push_back() can invalidate iterators like the ones being used internally by the range-for: If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated. You can use std::copy() after a resize(): vector<int> a; a.push_back(2); a.push_back(3); auto size = a.size(); a.resize(size * 2); std::copy(a.begin(), a.begin() + size, a.begin() + size);
73,127,632
73,127,758
find_if is not returning the expected output
I am using find_if() to find the next higher value in a vector. It is returning the next index and not a higher value. The input vector is: vector<int> height = { 1,8,6,2,5,4,8,3,7 }; I am looking for the next highest value, starting at i=0, height[0] = 1. The code updates to set i=1, height[1] = 8. I expect to get i=7. I get i=2 instead. for (size_t i = 0; i < height.size() - 1; i++) { auto res = std::find_if((height.begin() + i + 1), height.end(), [&height, i](int x) { return height[x] >= height[i]; }); auto higher_index = std::distance(height.begin(), res); if (res != height.end() && higher_index < height.size()) { // found the next highest height // calculate new area and make i the same as highest height area = min(height[i], height[higher_index]) * (higher_index - i); maxA = max(maxA, area); i = higher_index - 1; } }
Your lambda should look like this [&height, i](int x) { return x >= height[i]; } find_if passes the value of each element of the given sequence to the predicate. Not the index of each element.
73,127,939
73,128,120
Any way to check count of template parameters at compile time?
Is there any way to check number of template parameters and compile time? I would like to do this (this is not real code): template<typename... Types> class Foo { // Enable this if count of 'Types' is 1. Types[0] Bar() { return Types[0]{}; } // Enable this otherwise. std::variant<Types> Bar() { return std::variant<Types>{}; } }; Is there any way to achieve this?
One option is to add a template parameter and then leverage constexpr if to check if the pack is empty or not like template<typename first_t, typename... rest_t> class Foo { auto Bar() { if constexpr (sizeof...(rest_t) == 0) return first_t{}; else return std::variant<first_t, rest_t...>{}; } };
73,127,942
73,128,396
Overloaded method resolution for variadic tuples displays strange results
I'm getting strange and unexpected results for this code: https://godbolt.org/z/8vs87vcKK #include <string> #include <iostream> #include <tuple> using namespace std; struct Foo { template < typename ... t_Tys > static void foo( tuple< t_Tys ... > const & ) { cerr << "foo()\n"; } template < class ... t_Tys > static void foo( tuple< string, t_Tys ... > const & _rtp ) { cout << "foo( string )\n"; } template < class ... t_Tys > static void foo( tuple< string, int, t_Tys ... > const & _rtp ) { cout << "foo( string, int ) [" << get<1>(_rtp) << "]\n"; } }; int main() { Foo::foo( make_tuple<string>( "foo" ) ); Foo::foo( make_tuple<int>( 1 ) ); Foo::foo( make_tuple( "foo", 1 ) ); Foo::foo( make_tuple<string,int>( "foo", 1 ) ); } Output is: foo() foo() foo( string ) foo( string, int ) [1] First question: I would expect that the first "foo()" would be "foo( string )", why is this not the case? Then when I change the first call to foo() to this: Foo::foo( make_tuple( "foo" ) ); https://godbolt.org/z/zh9G39z61 the output is: foo() foo() foo() foo( string, int ) [1] Question 2: Why did the change to the first call to foo() not generate a call to foo( tuple< string> const & )? Question 3: Why did the change to the first call to foo() cause the overload chosen by the third call to foo() to change? This one is really weird to me as it indicates a side effect of the first call and that just doesn't make sense to me. Thanks in advance.
The first template is using cerr, while the others are using cout. Since you used '\n' instead of endl to end the line, your output is not immediately flushed. This is reordering your output. Fixing this, the first output becomes: foo( string ) foo() foo() foo( string, int ) [1] The first foo() does indeed result in foo( string ), while the third foo() was actually foo(). The change to the first call to foo() did not cause any side effects to the third call. As for why foo( make_tuple( "foo" ) ) doesn't use the string template, that's because when you pass in a string constant to make_tuple, it returns a tuple<char const * const>.
73,128,622
73,129,801
How to run function after delay asynchronously in C++
I want to implement something like Java's TimerTask in C++. I want to use it for invoking functions sometimes, not periodic. For periodic launching it will be a good idea to implement "event loop" scheme with 2 threads, with creating tasks in the first thread and process it in the second. But I do not want to write much code. So I've written smth like this: template <typename F, typename... Args> auto timed_run(const uint64_t delay_ms, const F& function, Args... args) { const auto f = [&] { std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); function(args...); }; auto future = std::async(std::launch::async, f); return future; } But it does not work as I need because it is not asynchronous at all due to it waits at future destructor as described there. So we need to create thread by ourselves. Okay, lets do it: template <typename F, typename... Args> auto timed_run(const uint64_t delay_ms, const F& function, Args... args) { std::packaged_task<void()> task([&]() { std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); function(args...); }); auto future = task.get_future(); std::thread thread(std::move(task)); thread.detach(); return future; } In this implementation the are no locks and waits, but it simply does not run our function. It is because we can't use sleep on the detached threads. So, how can I implement what i want?
template <typename F, typename... Args> auto timed_run(const uint64_t delay_ms, F&& function, Args&&... args) { std::packaged_task<void()> task([=]() { std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); function(args...); }); auto future = task.get_future(); std::thread(std::move(task)).detach(); return future; }
73,129,254
73,129,679
Parameter pack constructor preferred over other constructor calls
Consider a constructor accepting a parameter pack, such as template<typename First, typename... Rest> consteval explicit foo(const First& first, const Rest... rest) : arrayMember{first, rest...} { } where First and Rest... all have arithmetic types, And another, different constructor that takes two arithmetic types: explicit foo(std::size_t low, std::size_t high) { /* ... */ } Imagine now that we wish to call the second constructor taking the two arithmetic types parameters: foo f(3,4); ... But this actually calls the constructor that takes a parameter pack. I am wondering whether there is a way to disambiguate the calls. For example, is there a way (through preprocessor magics or something) to call the parameter pack constructor with brace initialization ({ ... }), and to call the other constructor with direct initialization ((..., ...))? I have thought of disabling the parameter pack constructor if the passed arguments are 2, but what if I actually wanted to call it with two parameters? Minimal reproducible example: https://godbolt.org/z/5P9cEdf7v
Assuming an implementation similar to this: template <typename T, std::size_t Size> class foo { private: T _vector[Size]{}; public: using size_type = std::size_t; // .. other constructors .. explicit foo(size_type lower, size_type higher) { // (1) // ... } template <typename Stream> constexpr void print(Stream& stream) const { for (auto x : _vector) stream << x << ' '; stream << '\n'; } }; You can replace your first constructor by one that takes a const reference to an array, T const (&)[Size]: consteval explicit foo(T const (&in)[Size]) // (2) : foo(in, std::make_index_sequence<Size>{}) {} This constructor delegates the initialization of _vector to another constructor which exploits the inices trick: template <std::size_t... Is> consteval explicit foo(T const (&in)[Size], std::index_sequence<Is...>) // (3) : _vector{in[Is]...} {} With this implementation: #include <iostream> int main() { foo<int, 3> vec0(3, 4); // calls (1) vec0.print(std::cout); constexpr foo<int, 3> vec1({3, 4}); // calls (2), which calls (3) vec1.print(std::cout); constexpr foo<int, 3> vec2{{3, 4}}; // calls (2), which calls (3) vec2.print(std::cout); }
73,129,264
73,129,515
Generic way to select a map based on data type of key
I have a few disjoint maps which map unique types to strings. For example: enum class Colors {RED, GREEN}; enum class Days {MON, SUN}; std::map <Colors, std::string> map1{ {Colors::RED, "red"}, {Colors::GREEN, "green"}, }; std::map <Days, std::string> map2{ {Days::MON, "mon"}, {Days::SUN, "sun"}, }; Given a key, I want to be able to extract its value transparently from the corresponding map (there is exactly one map for a type). I considered a wrapper function like so template <typename T> auto extractValue(T k){ // Somehow use type T to switch maps and return value corresponding to k } I'm however not sure how/if this can be achieved. If this is not possible, what could be an alternate approach where I can exploit the fact that there is exactly one map per type. I'm using C++20. Edit: I can achieve this by writing overloads of extractValue for each type, but I'm looking for a more "generic" approach.
In C++17 and later, you can use if constexpr, eg: template <typename T> auto extractValue(T k){ if constexpr (std::is_same_v<T, Colors>) { return map1[k]; } else if constexpr (std::is_same_v<T, Days>) { return map2[k]; } return std::string{}; } Otherwise, you can use template specialization, eg: template <typename T> auto extractValue(T k){ return std::string{}; } template <> auto extractValue<Colors>(Colors k){ return map1[k]; } template <> auto extractValue<Days>(Days k){ return map2[k]; } Or, you could just simply overload the function, eg: auto extractValue(Colors k){ return map1[k]; } auto extractValue(Days k){ return map2[k]; }
73,129,518
73,129,793
Inconsistent implicit conversion behavior
I encountered a case where I cannot understand the implicit conversion behavior in c++. The code is the following: template <bool b, int i, unsigned... us> void foo() {} template <int i, unsigned... us> void foo() {return foo<false, i, us...>();} int main() { foo<true, -1, 0ul, 1ul, 2ul>(); // compiles with clang and gcc > 8 (gcc<=8 gives ambiguous function call) foo<true, +1, 0ul, 1ul, 2ul>(); // ambiguous function call error foo<-1, 0ul, 1ul, 3ul>(); // compiles with clang and gcc > 8 (gcc<=8 gives ambiguous function call) foo<+1, 0ul, 1ul, 3ul>(); // ambiguous function call error } For line 1 and 2 in main(), the compiler seems to implicitly convert int to unsigned only for positive integers (this is understandable but is there a rule for this?) For line 3 and 4 in main(), the compiler seems to implicitly convert int to bool only for positive integers. I cannot understand why. Background: Ideally, I want to get a similar construct to work which effectly leads to a default value for the bool template parameter. But because of the parameter pack and c++ implicit builtin conversions, this seems to be difficult.
A non-type template argument is required to be a converted constant expression of the template parameter's type. A converted constant expression specifically does not allow for narrowing conversions, which in the case of constant expression evaluation between integral types means that the conversion is not allowed if it would change the numeric value. This is specific to the converted constant expression requirement. If these were function parameter and argument, then implicit conversion of -1 to unsigned would be allowed and it also has a well-defined result, although obviously not with the same numeric value of -1. Therefore in foo<true, -1, 0ul, 1ul, 2ul>(); the template which requires unsigned in that position for -1 is indeed not viable as an overload candidate. Boolean conversions, meaning conversions from other scalar types to bool are not listed in the list of conversions allowed for a converted constant expression at all (see [expr.const]/10), which as far as I can tell should make the overload with bool in the first position non-viable for both foo<-1, 0ul, 1ul, 3ul>(); and foo<+1, 0ul, 1ul, 3ul>();. I am not sure why the compilers consider the latter ambiguous anyway. According to the resolution of CWG issue 1407 as not-a-defect, the conversion from int template argument to bool template parameter is indeed not allowed, but compilers are behaving non-conforming and seem to treat it like an integral type with range 0/1. I don't know what problem GCC <8 has. I guess it was just a bug that it considered the overload ambiguous.
73,129,742
73,130,266
Fire base Update c++ / how to detect string in URL
I want to change some Data in my realtime firebase based on the id. I want to customize my Https but it does not work. when i add + id to my URL i got a failure: QNetworkRequest newAdminRequest(QUrl("gymmanagment-a6c01-default-rtdb.europe-west1.firebasedatabase.a…" + id)) – void DatabaseHandler::AddAdmin(QString name, QString password, QString email, QString Geburtsdatum){ m_networkManager = new QNetworkAccessManager( this); QVariantMap newAdmin; newAdmin["Name"] = name; newAdmin["Password"] = password; newAdmin["Email"] = email; QJsonDocument jsonDoc = QJsonDocument::fromVariant( newAdmin ); std::string id = "-N7pPxSHoPVlyEi8e0xW"; QNetworkRequest newAdminRequest(QUrl("https://gymmanagment-a6c01-default-rtdb.europe-west1.firebasedatabase.app/Admin.json"+ id)); newAdminRequest.setHeader(QNetworkRequest::ContentTypeHeader, QString("application/json")); m_networkManager->put(newAdminRequest, jsonDoc.toJson() );}
You need to access the 'id' as if it were an 'endpoint', like this: https://gymmanagment-a6c01-default-rtdb.europe-west1.firebasedatabase.app/Admin/-N7pPxSHoPVlyEi8e0xW.json For general case, you can join each part: QString id = "-N7pPxSHoPVlyEi8e0xW"; QString base = "https://gymmanagment-a6c01-default-rtdb.europe-west1.firebasedatabase.app/Admin/"; QUrl url = base + id + ".json"; yourRequest->setUrl(url); Then, put your changes.
73,130,012
73,130,310
How do I pass a return value to another function and assign the return value to a variable within that function?
My program consist of 3 files. The clockType.h - the class function prototypes, clockTypeImp.cpp - definitions of functions, and the testing program testClockClass.cpp. I am trying to pass the return value of the first function to the next function in the code below. I think I am supposed to pass it as a reference perimeter, or a pointer*. You can see my failed attempt at assigning the return value to the variable diffSec. (What I am trying to do is convert the difference in seconds between two clocks and out put that difference as HH:MM:SS). Part of my clockTypeImp.cpp implementation file: int clockType::clockDiffseconds(clockType otherClock) { int elapsedSec; return (abs(elapsedTimeSeconds() - otherClock.elapsedTimeSeconds())); } void clockType::secondsToHHMMSS() { int diffSec = clockType::clockDiffseconds(clockType otherClock); int diffHours = diffSec/3600; int diffMinutes = (diffSec/60)%60; int diffSeconds = diffSec%60; cout << "Converted to HH:MM:SS: " << diffHours << ":" << diffMinutes << ":" << diffSeconds; } Part of my clockType.h file where clockType is coming from: class clockType { public: void remainingTimeSeconds(int& totalEndSec); // Function to convert clock to time remaining in seconds. int clockDiffseconds(clockType otherClock); // Function for finding difference in time between clocks. void secondsToHHMMSS(); // Function for converting seconds to HH:MM:SS. bool equalTime(const clockType& otherClock) const; // Function to compair the two times. private: int hr; // Variable to store the hours. int min; // Variable to store the minutes. int sec; // Variable to store the seconds. }; Here is part of my testing program. #include <iostream> #include <iomanip> #include "clockType.h" using namespace std; int main() { clockType myClock; clockType yourClock; int hours; int minutes; int seconds; int elapsedSec; int totalEndSec; cout << endl << "myClock Time is not set:\n"; myClock.printTime(); cout << endl << "myClock Time is set:\n"; myClock.setTime(9, 3, 30); myClock.printTime(); cout << endl; cout << endl << "yourClock Time is not set:\n"; yourClock.printTime(); cout << endl << "yourClock Time is set:\n"; yourClock.setTime(5, 45, 16); yourClock.printTime(); cout << endl << endl; if (myClock.equalTime(yourClock)) { cout << "Both times are equal." << endl; } else { cout << "The two times are not equal." << endl; } cout << endl << "Set the time for myClock\nEnter the hours, minutes, and seconds:\n"; yourClock.remainingTimeSeconds(totalEndSec); cout << "\x1B[32m-->\033[0m" << " The total remaining seconds of \x1B[32myourClock\033[0m is: " << totalEndSec << endl; myClock.remainingTimeSeconds(totalEndSec); cout << "\x1B[33m-->\033[0m" << " The total remaining seconds of \x1B[33mmyClock\033[0m is: " << totalEndSec << endl; cout << endl; cout << "\x1B[34m-->\033[0m" << " The difference in seconds between the \x1B[34mtwo clocks\033[0m is: " << myClock.clockDiffseconds(yourClock) << endl; Let me know if you need to see the full code of the file(s).
clockDiffseconds() is a non-static method that acts on this, calculating the difference in seconds between this and another clock otherClock. That is fine. But secondsToHHMMSS() has no concept of otherClock. It is also a non-static method that acts only on this. So, for secondsToHHMMSS() to be meaningful, you have a few choices: re-think what secondsToHHMMSS() actually means to you. The way you have written it, it should just print the current seconds of this as-is. In which case, use the value returned by clockDiffseconds() to constructs a new clockType object whose elapsedTimeSeconds() returns just that value, and then call secondsToHHMMSS() on that new clockType object, eg: class clockType { public: ... clockType clockDiff(clockType otherClock) const; void secondsToHHMMSS() const; ... }; clockType clockType::clockDiff(clockType otherClock) const { int elaspedSec = abs(elapsedTimeSeconds() - otherClock.elapsedTimeSeconds()); return clockType(elaspedSec); // add a constructor to clockType that stores elaspedSec in such // a way that its elapsedTimeSeconds() can then return it... } void clockType::secondsToHHMMSS() const { int elapsedSec = elapsedTimeSeconds(); int hours = elapsedSec/3600; int minutes = (elapsedSec/60)%60; int seconds = elapsedSec%60; cout << "Converted to HH:MM:SS: " << hours << ":" << minutes << ":" << seconds; } clockType myClock, yourClock, elapsed; ... elapsed = myClock.clockDiff(yourClock); elapsed.secondsToHHMMSS(); ... Otherwise, if you really want secondsToHHMMSS() to express the difference in seconds between two clocks, then you will have to pass in the otherClock as a parameter to secondsToHHMMSS(), just like you already do with clockDiffseconds(), eg: class clockType { public: ... int clockDiffseconds(clockType otherClock) const; void secondsToHHMMSS(clockType otherClock) const; ... }; int clockType::clockDiffseconds(clockType otherClock) const { return abs(elapsedTimeSeconds() - otherClock.elapsedTimeSeconds()); } void clockType::secondsToHHMMSS(clockType otherClock) const { int diffSec = clockDiffseconds(otherClock); int diffHours = diffSec/3600; int diffMinutes = (diffSec/60)%60; int diffSeconds = diffSec%60; cout << "Converted to HH:MM:SS: " << diffHours << ":" << diffMinutes << ":" << diffSeconds; } clockType myClock, yourClock; ... myClock.secondsToHHMMSS(yourClock); ... Otherwise, consider changing secondsToHHMMSS() to be a static method instead, and then pass in the desired seconds as a parameter, such as from an earlier call to clockDiffseconds(), eg: class clockType { public: ... static void secondsToHHMMSS(int seconds); ... }; void clockType::secondsToHHMMSS(int seconds) const { int hours = seconds/3600; int minutes = (seconds/60)%60; seconds = seconds%60; cout << "Converted to HH:MM:SS: " << hours << ":" << minutes << ":" << seconds; } clockType myClock, yourClock; ... int diffSec = myClock.clockDiffseconds(yourClock); clockType::secondsToHHMMSS(diffSec); ...
73,130,340
73,130,928
How to not break bindings in qml?
I currently have an image which becomes visible or not depending on some steps of a process. The qml code for that image is the following : Image { id : cameraDisplay visible : mainViewModel.getCurrentSegmentIsCameraDisplayed anchors.centerIn : parent source: "Images/Todo.png" } I also have a button, which the user can press to display that image or not : Button { Layout.fillWidth: true Layout.fillHeight: true buttonText : "CAMERA" onClicked: {cameraDisplay.visible = !cameraDisplay.visible;} } In the c++, the binding looks like this : Q_PROPERTY(bool getCurrentSegmentIsCameraDisplayed READ getCurrentSegmentIsCameraDisplayed NOTIFY segmentChanged) the idea is that every time the current step of the process changes in my program, a notification is sent. That notification is then sent to the QML, which then gets the backend value to know if the camera should display or not that image. I also have a button, which allows the user to toggle on or off the visibility of that image. The problem is that once that button is clicked, I lose the Q_PROPERTY binding, which means that once I go to the next segment, the notifications sent to the qml won't change the visibility of the image. So basically, what I would want would be the following situation : The segment changes, a notification is sent to the qml, and the visiblity of the image is updated automatically. The user presses the button, which toggles the visibility of that image. The segment changes again, a notification is sent to the qml, and the visibility of that image is again updated according to the backend. Currently, step 3 doesn't work. What should I change to make it work? thanks
You can change your binding in C++ to emit a signal when a change occurs, like this: Q_PROPERTY(bool getCurrentSegmentIsCameraDisplayed READ getCurrentSegmentIsCameraDisplayed WRITE setCurrentSegment NOTIFY segmentChanged) In your class.h, class MyClass : public QObject { Q_OBJECT bool _segment; public: const bool &getCurrentSegmentIsCameraDisplayed() const; public slots: void setCurrentSegment(const bool &newSegment); signals: void segmentChanged(const bool &segment); }; In your class.cpp, void MyClass::setCurrentSegment(const bool &newSegment) { if (_segment == newSegment){ return; }else{ _segment = newSegment; emit segmentChanged(_segment); } } const bool &MyClass::getCurrentSegmentIsCameraDisplayed() const { return _segment; } Now in C++ you can change the process value any way you want. On the QML side, when you need to change the property, just use the SLOT setCurrentSegment passing its new state: Image { id : cameraDisplay visible: mainViewModel.getCurrentSegmentIsCameraDisplayed anchors.centerIn : parent source: "https://www.cleverfiles.com/howto/wp-content/uploads/2018/03/minion.jpg" } Button { text : "CAMERA" onClicked: { mainViewModel.setCurrentSegment(!cameraDisplay.visible) } } The binding is maintained regardless of where the change takes place.
73,130,478
73,130,942
Variadic template: inline pattern expansion
C++ variadic templates can use patterns where you can repeat blocks surrounding the variadic argument, like so: template<typename... Args> struct MyStruct : seq<pair<Other, Args>...> MyStruct<X, Y> // expands to seq<pair<Other, X>, pair<Other, Y>> However, as far as I can tell, all these pattern expansions require (and retain) an enclosing block. I'm looking to expand a pattern inline, like this: template<typename... Args> struct MyStruct : seq<???Other, Args???...> MyStruct<X, Y> // expands to seq<Other, X, Other, Y> Is there a way to achieve this effect?
If you fancy doing meta-programming yourself, you can accomplish the behaviour with four utility overloads. Like another answer pointed out, the key is concatenating seq types, so our utilities will do just that. The important thing to understand is that meta-programming is primarily functional in nature, so the tools will be recursion and pattern matching (all during overload resolution). Here are the overloads: namespace detail { auto seq_concat() -> seq<>&; template<typename... Args> auto seq_concat(seq<Args...>&) -> seq<Args...>&; template<typename... Args, typename... Brgs> auto seq_concat(seq<Args...>&, seq<Brgs...>&) -> seq<Args..., Brgs...>&; template<class Seq, class... Seqs> auto seq_concat(Seq& s, Seqs&... ss) -> decltype(seq_concat(s, seq_concat(ss...))); } The first three are our "base case". When concatenating zero to two seqs, we lay out explicitly what type we should get, while the final overload is our general case. To concatenate a list of three or more "seq-like" types, is to concentrate the elements in the list tail, then take that result and concatenate it with the list head. Now we can write the utility you need, because to create a seq<Other, A, Other, B> we may just concatenate seq<Other, A> with seq<Other, B>, and in if we need more types, we can do pack expansion on seq<Other, Args>... and concatenate all of those. struct Other; template<typename... Args> using seq_interleave_with_other = typename std::remove_reference<decltype(detail::seq_concat(std::declval<seq<Other, Args>&>()...))>::type; We create a pattern std::declval<seq<Other, Args>&>()... to "give us references to objects" we can use in an unevaluated context, then invoke detail::seq_concat(...) on the pattern. The return type is (almost) what we need, because our utilities added references for simplicity of implementing them. A quick trip through std::remove_reference and we are done. To use it, just write: template<typename... Args> struct MyStruct : seq_interleave_with_other<Args...> {}; Here's everything in a live example to play with.
73,131,354
73,131,439
Redis-protobuf: Err type mismatch seen with protos having nested messages
When there are more than one proto files with nested messages loaded by libredis-protobuf.so, unable to set any fields of the second proto message. Both proto files are proto3 version. 127.0.0.1:6379> PB.SCHEMA Msg "message Msg {\n int32 i = 1;\n .SubMsg sub = 2;\n repeated int32 arr = 3;\n}\n" 127.0.0.1:6379> PB.SET key Msg '{"i" : 1, "sub" : {"s" : "string", "i" : 2}, "arr" : [1, 2, 3]}' (integer) 1 127.0.0.1:6379> PB.GET key --FORMAT JSON Msg "{\"i\":1,\"sub\":{\"s\":\"string\",\"i\":2},\"arr\":[1,2,3]}" 127.0.0.1:6379> 127.0.0.1:6379> PB.SCHEMA Rsg2 "message Rsg2 {\n int32 i = 1;\n .SubRsg2 sub = 2;\n repeated int32 arr = 3;\n}\n" 127.0.0.1:6379> 127.0.0.1:6379> PB.SET key Rsg2 '{"i" : 1, "sub" : {"s" : "string", "i" : 2}, "arr" : [10, 20, 30]}' (error) ERR type mismatch 127.0.0.1:6379> 127.0.0.1:6379> PB.SET key Rsg2 /i 10 (error) ERR type missmatch 127.0.0.1:6379> PB.SET key Rsg2 /arr/0 2 (error) ERR type missmatch 127.0.0.1:6379> Same issue seen when using protobuf-3.8.0-map-reflection.tar.gz and latest protobuf. Any help/info appreciated.
Because you've already set key as an object of Msg type. When you try to set key to an object of another type, e.g. Rsg2, it returns error reply: type mismatch. It behaviors like trying to set a key of which the type is HASH. You need to delete the key, and then you can set it to an object of another type. Or just setting another key. PB.SET another-key Rsg2 '{"i" : 1, "sub" : {"s" : "string", "i" : 2}, "arr" : [10, 20, 30]}' B.T.W. there's a plan to set (key, value) pair without checking the type, i.e. an option: --FORCE.
73,131,430
73,132,491
P/Invoke (DLLImport) Different Function Signature
According to the documentation, when trying to call unmanaged code in my managed code, it should has the exact same function signature as the unmanaged code. I tried putting in a different function signature that I know should not have worked. Original: int Foo(LibraryDefinedString str, _Outptr_ LibraryDefinedHandle * ptr) Adaptation (after calling DllImport): Uint32 Foo(byte[] str, IntPtr ptr) No exceptions were thrown. Even after I changed the parameters (putting floats or another user-defined type), it still did not throw any exception. Have not tested whether the function in the Dll actually gets called, but my main question : Is there no warning or error when putting different function signatures from the unmanaged code?
No, there is no warning. How could there be? There is no reflection on the native side, so there is no way for the PInvoke marshaller to validate if the managed side is correct. Either the code works, or the code has undefined behavior that may or may not fail. In any case, your "wrong signature" may or may not be wrong. int and UInt32 have the same size. LibraryDefinedHandle* and IntPtr have the same size. What we don't know is what LibraryDefinedString is actually defined as and whether byte[] is compatible with it or not. If the signature is mismatched, there are no errors reported on the managed side, but you may get crashes or wrong behavior on the native side.
73,131,471
73,131,528
Does header initialization break RAII?
Consider the following C++ header: #include "OtherThing.h" class Thing { public: Thing(); //ctor private: OtherThing my_var_{}; }; Is the private var my_var_ still managed according to RAII, or does its lifetime exceed the scope of Thing in any way? I searched for a clear answer for a good while, but either formed my question poorly or didn't know how to read what was given.
Is the private var my_var_ still managed according to RAII, or does its lifetime exceed the scope of Thing in any way? The data member my_var_ is a non-static data member and is associated with a particular instance of class Thing. More importantly, it's lifetime can never exceed the lifetime of the associated Thing object. When a given Thing object goes out of scope, it's data members are also destroyed. Basically, a Thing object includes its data members so logically when the Thing object is destroyed the data members will also be destroyed. Also note that technically the lifetime of an object with a constructor doesn't begin until the execution of the constructor has completed. So the lifetime of the class members is slightly longer than lifetime of the containing object as pointer out by @M.M
73,131,627
73,133,527
Forward and reverse conversions between vector<Eigen::Vector3f> and Eigen::Matrix3Xf
How to convert vector<Eigen::Vector3f> to Eigen::Matrix3Xf ? and inverse operation ? #include <Eigen/Eigen> #include <iostream> #include <vector> using namespace std; vector<Eigen::Vector3f> x{{1.0, 2.0, 3.0}, {1.0, 2.0, 3.0}, {1.0, 2.0, 3.0}}; Eigen::Matrix3Xf y; y = x? vector<Eigen::Vector3f> x; Eigen::Matrix3Xf y{{1.0, 2.0, 3.0}, {1.0, 2.0, 3.0}, {1.0, 2.0, 3.0}}; x = y?
Assignment vector to Matrix, use a Map (you need to make sure that x.size()>0): // Works as constructor or assignment: Eigen::Matrix3Xf y = Eigen::Matrix3Xf::Map(x[0].data(), 3, x.size()); The other way around, you can use the iterator interface of Eigen: // Constructor: vector<Eigen::Vector3f> x(y.colwise().begin(), y.colwise().end()); // Assignment: x.assign(y.colwise().begin(), y.colwise().end()); Usually, there is no need to copy between both representations, you can use Eigen::Map directly in Eigen expressions or pass Eigen iterators directly to std algorithms.
73,131,649
73,131,670
C++ class overloaded operator `()` called in template is not able to change member variable's value
I met a problem when working with templates and overloaded operators in C++. I want to create a class Foo with an overloaded operator (), and I also want to change the value of a private member variable bar_ of class Foo inside the overloaded (), and keep that value for later use. I have to finish this with a template: I will pass an object of the Foo class into the template, and then call it with the object's name (i.e. run the overloaded () operator) inside the template. Later, I will call the GetBar public member function on the object to get the value of bar_. In the following minimal reproducible example, the value of the private member variable bar_ is changed to 2 in the overloaded () operator, and is called in the template. However, when I tried to get the value of bar_ later outside the template using the GetBar public member function, it gives me the value 1, which is the initial value given to the variable bar_ in the constructor. Thus, the value change in the () operator doesn't work. Does anyone have an idea what is happening here? I am not sure why the value change is not saved in the variable. #include <iostream> #include <unordered_map> using std::unordered_map; using std::cout; using std::endl; using std::unordered_map; class Foo { public: Foo() : bar_(1) {} void operator()() { bar_ = 2; std::cout << "print in the operator: bar_ = " << bar_ << std::endl; return; } size_t GetBar() { return bar_; } private: int bar_; }; template <typename T> int NodeWalk(T action) { action(); return 0; } int main() { Foo obj; NodeWalk(obj); cout << "print out the operator: bar_ = " << obj.GetBar() << endl; return 0; } Output: print in the operator: bar_ = 2 print outside the operator: bar_ = 1
Your function int NodeWalk(T action) takes the parameter by value, which means that the first print from your operator()() is called from a copy, which did alter the value of bar_. But once the function ends, the copy is destroyed. The original object declared in main() is unaltered, which is why you see the original value when you try to print again. If you want the original to be altered, pass the parameter by reference, like this: int NodeWalk(T& action).
73,131,716
73,131,820
Using private member variable as private function parameter
class C { public: void clearWithParam() { clearImage(image, size); } void clearWithoutParam() { clearImage(); } private: unsigned char* image; size_t size; void clearImage(unsigned char* image, size_t& size) { for(int i=0; i<size; i++) { image[i] = 0; } } void clearImage() { for(int i=0; i<this->size; i++) { this->image[i] = 0; } } } I found there are two ways of implementing private methods. Two clearImage()s here do exactly the same thing. However the first one takes private members image and size as its parameters, and the second access the private member directly. Which one is more preferred?
By the rules that govern scope, the function args are given preference over the members of the same name. Since the instance remains accessible, you can still access the member variables via things like this->image. Some people prefer to try and avoid such ambiguity and have established a fairly popular (to the point of it being adopted into c++ code quality requirements in some places) naming convention of having all members begin with a m_ prefix. Great time savings compared to typing this-> and reading it too. When code is clear yet more fits on a screen at once, it tends to reduce scrolling required for review too. Furthermore, if a function needs nothing from the instance, consider adding the static modifier.
73,131,777
73,146,722
Is it possible to use ActiveX controls in an SDI application (as opposed to a dialog-based application)?
I'm new to MFC and ActiveX. I'm trying to use a 3rd party ActiveX control in my MFC application. I successfully did it using a dialog-based MFC Application, but it doesn't work if I select 'Single document' when creating a new MFC project(solution) in Visual Studio. 1. How can I use a 3rd-party ActiveX control if I want to create a 'single/multiple document' MFC application? 2. What is the idiomatic way to use 3rd-party ActiveX control with C++? (it's ok even if it's not MFC) I really appreciate any help.
The easiest way to integrate/support controls (and activeX controls) in your MFC SDI application, is to derive your view class from CFormView. That will allow you to add Win32 and ActiveX controls to your form window, similar to how you did it with a dialog-based application. When you create a new MFC SDI application, ensure the "ActiveX Controls" checkbox is checked in the Advanced Features section of the wizard. Then in the "Generated Classes" section change the base class for your view class to CFormView. This will give you a dialog resource (for your view), which you can drag/drop Win32 or ActiveX controls onto. Sincerely,
73,132,051
73,132,107
C++ Use vector rvalue as an argument
Consider the code snippet below: void PrintLines(vector<string>& lines){} vector<string> lines = {"Images", "Transcriptions"}; PrintLines(lines); Is there a possibility to pass the lines values directly, without initializing the "lines" variable? Like this: PrintLines({"Images", "Transcriptions"});
First things first, you've not specified the return type of the function when defining it. Is there a possibility to pass the lines values directly, without initializing the "lines" variable? Yes, you can do that by making the parameter lines to be a const lvalue reference to std::vector so that it can bind to rvalue as shown below: // vvvvv added low level const here void PrintLines(const std::vector<std::string>& lines) ^^^^ // added void as return type here { for(const std::string&elem: lines) { std::cout<<elem<<std::endl; } } int main() { PrintLines({"Images", "Transcriptions"});//calls PrintLines return 0; } Demo
73,132,267
73,132,313
How to import library in CMAKE download by vcpkg?
I am trying to import a library that i installed using vcpkg (vcpkg install azure-storage-blobs-cpp) In my c++ file I am trying to import azure/storage/blobs.hpp In my vcpkg directory, i have the following file ./installed/x64-osx/include/azure/storage/blobs.hpp ./packages/azure-storage-blobs-cpp_x64-osx/include/azure/storage/blobs.hpp vcpkg install azure-storage-blobs-cpp returns azure-storage-blobs-cpp provides CMake targets: # this is heuristically generated, and may not be correct find_package(azure-storage-blobs-cpp CONFIG REQUIRED) target_link_libraries(main PRIVATE Azure::azure-storage-blobs) Here is my cpp file #include <iostream> #include <azure/storage/blobs.hpp> int main() { std::cout<<"Hello CMake!"<<std::endl; return 0; } Here is my CMAKE file cmake_minimum_required(VERSION 3.9.1) project(CMakeHello) set(CMAKE_CXX_STANDARD 14) find_package(azure-storage-blobs-cpp CONFIG REQUIRED) target_link_libraries(main PRIVATE Azure::azure-storage-blobs) add_executable(cmake_hello azuretest.cpp) but i am reaching CMake Error at CMakeLists.txt:7 (find_package): Could not find a package configuration file provided by "azure-storage-blobs-cpp" with any of the following names: azure-storage-blobs-cppConfig.cmake azure-storage-blobs-cpp-config.cmake Add the installation prefix of "azure-storage-blobs-cpp" to CMAKE_PREFIX_PATH or set "azure-storage-blobs-cpp_DIR" to a directory containing one of the above files. If "azure-storage-blobs-cpp" provides a separate development package or SDK, be sure it has been installed. after cmake CMakeLists.txt How do I import azure/storage/blobs.hpp? This is in mac environment
You need to use: -DCMAKE_TOOLCHAIN_FILE=[path to vcpkg]/scripts/buildsystems/vcpkg.cmake while configuring your cmake. You can see full guide here. So you need to first correct your cmake as follows: cmake_minimum_required(VERSION 3.9.1) project(CMakeHello) set(CMAKE_CXX_STANDARD 14) find_package(azure-storage-blobs-cpp CONFIG REQUIRED) add_executable(cmake_hello azuretest.cpp) target_link_libraries(cmake_hello PRIVATE Azure::azure-storage-blobs) then run following commands in your source directory: cmake -B ./build -S . -DCMAKE_TOOLCHAIN_FILE=[path_to_vcpkg]/scripts/buildsystems/vcpkg.cmake cmake --build ./build remember to replace [path_to_vcpkg] with real path.
73,132,597
73,133,364
std::sample() with integer range
How can I pick multiple values randomly in any given integer range? With std::sample(), one possible implementation would be: void Sample( int first, int last, std::vector<int> *out, std::size_t n, std::mt19937 *g) { std::vector<int> in{}; for (int i = first; i < last; ++i) { in.emplace_back(i); } std::sample(in.begin(), in.end(), std::back_inserter(*out), n, *g); } But I'm hesitating because creating in vector seems redundant and impractical, especially when first is 0 and last is very big number. Is there any public implementation or library for this requirement? e.g.: sample(int first, int last, ...) or, ranges::sample(int n, ...)
In C++20 you can sample on iota_view #include <ranges> #include <vector> #include <algorithm> #include <random> void Sample( int first, int last, std::vector<int> *out, std::size_t n, std::mt19937 *g) { std::ranges::sample( std::views::iota(first, last), std::back_inserter(*out), n, *g); } Demo Note that the above does not work in libstdc++ because ranges::sample incorrectly uses the std::sample's implementation. Since iota_view's iterator only satisfies Cpp17InputIterator, std::sample requires that the output range must be a random access iterator, which is not the case for back_inserter_iterator. The workaround is to pre-resize the vector. void Sample( int first, int last, std::vector<int> *out, std::size_t n, std::mt19937 *g) { out->resize(n); std::ranges::sample( std::views::iota(first, last), out->begin(), n, *g); } which works in both libstdc++ and MSVC-STL.
73,133,226
73,133,401
This print function cannot output the value in the deque
The result of the current execution of this program does not display the result. I want to display the values in the even deque and odd deque through the print function. During the debugging process, I found that the value in the deque already exists, but the print function will end in the middle. #include <list> #include <deque> void print(std::deque<int>::iterator beg, std::deque<int>::iterator end); int main() { std::list<int> lint{1, 2, 3, 4, 5, 6, 7, 8, 9}; std::list<int>::iterator itor; std::deque<int> dint1, dint2; itor = lint.begin(); for (; itor != lint.end(); itor++) { if (*itor % 2 == 0) { dint2.push_back(*itor); } else dint1.push_back(*itor); } std::deque<int>::iterator itorde1; std::deque<int>::iterator itorde2; itorde1 = dint1.begin(); itorde2 = dint1.end(); std::deque<int>::iterator itorde3; std::deque<int>::iterator itorde4; itorde3 = dint2.begin(); itorde4 = dint2.end(); print(itorde1, itorde2); print(itorde3, itorde4); } void print(std::deque<int>::iterator beg, std::deque<int>::iterator end){ while (beg == end) { std::cout<< *beg; beg++; } } ```
You have an error in the print function, the condition should be beg != end. Here is the function: void print(std::deque<int>::iterator beg, std::deque<int>::iterator end){ while (beg != end) { std::cout << *beg; beg++; } std::cout << "\n"; }
73,133,294
73,133,313
What is the difference between deque.at(0) vs deque[0]
So i have this queue deque<int> deq1(2,10); I Have accessed the element using 2 way and both of them return the same value cout<<deq1[0]; cout<<deq1.at(0); why did them make a special function to do the same thing or is one way better than the other?
The only difference is that the function at throw an exception if the index is out of range while the operator[] doesn't make any check. You can see the documentation here https://en.cppreference.com/w/cpp/container/deque/at https://en.cppreference.com/w/cpp/container/deque/operator_at
73,134,196
73,134,792
Hidden friend to_json function unexpectedly resolves for shared_ptr
The code below (Goldbolt) compiles and runs (on both gcc and clang) and does what I would hope. But I'm surprised! I expected to have to use an adl_serializer specialisation (as opposed to the hidden friend here) for it to be able to find the to_json/from_json functions, as the Example class is hidden inside a std::shared_ptr. So the question is, is this expected (and why?), or a bug in the compilers that might break my code when it gets fixed. #include <memory> #include <nlohmann/json.hpp> struct Example { int a; int b; Example(int a, int b) : a(a), b(b){}; Example(Example&&) = delete; Example& operator=(Example&&) = delete; Example(Example&) = delete; Example& operator=(Example&) = delete; friend void to_json(nlohmann::json& j, const std::shared_ptr<Example>& p) { j = {{"a", p->a}, {"b", p->b}}; } friend void from_json(const nlohmann::json& j, std::shared_ptr<Example>& p) { p = std::make_shared<Example>(j.at("a").get<int>(), j.at("b").get<int>()); } }; int main() { auto j = R"({ "a" : 1, "b" : 2 })"_json; auto c = j.get<std::shared_ptr<Example>>(); auto j2 = nlohmann::json(c); }
A friend function definition not declared elsewhere is declared in the same namespace as the class it is defined in. There are two reasons your to_json and from_json are found. The first, and simplest reason is that Example is in the global namespace, so lookup will reach there if it doesn't find a match elsewhere. The second reason is that adl looks at the namespace that Example is in. For arguments whose type is a class template specialization, in addition to the class rules, the following types are examined and their associated classes and namespaces are added to the set a. The types of all template arguments provided for type template parameters (skipping non-type template parameters and skipping template template parameters) (from cppreference)
73,134,275
73,134,425
Is there a clean way to make declvals for types with no default constructors?
consider this example: template<typename T> concept Iteratable = requires(T n) { n.begin(); n.end(); }; namespace detail { template<Iteratable T> using subtype = std::decay_t<decltype(*(std::declval<T>().begin()))>; template<Iteratable T> constexpr auto deepest_subtype_recursive() { if constexpr (Iteratable<subtype<T>>) { return detail::deepest_subtype_recursive<subtype<T>>(); } else { return subtype<T>{}; } } } template<Iteratable T> using deepest_subtype = decltype(detail::deepest_subtype_recursive<T>()); A recursive function that calls itself with the subtype, until the type in question is no longer iteratable, then that type is returned. What this enables, is to find the deepest container type at compile time. So e.g. vector<list<deque<int>>> becomes int: int main() { using container_type = std::vector<std::list<std::deque<int>>>; using deepest = deepest_subtype<container_type>; static_assert(std::is_same_v<deepest, int>); } using this way of return the value, and finding out the type with decltype is something I do very often, as I can write code that has more room to breathe and doesn't rely on insanley nested std::conditional_ts. this example breaks, once I apply it on a class that doesn't have a default constructor: struct foo { foo(int) {} }; int main() { using container_type = std::vector<std::list<std::deque<foo>>>; using deepest = deepest_subtype<container_type>; static_assert(std::is_same_v<deepest, foo>); } error C2512: 'foo': no appropriate default constructor available on the line where it says return subtype<T>{};. I also can't say return std::declval<subtype<T>>(); as that will give the error error C2338: static_assert failed: 'Calling declval is ill-formed, see N4892 [declval]/2.' To fix this I had the following idea: Skip the constructor by declaring a pointer, and immediately derefence it. So basically making my own declval: template<typename T> constexpr auto declval() { using pointer = T*; return *(pointer{}); } namespace detail { template<Iteratable T> using subtype = std::decay_t<decltype(*(std::declval<T>().begin()))>; template<Iteratable T> constexpr auto deepest_subtype_recursive() { if constexpr (Iteratable<subtype<T>>) { return detail::deepest_subtype_recursive<subtype<T>>(); } else { return declval<subtype<T>>(); } } } this works, but it doesn't seem like a very clean solution to me. Is there a clean way to declval? like maybe there is a utility like that already, or a utility that fully constructs a passed object. Or am I supposed to abandon returning values and rather make the logic with only types, therefore using statements?
You can return std::type_identity<T>{} (which is always default-constructible) and use decltype()::type to get the wrapped type. namespace detail { template<Iteratable T> using subtype = std::decay_t<decltype(*(std::declval<T>().begin()))>; template<Iteratable T> constexpr auto deepest_subtype_recursive() { if constexpr (Iteratable<subtype<T>>) { return detail::deepest_subtype_recursive<subtype<T>>(); } else { return std::type_identity<subtype<T>>{}; // here } } } template<Iteratable T> using deepest_subtype = typename decltype( detail::deepest_subtype_recursive<T>())::type; It's worth noting that you don't have to make your own wheels, the standard already provides something like Iteratable and subtypes, namely ranges::range and ranges::range_value_t.
73,134,485
73,134,534
In the following code, does pop() actually removes the item from the array 'num' or the item still exists inside the 'num'?
Does pop function really removes the item from the array, it just changes the pointing index? int STACK::pop() { int temp; if(isEmpty()) return -9999; temp=num[top]; --top; return temp; }
No, the element isn't removed from the array. It isn't possible to add or remove elements of an array. Arrays have constant number of elements through their lifetime.
73,134,544
73,165,866
Qt Creator Clang Code Model can't find included header in included header
My problem is as follow: The clang code model from Qt Creator is unable to find the first header included in the header file of a cpp file. CPP-File: Header file of that cpp-file: As you can see, the code model has no issues finding QDialog in the header file, but has so in the cpp file. I have the same issue in other files too. The project compiles without problems too. I already deleted the cache files in my build folder and reindexed all again. I can't find the log files of clang tho.
Disabling unity build fixed it.
73,134,842
73,134,921
How can I extend or change the behaviour of c++ standard library objects
Let's say I want to change the default way the std::bitset prints out its bit. The normal way is: #include <iostream> #include <bitset> int main() { std::cout << "size of int is: " << (sizeof (int)) << std::endl; std::bitset<32> bits = 0xFFFF0000; std::cout << "Original\n" << bits << std::endl; return 0; } Which rightfully outputs (assuming 32 bit processor): size of int is: 4 Original 11111111111111110000000000000000 Now I want it to print the bits with a space between each byte: e.g. 11111111 11111111 00000000 00000000 or a hypen between each byte: 11111111-11111111-00000000-00000000 I know that a solution is to I make my own function to print bits. But I want to know how can I extend or add more functionality and options to a standard library object.
I want to know how can I extend or add more functionality and options to a standard library object. Don't. At least not directly. In general you better do not overload operators for types you do not own. In this case there is already an std::ostreams << operator. Rather write your own custom type that manages how to print a std::bitset. #include <iostream> #include <bitset> template<size_t N> struct pretty_print_bitset { pretty_print_bitset(std::bitset<N>& ref,char sep) : ref(ref),sep(sep) {} // constructor for CTAD std::bitset<N>& ref; char sep; }; template <size_t N> std::ostream& operator<<(std::ostream& out,const pretty_print_bitset<N>& ppb){ for (int i=0;i<N;++i){ out << ppb.ref[i]; if ((i+1)%8 ==0 && i !=N-1) out << ppb.sep; } return out; } int main() { std::bitset<32> b; std::cout << pretty_print_bitset{b,'-'}; } Output: 00000000-00000000-00000000-00000000
73,135,323
73,138,604
Should I call `delete` on object allocated using polymorphic allocator
Does polymorphic allocator (I personally use boost and C++17, but guess that it's the same for stl and C++20) in it's destructor automatically destructs objects allocated inside it's memory resource, or should delete for each object be called manually, like if I'm using default stl std::allocator (where not calling delete and then destructing object is an undefined behaviour)?
A polymorphic allocator is a cheaply copyable object and doesn't own objects. What you might be confusing it with is a memory_resource, which has capacity to store objects. Still, it doesn't own those, because it cannot even know the type(s) of object(s) stored in its capacity. On the other hand, there are container types that use an allocator to allocate storage for their objects. The container does own the objects, and will destruct them and deallocate from the same (or rather, equivalent) allocator. In short, you will not be allocating from an allocator, your allocator-aware container will. And it will not call delete, but rather the expectable allocator.deallocate() or allocator.delete_object() depending on how the allocation was made. Example 1: Allocator-Aware Container Because an example speaks a thousand words: Live On Compiler Explorer #include <iostream> #include <memory_resource> #include <vector> struct X { X() { std::cout << __PRETTY_FUNCTION__ << "\n"; } ~X() { std::cout << __PRETTY_FUNCTION__ << "\n"; } }; int main() { std::pmr::vector<X> v; v.reserve(3); // watch v reallocate if you remove this line v.emplace_back(); v.emplace_back(); v.emplace_back(); } // v destructs and deallocates automically Prints: X::X() X::X() X::X() X::~X() X::~X() X::~X() I'll leave it as an exercise to see whether your standard library implementation changes behaviour if you remove the call to reserve(). Example 2: Raw allocator use It's pretty clear that the allocator interface is not for direct consumption: Live On Compiler Explorer #include <iostream> #include <memory_resource> #include <vector> struct X { X() { std::cout << __PRETTY_FUNCTION__ << "\n"; } ~X() { std::cout << __PRETTY_FUNCTION__ << "\n"; } }; int main() { std::pmr::monotonic_buffer_resource mem(1024); std::pmr::polymorphic_allocator<X> alloc(&mem); { auto x1 = alloc.new_object<X>(); auto x2 = alloc.new_object<X>(); auto x3 = alloc.new_object<X>(); // cannot use `operator delete`: // delete x1; // Undefined Behaviour // need to manually delete the objects we own through the allocator alloc.delete_object(x3); alloc.delete_object(x2); alloc.delete_object(x1); } { // c++17 interface auto x1 = alloc.allocate(sizeof(X)); alloc.construct(x1); auto x2 = alloc.allocate(sizeof(X)); alloc.construct(x2); auto x3 = alloc.allocate(sizeof(X)); alloc.construct(x3); // cannot use `operator delete`: // delete x1; // Undefined Behaviour // need to manually delete the objects we own through the allocator alloc.destroy(x3); alloc.deallocate(x3, sizeof(X)); alloc.destroy(x2); alloc.deallocate(x2, sizeof(X)); alloc.destroy(x1); alloc.deallocate(x1, sizeof(X)); } } Prints X::X() X::X() X::X() X::~X() X::~X() X::~X() X::X() X::X() X::X() X::~X() X::~X() X::~X()
73,135,493
73,135,636
QT C++ how to append text on last lıne and keep old lınes?
Instead of overwriting the new text, I want to preserve the existing content and add it to the new line. I need make a simple log for login. But When I try save to txt file Is overwriting on file. But when I try it, It just overwriting on file. How can I add to new line when new log is coming? Here is my login function void loginpage::on_lgnBtn_clicked() { login = ui -> lgnUname -> text(); password = ui -> lgnPass -> text(); QString passwordhash = passwordHash(password.toUtf8()); qDebug() << passwordhash; if (login == "admin" && passwordhash == getTxtPassword()) { loginLog(); hide(); mw = new MainWindow(this); mw -> show(); } else { QMessageBox::warning(nullptr, "Hata", "Kullanıcı adınız veya şifreniz hatalı!"); loginLog(); } } Here is my function for write to file. void loginpage::loginLog() { QString TEXT_DIR = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/test/log.txt"; QFile file(TEXT_DIR); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream( & file); QString UnameLog = login; QString PassLog = password; stream << "Giriş yapıldı"; stream << "\n"; stream << UnameLog; stream << "\n"; qDebug()<< UnameLog; stream << PassLog; file.close(); } else { qDebug() << "hata log yazılamadı"; } } I think there is something missing or wrong, but I couldn't figure it out. Can you help me please?
Did you check the documentation? The flag you want is QIODevice::Append.
73,135,760
73,201,976
pybind11 crashes (segmentation fault (core dumped)) while importing ONNX python module
I am using pybind11 in my C++ code. When I try to import onnx, my code crashes with Segmentation fault (core dumped). However, if I import onnxruntime, everything is well. Of course both onnx and onnxruntime are installed on my system via pip. // installed libraries pip install onnx pip install onnxruntime // C++ code #include <pybind11/embed.h> namespace py = pybind11; py::module::import("onnxruntime"); // This is okay py::module::import("onnx"); // This crashes with segmentation fault The order of the import lines is irrelevant. Wherever it is, py::module::import("onnx") crashes with segmentation fault. How can I successfully run py::module::import("onnx")?
I am answering my own question. The cause of the problem was that onnx was not compatible with protobuf version 3.19.0 or higher. Using protobuf between 3.18.1 and 3.12.0 will solve the problem.
73,135,910
73,135,954
why does my std::transform retuns nothing/empty string?
can you help explain me how to use std::transform ? I need to create a function that returns a string and has a string as parameter and use std::transform to convert all the uppercase char to lower and vice versa lowercase char to uppercase example: input = "aBc" output = "AbC" and i want to do it with a lambda, not using other mehtod like toupper, etc. ​​​​​​this is what i have so far which doesnt work, it compiles and runs but it returns nothing/ empty string; std::string func(std::string inputString){ std::string result; std::transform(inputString.begin(), inputString.end(), result.begin(), [](char& c){ if (c < 97) return c + 32; if (c >= 97) return c - 32; }); return result; }
You haven't allocated any space in result, so you are observing a pretty "gentle" case of undefined behavior ("gentle" because the program is observably not working, rather than happening to work by pure luck). To solve the problem, you can either allocate such memory before calling std::transform, e.g. via result.resize(inputString.size()); or use a back_inserter for result (instead of its begin iterator result.begin()), which will take care of the allocation; the page on std::transform has such an example. In this latter case, it is still probably a good idea to reserve some space via result.reserve/* not resize! */(inputString.size());
73,136,044
73,136,347
How can i make private destructor from singleton using shared_ptr?
i tested two type of singleton from C++17 first is unique_ptr second is shared_ptr these have to work with private constructor and destructor cause nobody can't change any instance status i finaly successed to compose unique_ptr version but shrared is not done shared_ptr version makes error error is 'Singleton2::~Singleton2()' is private within this context' { __p->~_Up(); } how can i make shared_ptr singleton? here's code class Singleton1 { public: static Singleton1& GetInstance() { if(!mFlag) { mFlag = true; mSingle = std::make_unique<Singleton1>(Singleton1(1)); } return *mSingle.get(); } private: friend std::unique_ptr<Singleton1>::deleter_type; Singleton1(int n) : mNum(n) { std::cout << "this is unique_ptr singleton" << std::endl; } ~Singleton1() = default; private: const int mNum; inline static bool mFlag; inline static std::unique_ptr<Singleton1> mSingle; }; class Singleton2 { public: static Singleton2& GetInstance() { if(!mFlag) { mFlag = true; mSingle = std::make_shared<Singleton2>(Singleton2(1)); } return *mSingle.get(); } private: Singleton2(int n) : mNum(n) { std::cout << "this is shared_ptr singleton" << std::endl; } ~Singleton2() = default; private: const int mNum; inline static bool mFlag; inline static std::shared_ptr<Singleton2> mSingle; }; int main() { Singleton1& res = Singleton1::GetInstance(); Singleton2& res = Singleton2::GetInstance(); return 0; }
You can use a custom deleter and make that friend of Singleton2: #include <memory> #include <iostream> class Singleton2 { struct Deleter { void operator()(Singleton2* ptr){ delete ptr;} }; friend Deleter; public: static Singleton2& GetInstance() { if(!mFlag) { mFlag = true; mSingle = std::shared_ptr<Singleton2>(new Singleton2(1),Deleter{}); } return *mSingle.get(); } private: Singleton2(int n) : mNum(n) { std::cout << "this is shared_ptr singleton" << std::endl; } ~Singleton2() = default; private: const int mNum; inline static bool mFlag; inline static std::shared_ptr<Singleton2> mSingle; }; int main() { //Singleton1& res = Singleton1::GetInstance(); Singleton2& res = Singleton2::GetInstance(); return 0; } Live Demo However, consider to simply make the destructor public. As the pointer is encapsulaed there is no danger of someone accidentally destroying the object. And if they want to do it on purpose, they will find a way, whether the destructor is private or not. private is not a way to prevent someone by all possible means to access the function. Its rather a way to unambigously inform others that they should not play tricks to access the method. And because you do not hand the pointer to the caller, they'd also have to "play tricks" when the destructor is public. PS: I suggest you to use the Meyers Singleton where the instance is stored as function local static variable. It is thread-safe while your GetInstance is not.
73,136,532
73,138,839
Where is the data race in this simple c++ code
Both clang++ and g++ sanitizers produce similar warning about data race for this simple code. Is it a false alarm? What is the problem? Code: #include <thread> struct A { void operator()() { } }; struct B { void operator()() { } }; int main(void) { // callable objects are created and moved into thread std::thread t1(A{}); std::thread t2(B{}); t1.join(); t2.join(); return 0; } Compile flags: -pthread -O0 -g -fsanitize=thread -fsanitize=undefined Sanitizer output for g++: ================== WARNING: ThreadSanitizer: data race (pid=80173) Write of size 8 at 0x7b0400000800 by thread T2: #0 pipe ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:1726 (libtsan.so.0+0x3ea28) #1 __sanitizer::IsAccessibleMemoryRange(unsigned long, unsigned long) ../../../../src/libsanitizer/sanitizer_common/sanitizer_posix_libcdep.cpp:276 (libubsan.so.1+0x20102) #2 std::thread::_State_impl<std::thread::_Invoker<std::tuple<B> > >::~_State_impl() /usr/include/c++/11/bits/std_thread.h:201 (a.out+0x5191) #3 <null> <null> (libstdc++.so.6+0xdc2cb) Previous write of size 8 at 0x7b0400000800 by thread T1: #0 pipe ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:1726 (libtsan.so.0+0x3ea28) #1 __sanitizer::IsAccessibleMemoryRange(unsigned long, unsigned long) ../../../../src/libsanitizer/sanitizer_common/sanitizer_posix_libcdep.cpp:276 (libubsan.so.1+0x20102) #2 std::thread::_State_impl<std::thread::_Invoker<std::tuple<A> > >::~_State_impl() /usr/include/c++/11/bits/std_thread.h:201 (a.out+0x53a5) #3 <null> <null> (libstdc++.so.6+0xdc2cb) Thread T2 (tid=80176, running) created by main thread at: #0 pthread_create ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:969 (libtsan.so.0+0x605b8) #1 std::thread::_M_start_thread(std::unique_ptr<std::thread::_State, std::default_delete<std::thread::_State> >, void (*)()) <null> (libstdc++.so.6+0xdc398) #2 main a.cpp:20 (a.out+0x3396) Thread T1 (tid=80175, finished) created by main thread at: #0 pthread_create ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:969 (libtsan.so.0+0x605b8) #1 std::thread::_M_start_thread(std::unique_ptr<std::thread::_State, std::default_delete<std::thread::_State> >, void (*)()) <null> (libstdc++.so.6+0xdc398) #2 main a.cpp:19 (a.out+0x3383) SUMMARY: ThreadSanitizer: data race ../../../../src/libsanitizer/sanitizer_common/sanitizer_posix_libcdep.cpp:276 in __sanitizer::IsAccessibleMemoryRange(unsigned long, unsigned long) ================== ThreadSanitizer: reported 1 warnings Note: This warning is given only when thread and UB sanitizers are both enabled.
The program is well-formed. It doesn't have any data race or other undefined behavior and it also doesn't have any race condition or unspecified behavior (except for the possibility of aborting with an uncaught exception if thread creation fails). Thread sanitizer is simply not playing nice with the undefined behavior sanitizer. Whether they are meant to be usable together I am not sure. I have had issues like this before when combining them and so would recommend not doing that. If they are meant to play nicely together, then this would indeed be a bug.
73,137,993
73,161,527
Is there any way to get more debug info from gdb?
I can get more debug info if built my program on Windows compared to Linux. Here is my code: #include <iostream> #include <vector> using namespace std; class Base { public: Base() = default; virtual ~Base() = default; }; class Derived : public Base { public: Derived() = default; ~Derived() = default; private: int i = 1; }; int main() { vector<Base*> a; a.push_back(new Derived()); return 0; } Build On Linux: Build On Windows: It's obvious I can get more information with Windows build version. Such as vector info, vector element real type, derived object info... But Linux version, I only get the pointer address. By the way, they are all debugging by visual studio. Is there some way to add more debug info to the program built by GNU compiler? Such as compiler flags?
I fixed this problem by add a init command to the ~/.gdbinit. Add the following command to the first line of file ~/.gdbinit. set print object on
73,138,314
73,165,433
how to make pybind11 property docstring to show up?
I have following code: py::class_<Logger> logger(m, "Logger"); logger.doc() = "class docstring"; logger.def("setLevels", [](uint16_t levels) { LoggerInstance.setLevels(levels); }, R"( Turns on/off different logging levels Parameters * levels Logging level flags )" ); //expose values as constant fields logger.def_property_readonly_static("LOG_NONE", [](py::object /* self */){return LOG_NONE;}, "no log level turned on"); logger.def_property_readonly_static("LOG_INFO", [](py::object /* self */){return LOG_INFO;}, "info level logs turned on"); logger.def_property_readonly_static("LOG_DEBUG", [](py::object /* self */){return LOG_DEBUG;}, "debug level logs turned on"); logger.def_property_readonly_static("LOG_WARN", [](py::object /* self */){return LOG_WARN;}, "warning logs turned on"); logger.def_property_readonly_static("LOG_ERROR", [](py::object /* self */){return LOG_ERROR;}, "error logs turned on"); According to this answer, this is the correct way for passing docstring. But when I check it in python (3.6) help(Logger) I get empty data descriptors: How could I get the docstrings to show up in python help?
I think it's a bug (see here). If you can change the C++ source you could try to make those members non-static and then use def_property_readonly (for which docstrings show up, at least in my tests).
73,138,979
73,144,015
Finding denominator which the dividend has the maximum remainder with
I need to find the maximum remainder for n divided by any integer number from 1 to n, and the denominator which this remainder is found with. In my implementation fun1 works as expected and returns the max remainder, fun2 is supposed to give 3 but its giving 2 .probably mistake is at break statement. Sample input: 5 Expected output: 2 3. My output: 2 2. #include <iostream> #include <algorithm> using namespace std; int fun2(int a); int fun1(int n ,int num); int main(){ int n = 0; int num = 0;; cin >> n; int p = fun1(n, num); cout << p << "\n"; cout << fun2(p); } int fun1(int n, int num){ int b = 0; for(int i = 1; i <= n; i++){ num = n % i; b = max(num, b); } return b; } int fun2(int n,int p ){ int num = 0; int c = 0; int d = 0; for(int i = 1; i <= n; i++){ num = n % i; c = max(num, c); if(c == p){ break; } d = i; } return d; }
In fun2 you have: if(c == p){ break; } d = i; When you found the right index so that c == p the break will exit the loop and d == i; is not execute. Therefore d has the value from the previous loop, i.e. one less than you need. Apart from that the code really smells: fun1 should not have a second argument sum. should remember the index where if found the largest remainder and you would be done fun2 the maximum remainder is p, no need to max(num, c). Actually drop the c alltogether and just use num == p n % 1 == 0 and n % n == 0. The loop will always break with i < n. Might as well not have a conditional: for(int i = 1; ; i++) you need d because at the end of the loop i disappears. Why not pull i out of the loop? int i; for(i = 1; ; i++) and now you can use a different conditional again int fun2(int n,int p ){ int i; for(i = 1; n % i != p; i++) { } return i; } or int fun2(int n,int p ){ int i = 1; for(; n % i != p; i++) { } return i; } or int fun2(int n,int p ){ int i = 1; while(n % i != p) ++i; return i; }
73,140,361
73,150,780
QT - embedding translations works on Windows, not on Linux
In the SQLiteStudio I started using CONFIG += lrelease embed_translations for automatically embedding all translations into the app's resources. I did so by declaring: CONFIG += lrelease embed_translations QM_FILES_RESOURCE_PREFIX = /msg/translations TRANSLATIONS += $$files(translations/*.ts) This is done for all modules (in their pro files). Modules are compiled into shared libraries (such as coreSQLiteStudio, guiSQLiteStudio and then there is a executable module sqlitestudio, which is the application to run and it's dynamically linked to others, so it looks like: sqlitestudio <- executable (contains *.qm files) `- guiSQLiteStudio.so (contains *.qm files) `- coreSQLiteStudio.so (contains *.qm files) Then in runtime I'm using translation files with Qt's resources system (by call to QTranslator::load() with :/msg/translations/coreSQLiteStudio_pl_PL.qm, :/msg/translations/sqlitestudio_pl_PL.qm, etc). This works well under Windows, but - for some reason - not under Linux. The problem is that under Linux only files from sqlitestudio module (i.e. sqlitestudio_pl_PL.qm) are visible under the :/msg/translations prefix, while under Windows also other module translations (i.e. coreSQLiteStudio_pl_PL.qm, guiSQLiteStudio_pl_PL.qm) are visible under the same prefix. I've debugged TRANSLATIONS += $$files(translations/*.ts) and it is resolved properly for all modules (under Linux too). Then I have debugged runtime contents of :/msg/translations and confirmed that only sqlitestudio qm files are visible under Linux, while under Windows all qm files (from all modules) are visible. What could be causing this weird behavior? (For wider code context you may refer to SQLiteStudio's code base - it's open source and available at GitHub) EDIT - Further analysis: A qrc file is generated properly by Qt, I can see it and it has expected contents. I also see the rcc to compile it to the cpp file and make to compile it to the object file, then I see the object file linked into the final shared library. I can see all these intermediate files in the build directory. It seems that the problem is in runtime. I've listed all resources visible using function: void printResources(const QString& path, int indent) { QDir d; d.setPath(path); for (QString& f : d.entryList(QStringList({"*"}))) { qDebug() << QString(" ").repeated(indent) << f; if (!f.contains(".")) { printResources(path + "/" + f, indent + 4); } } } and then calling printResources(":/", 0);, which printed various resources, but it DID NOT contain QM files from the shared library resources, while it does contain QM files from the executable resources. It also has all resources that were explicitly added to another resources file in the shared library (some static resources, not auto generated qm files). Why does Qt have problems accessing QM auto-generated resources from shared library and only under Linux?
I got the solution. Short answer Add QMAKE_RESOURCE_FLAGS += -name coreSQLiteStudio_qm_files to all pro files (and replace the coreSQLiteStudio_qm_files to unique name in each case). If you have other (explicit) resource files in the project, you will need to have dynamic, but predictible names, like: QMAKE_RESOURCE_FLAGS += -name ${QMAKE_TARGET}_${QMAKE_FILE_BASE}, so you can pass it to the Q_INIT_RESOURCE() macro. Long answer The auto-generated (by qmake) resource file with qm files inside is compiled by the rcc into cpp file with a default initialization function qInitResources_qmake_qmake_qm_files(), which then is repeated over all other modules (shared libraries) and causes only one of those to be used in the runtime. Solution is to make initialization functions unique for each module, therefore you need to pass unique name of the resource initialization function to the rcc. By using statement like above (in the short answer) you will get initialization function qInitResources_coreSQLiteStudio_qm_files(). It seems like conflicting name of the function doesn't matter under Windows, but it does under Linux.
73,140,470
73,157,546
No matching function to call 'createMatrix'
What I'm trying to do I'm trying to convert a buffer of type [Int] to [[Int]]. Since arrays are not super easy to return in C, I'm creating a new empty array and passing the pointer into a void function that is supposed to fill the address space with Integers from the buffer. Afterwards, the matrices are supposed to get added and the result written into a result buffer. The problem For some reason, it can't find my function. I'm kind of new to c++ so excuse me when it's something simple I'm overlooking here. The function is not part of a class. So technically it should be in the same namespace? #include <metal_stdlib> using namespace metal; void createMatrix(device int **arr, int count, int buff[]) { for(int i = 0; i < count; i++) for(int j = 0; j < count; j++) arr[j][i] = buff[i + j]; } kernel void addition_compute_function(constant int *arr1 [[ buffer(0) ]], constant int *arr2 [[ buffer(1) ]], device int *resultArray [[ buffer(2) ]], uint index [[ thread_position_in_grid ]]) { int array1[6][6] = {{0}}; createMatrix(**array1, 6, *arr1); // ERROR: No matching function for call to 'createMatrix' int array2[6][6] = {{0}}; createMatrix(**array2, 6, *arr2); // ERROR: No matching function for call to 'createMatrix' for (int i = 1; i <= 6; i++){ resultArray[i][index] = array1[i][index] + array2[i][index]; // ERROR: Subscripted value is not an array, pointer, or vector } } What I tried Most questions regarding this error are concerning methods of a class getting called after an object is initialized. This isn't the case here, so no dice thus far in researching the problem. Edit, incorporated feedback #include <metal_stdlib> using namespace metal; void createMatrix(device int (*arr)[6], int count,constant int* buff) { for(int i = 0; i < count; i++) for(int j = 0; j < count; j++) arr[j][i] = buff[i + j]; } kernel void addition_compute_function(constant int *arr1 [[ buffer(0) ]], constant int *arr2 [[ buffer(1) ]], device int *resultArray [[ buffer(2) ]], uint index [[ thread_position_in_grid ]]) { int array1[6][6] = {{0}}; createMatrix(array1, 6, arr1); //ERROR: No matching function for call to 'createMatrix' int array2[6][6] = {{0}}; createMatrix(array2, 6, arr2); //ERROR: No matching function for call to 'createMatrix' int tempResultArray[6][6] = {{0}}; // I want to do some stuff here I find the 2d array form more convientient to work with, therefore the back and forth for (int i = 1; i <= 6; i++){ tempResultArray[i][index] = array1[i][index] + array2[i][index]; } for (int i = 1; i <= 6; i++){ for (int j = 1; j <= 6; j++){ resultArray[i+j] = tempResultArray[i][j]; } } Edit2 I gave up, nothing worked. I can't find the reason the function was is not recognized. I don't even know if it's the way I'm calling the function/populating the parameters, or if the namespace is wrong. Documentation for this behavior is lacking. Ended up hardcoding the function to create a 2d array from 1d array and vice versa.
Any variable that is a pointer or reference must be declared with one of the address space attributes. This is the correct implementation of your function: void createMatrix(device int (*arr)[6][6], int count, constant int* buff) { for(int i = 0; i < count; i++) for(int j = 0; j < count; j++) (*arr)[j][i] = buff[i + j]; } Kernel: device int (*array1)[6][6] = {{0}}; createMatrix(array1, 6, arr1);
73,141,573
73,141,655
VS2022 C++20 E3309 an export declaration cannot export a name with internal linkage
This happens when exporting a module namespace variable. It compiles and works as intended but Intellisense seems disagree. Is it an intellisense bug or a undefined behavior that has side effects? Tried Unnamed/anonymous namespaces vs. static functions but still same error. Env: windows11 VS2022 ISO C++latest with Experimetal Module on. employee.ixx export module employee; import std.core; namespace Records { //raise E3309 export const int DefaultRaiseAndDemeritAmount{ 1'000 }; } main.cpp import std.core; import employee; using namespace std; int main() { auto RaiseModifier = Records::DefaultRaiseAndDemeritAmount; //compiler no error and work as intended, print 1000 to console. cout << RaiseModifier; }
As usual in these cases, intellisense is incorrect. Well, the rule it cites is correct, but it is applying it where it shouldn't. Yes, you cannot export a name with internal linkage. However, your variable doesn't have internal linkage. The rules for that have an explicit carve-out for "inline or exported" non-template const-qualified variables.
73,142,306
73,142,347
Selection sorting. not getting the required output
What is wrong with this code? Not getting the right output. void selectionSort(vector<int>& arr, int n) { for(int i = 0; i < n-1; i++ ) { int min = arr[i]; for(int j = i+1; j < n; j++) { if(arr[j] < min) min = arr[j]; } swap (min, arr[i]); } }
You are using the local variable min in the swap where you needed to use the vector element. swap(arr[index_min], arr[i]) // `index_min` is the index of the current min value.
73,142,525
73,142,680
MessageBox - HWND parameter
I am working on an MFC application and I am adding some error checking with the use of MessageBox which has documentation found here. int MessageBox( [in, optional] HWND hWnd, [in, optional] LPCTSTR lpText, [in, optional] LPCTSTR lpCaption, [in] UINT uType ); Note: The utype parameter is a list of styles separated with | Above is MessageBox's implementation. My question is about the HWND parameter. When writing my call to MessageBox, Visual Studio 2017 Professional did not ask for the HWND parameter. At first, I thought it was because it is optional, but the other two optional LPCTSTR parameters were not as optional as they seemed, and required me to put at least "" to satisfy them. Currently, my call to MessageBox only uses the last three parameters. My call is: int BoxReturnVal = MessageBox("foo1", "foo2", MB_OK | MB_ICON);. My question is why is the HWND parameter not asked for while writing the call to the function and do I need to worry about it all? Thank you in advance ! :D
You are not calling the MessageBox() function that you think you are. You are looking at the MessageBox() function in the Win32 API, but MFC has its own MessageBox() method in the CWnd class. The latter one, which does not have an HWND parameter, is the one you are actually calling.
73,142,639
73,145,428
C++ file cannot find library linked with CMake
I wanted to use DearImGui therefore I needed to either copy ImGui into the project or use a package manager, so I chose the latter. I'm currently using Conan as a my package manager, the file looks like this: conanfile.txt [requires] boost/1.79.0 imgui/1.88 glad/0.1.36 glfw/3.3.7 [generators] cmake_find_package cmake_paths CMakeDeps CMakeToolchain It has all the dependancies as a normal ImGui project would need as well as boost which had been downloaded as a binary previously and works fine, using just a normal header like #include <boost/asio.hpp>. I figure this happens because it was aleady installed. I have a basic file structure that looks like this, prebuild: conanfile.txt CMakeLists.txt src - main.cpp With this main CMakeLists I set up a linker with conan and simple setup instructions like the project name, executable, and the libraries cmake_minimum_required(VERSION 3.23) project(RenderCam CXX) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) include(${CMAKE_CURRENT_SOURCE_DIR}/build/conan_paths.cmake) add_executable(${PROJECT_NAME} src/main.cpp) find_package(Boost 1.79.0 REQUIRED COMPONENTS thread system filesystem) if(TARGET boost::boost) target_link_libraries(${PROJECT_NAME} boost::boost) endif() find_package(glfw3 3.3 REQUIRED) if(TARGET glfw) message("Found GLFW") target_link_libraries(${PROJECT_NAME} glfw) endif() find_package(imgui 1.88 REQUIRED) if(TARGET imgui::imgui) message("found imgui") target_link_libraries(${PROJECT_NAME} imgui::imgui) endif() After running two commands (conan install .. and cmake .. -DCMAKE_BUILD_TYPE=Release) in the new build directory the CMake build responds with all the found messages for the project as well as the location of the files, which should be expected. Though when add the #include <imgui.h> to the main.cpp it states the file is not found which shouldn't be if I have linked it. On the other hand #include <boost/asio.hpp> has no errors and I can go upon my day with all of the commands. I would just like to include the directories and have tried multiple steps and guides before I took it here. For further reference, this is my conanprofile : Configuration for profile default: [settings] os=Macos os_build=Macos arch=x86_64 arch_build=x86_64 compiler=apple-clang compiler.version=13 compiler.libcxx=libc++ build_type=Release [options] [conf] [build_requires] [env]
Don't mix up mutually exclusive generators like cmake_find_package vs CMakeDeps, or cmake_paths vs CMakeToolchain. Here is a basic example of non-intrusive integration of conan: conanfile.txt [requires] boost/1.79.0 imgui/1.88 glfw/3.3.7 [generators] CMakeToolchain CMakeDeps CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(RenderCam CXX) find_package(Boost 1.79.0 REQUIRED thread system filesystem) find_package(glfw3 3.3 REQUIRED) find_package(imgui 1.88 REQUIRED) add_executable(${PROJECT_NAME} src/main.cpp) target_link_libraries(${PROJECT_NAME} PRIVATE Boost::headers Boost::thread Boost::system Boost::filesystem glfw imgui::imgui) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_14) Install dependencies, configure & build: mkdir build && cd build conan install .. -s build_type=Release -b missing cmake .. -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Release cmake --build . --config Release
73,142,695
73,142,955
Can I use Qt visual studio tools for comercial projects?
I understand that I can work on closed source projects using Qt as long as I link dynamically the Qt libraries and don't include them in the release version of my app. My question is, if I use Qt visual studio tools, would it compile it including the Qt libraries on my release? if so, how could I make use of Qt libraries in visual studio? Also I guess another question would be, if I use the Qt IDE's like Qt Design studio can I compile my app so that it links the Qt framework dynamically?
This dialog in the installer has the answers to all your questions. So, with these limitations in this wizard, you can use the open source version of Qt in your project. And yes, you can of course link against Qt dynamically either in qmake or cmake. All these common and popular IDEs support cmake, like Visual Studio or QtCreator, so you should not worry about using Qt in these IDEs.
73,142,903
73,143,098
What is the difference between epoll and multiple connect attempt?
Let's say i have a non blocking TCP client socket. I want to connect to a TCP server. I found that either of the following ways can be used to do so. int num_of_retry=5; for(int i=0;i<num_of_retry;i++){ connect(SOCKET_FD,...); sleep(1000ms); } and this connect(SOCKET_FD,...); epoll_wait(...,5000ms) What are the main difference in the above two approaches, performance and otherwise?
In this particular example, the main difference is that sleep() will not exit until the full interval has elapsed, whereas epoll() (and select(), too) will exit sooner if the pending connect operation finishes before the full interval has elapsed. Otherwise, both examples are blocking the calling thread until something happens (which kind of defeats the purpose of using a non-blocking socket - except that this approach is the only way to implement a timeout with connect()). Note that in either example, if you call connect() on a socket while it is already working on connecting, connect() will fail with an EALREADY error. If a connect operation times out, you should close() the socket and create a new socket before calling connect() again. And you should wait for epoll() (or select()) to tell you when the operation is finished, don't just call connect() in a loop until it reports something other than EALREADY.
73,142,919
73,143,221
Why does my stringstream get filled with garbage after tryng to insert the contents into a vector?
Consider the code: void someFunc { std::stringstream value; std::vector<std::vector<int>> mapLayerCollision; int row = 0; for(int i = 0; i < gid_list.length(); i++) { if(gid_list[i] == ',') { value.str(""); int j = 1; while (gid_list[i-j] != ',' and i - j > 0) { std::cout << gid_list[i-j] << " | "; j++; std::cout << gid_list[i-j] << std::endl; } j--; value.str(""); std::cout << "j: " << j << std::endl; while (j > 0) { std::cout << "Inserting: " << gid_list[i-j] << std::endl; value << gid_list[i-j]; std::cout << "Value AFTER: " << value.str() << std::endl; j--; } std::cout << "Putting into vector: " << std::stoi(value.str()) << std::endl; //mapLayerCollision[row].push_back(std::stoi(value.str())); value.str(""); } else if(gid_list[i] == '\n') { value.str(""); int j = 1; while (gid_list[i-j] != ',') { j++; } j--; value.str(""); while (j > 0) { value << gid_list[i-j]; j--; } std::cout << "Putting into vector: " << value.str() << std::endl; //mapLayerCollision[row].push_back(std::stoi(value.str())); value.str(""); row++; } } } The declaration of gid_list is: std::string gid_list;, and the contents are: 79,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,454,455,70, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,195,210,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259,274,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,323,338,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,387,402,0,0,0,0,0,259, 274,0,0,346,0,0,0,350,0,0,0,0,0,0,0,0,0,451,466,0,0,0,0,0,259, 274,0,0,410,0,0,0,414,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 338,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 402,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 338,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,195,210,0,0,0,0,0,0,259, 402,0,0,0,0,195,198,199,200,210,0,0,0,0,0,0,451,466,0,0,0,0,0,0,259, 274,0,0,0,0,387,264,264,264,402,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 274,0,0,0,0,451,455,456,457,466,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,259, 212,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,216, 73,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,199,200,201,199,200,201,76 So I have the lines of code that insert the stringstream value into the vector commented out, the values being printed are correct, but as soon as I uncomment those lines the printed values of the stringstream are garbled and seem to be filled with random stuff. I know that stringstreams can be finicky, but the most confusing part is that the values are printed BEFORE being added to the vector. Question: Why is the stringstream value changing when a line of code is modified AFTER it, and how can I fix it?
I know that stringstream can be finicky It is not finicky, you use it improperly. All your code can be simpler std::vector<std::vector<int>> mapLayerCollision; std::string line; while (std::getline(cin, line)) { mapLayerCollision.emplace_back(); // This fixes your issue you have asked std::istringstream values(line); int n; while (values >> n) { mapLayerCollision.back().push_back(n); char c; if ((values >> c) && c != ',') { // bad content break; } } } The issue in your code is mapLayerCollision[row] that attempts to access rowth element of the empty vector.
73,142,968
73,142,969
Variable changes value when using conditional breakpoints in Eclipse
I am using the Eclipse IDE to develop C++ code for an ARM (STM32) processor. One of the options the debugger/Eclipse has is to set not only a breakpoint, but a condition at which to break. For example, "break at line 5 only if foo is 10." However, when debugging in this way, I came across a problem where memory was changing unexpectedly. Why is this happening?
The "condition" field for a breakpoint allows you to write a C/C++ statement which will be evaluated to determine if the processor should be paused. The fact that this can be ANY valid C/C++ statement can have some interesting (i.e., problematic) side-effects if you are not careful. For example, consider the following code: 1: void foo(int a) { 2: int b = a + 2; 3: } If you want to break at line (2) only if a is equal to 10, make sure the condition is a == 10 If you write a = 10 for the condition, the debugger will break at line (2) and set the value of a to 10
73,143,373
73,144,311
Boost Graph Library: Are Vertex Descriptors Necessarily Unique?
I realize this might be pedantic, but are BGL vertex descriptors always unique? For background, I have the following graph definition: typedef boost::adjacency_list<boost::setS, boost::listS, boost::undirectedS, VProp, EProp> Graph; Where I'm using listS as the node data structure. I know that this makes my descriptors, which appear to be of type void*, "stable": when a node is removed from the graph, other descriptors for other nodes can still be used. I've looked through the BGL documentation for forever, though, and I can't find a guarantee that these descriptors are unique. Essentially, I'm wondering if two descriptors are == if and only if the underlying node data they point to is the same. In other words, is comparing descriptors directly a valid way to check node equality? Clearly this is true when the node data structure is vecS (since the descriptor is an index in that case), but I haven't found any information in the case of listS in the BGL docs. Thanks in advance!
To the title: Are Vertex Descriptors Necessarily Unique? Yes. In other words, is comparing descriptors directly a valid way to check node equality? Yes. Clearly this is true when the node data structure is vecS Exactly. I was just going to give this exact example to give a partial proof. This means that your understanding of the library is already quite deep. I happen to have looked into the code a little deeper and know that the descriptor type in case of node-based vertex container selector (listS, setS etc). will amount to a type-erased version of a direct reference to elements in that (implementation defined) container. Note that the actual type of the elements will vary depending on many of the template arguments, and this is why the descriptor is cast to the opaque void* so user code doesn't have to know about the specific internals user code cannot (accidentally) abuse those internals via the descriptor Given this nature, we can at once explain both the stability (it matches the reference stability for the underlying container implementation) and the unique-ness guarantee (descriptor identity coincides with object identity of elements in the (vertex) storage container). Note This answer only reassures you about the case of adjacency_list<> instantiations. There are other Graph models. I happen to know off-hand most have very similar guarantees for which the proof follows largely the same structure. I have not (yet) scrutinized the documentation to verify your claim that it is undocumented, and I'm not convinced that adding the explicit guarantee helps, but I commend you for asking the question. It's a good habit for (C++) programmers.
73,143,507
73,143,625
How to concatenate 2 BSTRs with a space in between them?
I have some methods that return a BSTR, and I need to concatenate those BSTRs, but it should have a space between each BSTR: BSTR a + " " + BSTR b + " " + BSTR c + and so on... I found a function that concatenates two BSTRs, however I cannot insert a space between each BSTR. Sample code: static BSTR Concatenate2BSTRs(BSTR a, BSTR b) { auto lengthA = SysStringLen(a); auto lengthB = SysStringLen(b); auto result = SysAllocStringLen(NULL, lengthA + lengthB); memcpy(result, a, lengthA * sizeof(OLECHAR)); memcpy(result + lengthA, b, lengthB * sizeof(OLECHAR)); result[lengthA + lengthB] = 0; return result; } Also, I tried to wrap the first BSTR into a _bstr_t then use the += operator to insert a space, but the first BSTR value is lost. Any help? Update @Remy Lebeau answer works. However, I tried to do the same steps, but for 6 BSTRs, and it outputs empty string! Code: memcpy(result, a, lengthA * sizeof(OLECHAR)); result[lengthA] = L' '; memcpy(result + lengthA+1, b, lengthB * sizeof(OLECHAR)); result[lengthB] = L' '; memcpy(result + lengthB+1, c, lengthC * sizeof(OLECHAR)); result[lengthC] = L' '; memcpy(result + lengthC+1, d, lengthD * sizeof(OLECHAR)); result[lengthD] = L' '; memcpy(result + lengthD+1, e, lengthE * sizeof(OLECHAR)); result[lengthE] = L' '; memcpy(result + lengthE+1, f, lengthF * sizeof(OLECHAR)); result[lengthE + 1 + lengthF] = L'\0'; Thank you very much.
Simply include room for the space character in your length calculation, and then assign the actual space character in the allocated memory, eg: static BSTR Concatenate2BSTRs(BSTR a, BSTR b) { auto lengthA = SysStringLen(a); auto lengthB = SysStringLen(b); auto result = SysAllocStringLen(NULL, lengthA + 1 + lengthB); if (result) { memcpy(result, a, lengthA * sizeof(OLECHAR)); result[lengthA] = L' '; memcpy(result + lengthA + 1, b, lengthB * sizeof(OLECHAR)); // no need to null-terminate manually, SysAllocStringLen() already did it... //result[lengthA + 1 + lengthB] = L'\0'; } return result; } Online Demo UPDATE: Your approach for 6 BSTRs does not work because your memcpy() calls are copying data to the wrong indexes within the result, thus overwriting previous data. Use a variable to keep track of where you need to insert next, eg: UINT offset = 0; memcpy(result + offset, a, lengthA * sizeof(OLECHAR)); offset += lengthA; result[offset++] = L' '; memcpy(result + offset, b, lengthB * sizeof(OLECHAR)); offset += lengthB; result[offset++] = L' '; memcpy(result + offset, c, lengthC * sizeof(OLECHAR)); offset += lengthC; result[offset++] = L' '; memcpy(result + offset, d, lengthD * sizeof(OLECHAR)); offset += lengthD; result[offset++] = L' '; memcpy(result + offset, e, lengthE * sizeof(OLECHAR)); offset += lengthE; result[offset++] = L' '; memcpy(result + offset, f, lengthF * sizeof(OLECHAR)); offset += lengthF; result[offset] = L'\0'; // <-- should not be needed Alternatively: OLECHAR *ptr = result; memcpy(ptr, a, lengthA * sizeof(OLECHAR)); ptr += lengthA; *ptr++ = L' '; memcpy(ptr, b, lengthB * sizeof(OLECHAR)); ptr += lengthB; *ptr++ = L' '; memcpy(ptr, c, lengthC * sizeof(OLECHAR)); ptr += lengthC; *ptr++ = L' '; memcpy(ptr, d, lengthD * sizeof(OLECHAR)); ptr += lengthD; *ptr++ = L' '; memcpy(ptr, e, lengthE * sizeof(OLECHAR)); ptr += lengthE; *ptr++ = L' '; memcpy(ptr, f, lengthF * sizeof(OLECHAR)); ptr += lengthF; *ptr = L'\0'; // <-- should not be needed
73,143,614
73,143,648
does this reference the pointer returned with "new"?
I have created a char* str_1 and have allocated 64 bytes to it. Then I created another char* str_2 and referenced it to the initial string. char* str_1 = new char[64]; char* str_2 = str_1; // does it reference the object created with the new statement. My question is, does str_2 contain the reference to the allocated memory? In which case, could I do something like this? char* str_1 = new char[64]; char* str_2 = str_1; delete[] str_2; Is calling delete[] str_2 actually deleting the allocated memory? Or, is it causing a memory leak?
After the declaration of the pointer str_2, both pointers str_1 and str_2 are pointing to the same dynamically allocated memory (character array). char* str_1 = new char[64]; char* str_2 = str_1; After calling the operator delete []: delete[] str_2; Both pointers become invalid, because they both do not point to an existing object. There is no memory leak. You may use either pointer to delete the allocated array. But you may not delete the same dynamically allocated memory twice. A memory leak occurs when a memory was allocated dynamically and was not freed at all.
73,143,615
73,166,330
TaskDialogIndirect randomly fails and makes empty, undrendered window
I use TaskDialogIndirect() to display more advanced Error Messages. I can customize the buttons, icons, and more. The problem is that, sometimes it makes these invisible empty dialog boxes. I need it to be reliable. I am wondering why this is even happening in the first place. Example of it failing (there is no visible window): Here is the code that makes the dialogs (not production code): int MessageBoxPosL(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType, int X, int Y) { TaskDialogData data; data.X = X; data.Y = Y; TASKDIALOGCONFIG config = {}; config.cbSize = sizeof(config); config.hwndParent = hWnd; config.pszWindowTitle = lpCaption; config.pszContent = lpText; // configure other settings as desired, based on uType... config.pfCallback = &TaskDialogCallback; config.lpCallbackData = (LONG_PTR)&data; config.dwFlags = TDF_ENABLE_HYPERLINKS; config.hFooterIcon = LoadIcon(NULL, IDI_ERROR); config.dwCommonButtons = ButtonActive(TDCBF_YES_BUTTON) | ButtonActive(TDCBF_NO_BUTTON) | ButtonActive(TDCBF_OK_BUTTON) | ButtonActive(TDCBF_RETRY_BUTTON) | ButtonActive(TDCBF_CLOSE_BUTTON); config.pszMainIcon = SetIcon(); int button = 0; TaskDialogIndirect(&config, &button, NULL, NULL); return button; }
The problem was the flag TDF_ENABLE_HYPERLINKS. Adding hyperlinked text that is too long caused the dialog to spawn outside of the desktop view.
73,143,660
73,143,733
An elegant approach to comparing many int variables to a value - C++
Of the two current answers, I have chosen the one using the range based for loop as it better addressed my first requirement which is to avoid being lengthy. The answer with the variadic template is interesting (and I will try it out!) but lengthier than I would like (since I want everything done inside the same function I mentioned with the variables). If anyone else comes up with another method, I will still pay attention (even in the far future!) and am always happy to select a possibly better solution ;) I am using Visual Studio 2017 Professional, C++, MFC I have a strange question which might have no solution I have a function that comes across several int variables, say I have six in total: int1, int2, ..., int6. I want to compare each of these values to -1. If any of them == -1, then the void function returns, exiting early. I know the first idea you may come up with is a lengthy if statement, possibly with several branches like: if ( (int1 == -1) || (int2 == -1) || ... || (int6 == -1) ) { return;} or if (int1 == -1) { return;} else if (int2 == -1) { return;} ... else if (int6 == -1) { return;} Another idea is to push all these ints to a std::vector<int> then iterate through them, comparing each element to -1 with an if clause and returning if there is a match. This is the plan I will fall back to if there is no other solution. Is there a way to check these values with a more elegant approach that is: not lengthy does not use a container such as std::vector does not use much more memory than either of the two ideas above Again, I completely understand if there is no method that fits my specifications, and in that case I will go with the std::vector approach. And I do know that at some point I have to bite the bullet and get to comparing the ints but I am interested if there is some other method! Any help is appreciated, thank you in advance ! :D
You can use a range based for loop as for example for ( const auto &item : { v1, v2, v3, v4, v5, v6 } ) { if ( item == -1 ) return; } or in C++ 20 for ( int value = -1; const auto &item : { v1, v2, v3, v4, v5, v6 } ) { if ( item == value ) return; } If you do not want to create copies of the variables in the std::initializer_list then use std::reference_wrapper. As for example #include <iostream> #include <functional> #include <initializer_list> int main() { int v1 = -1, v2 = -2, v3 = -3, v4 = -4, v5 = -5, v6 = -6; for ( auto item : { std::ref( v1 ), std::ref( v2), std::ref( v3 ), std::ref( v4 ), std::ref( v5 ), std::ref( v6 ) } ) { if ( item == -1 ) { std::cout << "There is element with the value -1\n"; break; } } }
73,144,100
73,144,285
Error when using std::vector::size to create another vector
I am learning DSA and while practising my LeetCode questions I came across a question-( https://leetcode.com/problems/find-pivot-index/). Whenever I use vector prefix(size), I am greeted with errors, but when I do not add the size, the program runs fine. Below is the code with the size: class Solution { public: int pivotIndex(vector<int>& nums) { //prefix[] stores the prefix sum of nums[] vector<int> prefix(nums.size()); int sum2=0; int l=nums.size(); //Prefix sum of nums in prefix: for(int i=0;i<l;i++){ sum2=sum2+nums[i]; prefix.push_back(sum2); } //Total stores the total sum of the vector given int total=prefix[l-1]; for(int i=0; i<l;i++) { if((prefix[i]-nums[i])==(total-prefix[i])) { return i; } } return -1; } }; I would really appreciate if someone could explain this to me. Thanks!
If you use vector constructor with the integer parameter, you get vector with nums.size() elements initialized by default value. You should use indexing to set the elements: ... for(int i = 0; i < l; ++i){ sum2 = sum2 + nums[i]; prefix[i] = sum2; } ... If you want to use push_back method, you should create a zero size vector. Use the constructor without parameters. You can use reserve method to allocate memory before adding new elements to the vector.
73,144,358
73,144,389
C++ Same Variable on Left and Right Side of Assignment
Suppose that we have some object, such as std::vector<int> foo. I know from reading the C++ docs on self-assignment that foo = foo (although weird) should technically be OK since classes in C++ are responsible for being self-assignment safe. However, suppose that I also have some method reverse() that does not modify the input, but instead returns a new vector that is a reversed version of the given argument. I then perform: foo = reverse(foo); Would this be OK? I've gone down a pretty deep rabbit hole reading about sequence points and things like that, and TBH my brain is sort of fried now- could anybody offer a more straightforward explanation here? I know that x = x + 5 where x is of type int is clearly fine, but I'm wondering how this changes when we're dealing with objects that allocate memory. In addition, suppose that we had another method reverseMutate() that does mutate the input, and then returns that reversed (mutated) original vector back. I'm even less clear whether foo = reverseMutate(foo); is defined behavior. Thank you so much for the help! I promise I've tried diving into the C++ docs, and I'm just looking for a more straightforward explanation that doesn't make my brain hurt...
Yes on both counts. Everything is safe. foo = reverse(foo); If reverse doesn't mutate foo, then it returns a completely unrelated vector, and that vector is assigned to foo. Those two steps happen in that order. The result of reverse must be fully known before operator= is ever called on foo, for the same reason that if we do bar(baz(1)), the baz call must completely terminate before bar is ever called. foo = reverseMutate(foo); This one is a little more exciting but is still fine. If reverseMutate(foo) mutates foo and then returns it (i.e. literally return *this; as a std::vector<int>&), then it behaves the same as reverseMutate(foo); foo = foo; i.e. it's just self-assignment in disguise, and as you've already correctly pointed out, C++ classes are responsible for being able to handle this case.
73,144,452
73,144,556
Segmentation fault with references
Why do I get Segmentation fault with the code below? #include <iostream> #include <string> const std::string& f() { return "abc"; } std::string&& g() { return "xyz"; } int main() { const std::string& s1 = f(); std::string&& s2 = g(); s2 += "-uvw"; std::cout << s1 << ", " << s2 << std::endl; return 0; } I expected that both s1 and s2 are still alive with I print them, but actually they are not. Why? For example, they are alive in the code below that does not crash: #include <iostream> #include <string> int main() { const std::string& s1 = "abc"; std::string&& s2 = "xyz"; s2 += "-uvw"; std::cout << s1 << ", " << s2 << std::endl; return 0; } what is the difference?
Your second example with no extra function calls is well-defined due to the reference lifetime extension rules. Essentially, when a prvalue is immediately bound to a reference upon creation, the lifetime of the referenced object is extended to that of the reference. In your first example, reference lifetime extension does not apply. The prvalues created in your functions' return statements are not immediately bound to the references in main (there are intermediate steps). The objects referenced by the references returned by f and g are local to those functions, and immediately go out of scope when the function returns.
73,144,724
73,145,444
Python vs C++ Precision
I am trying to reproduce a C++ high precision calculation in full python, but I got a slight difference and I do not understand why. Python: from decimal import * getcontext().prec = 18 r = 0 + (((Decimal(0.95)-Decimal(1.0))**2)+(Decimal(0.00403)-Decimal(0.00063))**2).sqrt() # r = Decimal('0.0501154666744709107') C++: #include <iostream> #include <math.h> int main() { double zx2 = 0.95; double zx1 = 1.0; double zy2 = 0.00403; double zy1 = 0.00063; double r; r = 0.0 + sqrt((zx2-zx1)*(zx2-zx1)+(zy2-zy1)*(zy2-zy1)); std::cout<<"r = " << r << " ****"; return 0; } // r = 0.050115466674470907 **** There is this 1 showing up near the end in python but not in c++, why ? Changing the precision in python will not change anything (i already tried) because, the 1 is before the "rounding". Python: 0.0501154666744709107 C++ : 0.050115466674470907 Edit: I though that Decimal would convert anything passed to it into a string in order to "recut" them, but the comment of juanpa.arrivillaga made me doubt about it and after checking the source code, it is not the case ! So I changed to use string. Now the Python result is the same as WolframAlpha shared by Random Davis: link.
The origin of the discrepancy is that Python Decimal follows the more modern IBM's General Decimal Arithmetic Specification. In C++ however there too exist support available for 80-bit "extended precision" through the long double format. For reference, the standard IEEE-754 floating point doubles contain 53 bits of precision. Here below the C++ example from the question, refactored using long doubles: #include <iostream> #include <math.h> #include <iomanip> int main() { long double zx2 = 0.95; long double zx1 = 1.0; long double zy2 = 0.00403; long double zy1 = 0.00063; long double r; r = 0.0 + sqrt((zx2-zx1)*(zx2-zx1)+(zy2-zy1)*(zy2-zy1)); std::fixed; std::cout<< std::setprecision(25) << "r = " << r << " ****"; //25 floats // prints "r = 0.05011546667447091067728042 ****" return 0; }
73,145,529
73,151,406
Can not include linked with CMake third-party library
I am trying to use an fmt library in my C++ project for formatting. I have installed the package with anaconda. Afterwards, in my CMake file I have found the fmt package and link: set(fmt_DIR "/opt/anaconda3/lib/cmake/fmt/") find_package(fmt REQUIRED) target_link_libraries(<my_target> fmt) But even though these steps are done, I run into "fatal error: 'fmt' file not found", when trying to #include <fmt> I am probably missing something obvious. Would appreciate any help.
As @Tsyvarev mentioned in comment: ... after find_package(fmt) one should link with fmt::fmt: target_link_libraries(<your-target> fmt::fmt). So using target_link_libraries(<your-target> fmt::fmt) instead of target_link_libraries(<your-target> fmt) works perfectly.
73,145,946
73,146,008
Merge two 2D arrays into one C++
I would like to merge two arrays (inventory & inventory2) into one new array (inventory3) for sorting purposes. I am unable to have inventory3 have values assigned by inventory2 (the second nested for loop). inventory3 is accepting assignment from inventory correctly. I cannot figure out why this is not working. I have been able to verify that the contents of ivnentory2 are correct. void sortInput(string inventory[10][3], int inventory2[10][2]) { string inventory3[10][5]; for (int count = 0 ; count < 10 ; count++) { for (int count2 = 0 ; count2 < 3 ; count2++) { inventory3[count][count2] = inventory[count][count2]; cout << inventory3[count][count2] << "\t"; } for (int count2 = 3, count3 = 0 ; count3 < 2 ; count2++, count3++) { inventory3[count][count2] = inventory2[count][count3]; cout << inventory3[count][count2] << "\t"; } cout << endl; } }
You're trying to assign an int to a string in this statement: inventory3[count][count2] = inventory2[count][count3]; To make it work, convert the int to string like this: inventory3[count][count2] = to_string(inventory2[count][count3]);
73,146,307
73,146,335
Are standard library non-type template classes explicitly instantiated?
When we have a templated class (or function) that has a non-type template parameter, how are the versions generated by the compiler? Surely it doesn't create a version for every possible value of N Suppose something like std::array<T,N> ? I am trying to write my own templated function with a size_t template parameter, and I am trying to figure out whether/how I need to explicitly instantiate versions I will use (I have split the program across different translation units) I have a templated function which is something like template <size_t N> std::bitset<N> f(std::bitset<N> A){} I put the declaration into a header file and definition into a .cpp file. It doesn't generate the correct version. So I tried to explicitly instantiate it like template std::bitset<10> f<10>(std::bitset<10> A); but I get the error that "error: explicit instantiation of .... but no definition available"
Neither the standard library nor you need to explicitly instantiate any template specialization, whether it has non-type template parameters or not. Any specialization of the template which is used by the user in a way that requires a definition for the specialization to exist will cause it to automatically be implicitly instantiated if a definition for the entity which is instantiated is available. The condition should normally always be fulfilled since it is standard practice to place definitions of templated entities into the header file along with their initial declaration, so that they are accessible in all translation units using them. So std::array<T,N> will be implicitly instantiated for all pairs of types T and values N which are actually used by the translation unit. The only situation where explicit instantiation is required is if you intent to separate the definitions of template members into a single translation unit instead of the header file where they would be available for all translation units to implicitly instantiate. But you can only do that in the first place if you know all possible values for the template parameters, and you would then need to explicitly instantiate all of them, which for most non-type template parameters is not feasible. Aside from that explicit instantiation may be used as an optimization of compilation time by avoiding implicitly instantiating template specializations in every translation unit where they are used. That makes sense only for specializations which you know will be often used. For example some standard library implementations apply it to std::string, which is the specialization std::basic_string<char>. It doesn't really make sense to apply it to e.g. std::array.
73,146,387
73,146,671
How to include webview in existing Qt project?
I am trying to include one of the following libraries: #include <QtWebView> #include <QWebView> #include <QtWebEngineWidgets> #include <WebEngineCore> #include <QtWebEngine> Each time I add one of its includes an error appears in my code. However, I use Qt 6.3.1 and I find files that correspond to the includes in my system installation folder under macOS. I use a cmake in my qt project and not a file.pro or qmake. Ultimately, I want to display a web form in my UI.
You need to make sure that you install the QtWebEngine module when installing Qt. Then, in your CMakeLists.txt, you would write something like this below. Please note that you should use versionless targets as recommended by the Qt Project, i.e. do not use Qt6::WebEngineWidgets as that would have portability issues. find_package(Qt6 COMPONENTS WebEngineWidgets REQUIRED) target_link_libraries(YourTarget Qt::WebEngineWidgets) add_executable(YourTarget main.cpp) Then, you can just write something like this in your main.cpp: #include <QApplication> #include <QWebEngineView> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWebEngineView view; view.setUrl(QUrl(QStringLiteral("https://www.qt.io"))); view.show(); return app.exec(); } Please refer to the official examples for further details.
73,146,581
73,146,758
Is it UB to reference bind to underlying type of enum class object?
Is it UB to reference bind to underlying type of enum class object? I'm aware of the danger of pass-through return reference of the as_int function. The thunking function is just to help explain the question. XY problem - after a bunch of inline operators to static_cast to/from underlying type at appropriate places, I found this to be an easier to use alternative in places. But I am unsure if it is undefined behavior, and the reinterpret_cast takes off the safety. The public facing API of the enum class would not expose this pattern; it is just for private use in the implementation file. #include <iostream> using std::cout; enum class Int : int {}; inline auto as_int(Int& i) -> int& { return reinterpret_cast<int&>(i); } int main() { Int i{100}; int& r = as_int(i); cout << r << "\n"; //> 100 as_int(i) = 107; cout << r << "\n"; //> 107 }
Accessing the return value of as_int(i) as done in your main is an aliasing violation and therefore causes undefined behavior. The relevant paragraph of the standard ([basic.lval]/11) does not list underlying types of enumeration types as specifically allowed to alias. Currently the standard doesn't even specify that the enumeration type and the underlying type will share the same alignment. If it was different then the cast would not even preserve the value (so that a round-trip cast would be unsafe). But that seems like a defect, see CWG 2590. Alignment issues aside, the cast itself does not have undefined behavior, but accessing the enumeration object through the resulting reference does.