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
72,519,241
72,519,460
Static assertion failed error in defining set (STL container) with user defined objects c++17
I defined a set with data type as user defined object here. #include<bits/stdc++.h> using namespace std; class triplets{ public: int x,y,z; triplets(){ } triplets(int x,int y,int z){ this->x=x; this->y=y; this->z=z; } }; class Cmp{ public: Cmp(){}; bool operator() (const triplets &a, const triplets &b){ if( a.x == b.x){ return a.y < b.y; }else{ return a.x < b.x; } } }; int main(){ set<triplets,Cmp>s; s.insert(triplets(2,4,5)); return 0; } The code compiles fine in c++11 and c++14 versions. But it doesn't compile in c++17 and above. It throws following error. In file included from /usr/include/c++/11/map:60, from /usr/include/x86_64-linux-gnu/c++/11/bits/stdc++.h:81, from Arrays/TwoPointer/test.cpp:1: /usr/include/c++/11/bits/stl_tree.h: In instantiation of ‘static const _Key& std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_S_key(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Const_Link_type) [with _Key = triplets; _Val = triplets; _KeyOfValue = std::_Identity<triplets>; _Compare = Cmp; _Alloc = std::allocator<triplets>; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Const_Link_type = const std::_Rb_tree_node<triplets>*]’: /usr/include/c++/11/bits/stl_tree.h:2071:47: required from ‘std::pair<std::_Rb_tree_node_base*, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_unique_pos(const key_type&) [with _Key = triplets; _Val = triplets; _KeyOfValue = std::_Identity<triplets>; _Compare = Cmp; _Alloc = std::allocator<triplets>; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = triplets]’ /usr/include/c++/11/bits/stl_tree.h:2124:4: required from ‘std::pair<std::_Rb_tree_iterator<_Val>, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(_Arg&&) [with _Arg = triplets; _Key = triplets; _Val = triplets; _KeyOfValue = std::_Identity<triplets>; _Compare = Cmp; _Alloc = std::allocator<triplets>]’ /usr/include/c++/11/bits/stl_set.h:521:25: required from ‘std::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Tp>, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(std::set<_Key, _Compare, _Alloc>::value_type&&) [with _Key = triplets; _Compare = Cmp; _Alloc = std::allocator<triplets>; typename std::_Rb_tree<_Key, _Key, std::_Identity<_Tp>, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<_Key>::other>::const_iterator = std::_Rb_tree<triplets, triplets, std::_Identity<triplets>, Cmp, std::allocator<triplets> >::const_iterator; typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<_Key>::other = std::allocator<triplets>; typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<_Key> = __gnu_cxx::__alloc_traits<std::allocator<triplets>, triplets>::rebind<triplets>; typename _Alloc::value_type = triplets; std::set<_Key, _Compare, _Alloc>::value_type = triplets]’ Arrays/TwoPointer/test.cpp:29:13: required from here /usr/include/c++/11/bits/stl_tree.h:770:15: error: static assertion failed: comparison object must be invocable as const 770 | is_invocable_v<const _Compare&, const _Key&, const _Key&>, | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usr/include/c++/11/bits/stl_tree.h:770:15: note: ‘std::is_invocable_v<const Cmp&, const triplets&, const triplets&>’ evaluates to false Any idea how should I define the set?
bool operator() (const triplets &a, const triplets &b){ should be bool operator() (const triplets &a, const triplets &b) const{
72,519,383
72,522,923
Boost Beast Read Conent By Portions
I am trying to understand how can I limit the amount of data that is read from the internet by calling 'read_some' function in boost beast. The starting point is the incremental read example in the beast's docs. From the docs I understood that the really read data is stored in the flat_buffer. I make the following experiment: Set max flat_buffer's size to 1024 Connect to a relatively large (several KB) html page Call read_some one time Turn the internet off Try to read the page to the end Since buffer's capacity is not large enough to store the entire page, my experiment should fail - I should not be able to read the entire page. Nevertheless, it finishes successfully. That means that there exists some additional buffer where the read data is stored. But what is it made for and how can I limit its size? UPD Here is my source code: #include <boost/beast/core.hpp> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <boost/asio/strand.hpp> #include <cstdlib> #include <functional> #include <iostream> #include <memory> #include <string> namespace beast = boost::beast; // from <boost/beast.hpp> namespace http = beast::http; // from <boost/beast/http.hpp> namespace net = boost::asio; // from <boost/asio.hpp> using namespace http; template< bool isRequest, class SyncReadStream, class DynamicBuffer> void read_and_print_body( std::ostream& os, SyncReadStream& stream, DynamicBuffer& buffer, boost::beast::error_code& ec ) { parser<isRequest, buffer_body> p; read_header( stream, buffer, p, ec ); if ( ec ) return; while ( !p.is_done()) { char buf[512]; p.get().body().data = buf; p.get().body().size = sizeof( buf ); read_some( stream, buffer, p, ec ); if ( ec == error::need_buffer ) ec = {}; if ( ec ) return; os.write( buf, sizeof( buf ) - p.get().body().size ); } } int main(int argc, char** argv) { try { // Check command line arguments. if(argc != 4 && argc != 5) { std::cerr << "Usage: http-client-sync <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" << "Example:\n" << " http-client-sync www.example.com 80 /\n" << " http-client-sync www.example.com 80 / 1.0\n"; return EXIT_FAILURE; } auto const host = argv[1]; auto const port = argv[2]; auto const target = argv[3]; int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11; // The io_context is required for all I/O net::io_context ioc; // These objects perform our I/O boost::asio::ip::tcp::resolver resolver(ioc); beast::tcp_stream stream(ioc); // Look up the domain name auto const results = resolver.resolve(host, port); // Make the connection on the IP address we get from a lookup stream.connect(results); // Set up an HTTP GET request message http::request<http::string_body> req{http::verb::get, target, version}; req.set(http::field::host, host); req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING); // Send the HTTP request to the remote host http::write(stream, req); // This buffer is used for reading and must be persisted beast::flat_buffer buffer; boost::beast::error_code ec; read_and_print_body<false>(std::cout, stream, buffer, ec); } catch(std::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
The operating system's TCP IP stack obviously needs to buffer data, so that's likely where it gets buffered. The way to test your desired scenario: Live On Coliru #include <boost/beast.hpp> #include <iostream> #include <thread> namespace net = boost::asio; namespace beast = boost::beast; namespace http = beast::http; using net::ip::tcp; void server() { net::io_context ioc; tcp::acceptor acc{ioc, {{}, 8989}}; acc.listen(); auto conn = acc.accept(); http::request<http::string_body> msg( http::verb::get, "/", 11, std::string(20ull << 10, '*')); msg.prepare_payload(); http::request_serializer<http::string_body> ser(msg); size_t hbytes = write_header(conn, ser); // size_t bbytes = write_some(conn, ser); size_t bbytes = write(conn, net::buffer(msg.body(), 1024)); std::cout << "sent " << hbytes << " header and " << bbytes << "/" << msg.body().length() << " of body" << std::endl; // closes connection } namespace { template<bool isRequest, class SyncReadStream, class DynamicBuffer> auto read_and_print_body( std::ostream& /*os*/, SyncReadStream& stream, DynamicBuffer& buffer, boost::beast::error_code& ec) { struct { size_t hbytes = 0, bbytes = 0; } ret; http::parser<isRequest, http::buffer_body> p; //p.header_limit(8192); //p.body_limit(1024); ret.hbytes = read_header(stream, buffer, p, ec); if(ec) return ret; while(! p.is_done()) { char buf[512]; p.get().body().data = buf; p.get().body().size = sizeof(buf); ret.bbytes += http::read_some(stream, buffer, p, ec); if(ec == http::error::need_buffer) ec = {}; if(ec) break; //os.write(buf, sizeof(buf) - p.get().body().size); } return ret; } } void client() { net::io_context ioc; tcp::socket conn{ioc}; conn.connect({{}, 8989}); beast::error_code ec; beast::flat_buffer buf; auto [hbytes, bbytes] = read_and_print_body<true>(std::cout, conn, buf, ec); std::cout << "received hbytes:" << hbytes << " bbytes:" << bbytes << " (" << ec.message() << ")" << std::endl; } int main() { std::jthread s(server); std::this_thread::sleep_for(std::chrono::seconds(1)); std::jthread c(client); } Prints sent 41 header and 1024/20480 of body received 1065 bytes of message (partial message) Side Notes You start your question with: I am trying to understand how can I limit the amount of data that is read from the internet That's built in to Beast by calling 'read_some' function in boost beast. To just limit the total amount of data read, you don't have to use read_some in a loop (http::read by definition already does exactly that). E.g. with the above example, if you replace 20ull<<10 (20 KiB) with 20ull<<20 (20 MiB) you will exceed the default size limit: http::request<http::string_body> msg(http::verb::get, "/", 11, std::string(20ull << 20, '*')); Prints Live On Coliru sent 44 header and 1024/20971520 of body received hbytes:44 bbytes:0 (body limit exceeded) You can also set your own parser limits: http::parser<isRequest, http::buffer_body> p; p.header_limit(8192); p.body_limit(1024); Which prints Live On Coliru: sent 41 header and 1024/20480 of body received hbytes:41 bbytes:0 (body limit exceeded) As you can see it even knows to reject the request after just reading the headers, using the content-length information from the headers.
72,519,493
72,519,551
Forcing string literal argument to cause std::string class template deduction
I would like to write a class template, which is able to hold different types. However, I want to avoid specializations of type char* or char[]. Character strings should always be std::string. The code below is what I have so far. However, writing Scalar("hello") yields T = char[6] and not T = std::string. I could write Scalar<std::string>("hello") or Scalar(std::string("hello")) to work around the problem. My question is, is there a way to modify the code below such that writing Scalar("hello") works as intended and the class still has only one template parameter? template <typename T> class Scalar { public: explicit Scalar(const T& val); };
Deduction guide (c++17) might help: template <std::size_t N> Scalar(const char(&)[N]) -> Scalar<std::string>; Demo.
72,520,213
72,520,354
nested lambdas cause compiler to run out of heap
I'm writing some code which passes lambda functions to a suite of recursive functions. Some of these lambda functions are nested inside other lambda functions. I think I'm writing valid code but I'm getting a fatal error C1060: compiler is out of heap space error. Here is a much cut down version of the code struct Null { template <typename SK> static void match(SK sk) { } }; template <typename T> struct Repetition { template <typename SK> static void match(SK sk) { // <--------------------------------- error message points to this line T::match([]() { match([]() {}); }); } }; int main() { using Test = Repetition<Null>; Test::match([](){}); } Now this minimal version doesn't make much sense but it has the same compiler error. I've indicated the line with the error above. My question is, is this a compiler bug/limitation or is my code invalid in some way? Compiler is Visual Studio 2022 compiling C++20. Thanks
Per [expr.prim.lambda.closure] The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type To instantiate Repetition::match, the compiler must instantiate Null::match which requires an instantiation of Repetition::match... and so on. Each time the compiler recurses, []() {} is treated as a brand new type, ad infinitum. To get it to stop recursing, replace your call with: T::match(sk);
72,521,037
72,521,342
Implementing virtual functions in child's .cpp causes "undefined reference to `vtable for <child's class>`"
I have an interface: //Card.h #include "../Players/Player.h" class Card { public: virtual void applyEncounter(Player& player) const = 0; virtual void printInfo() const = 0; virtual ~Card() {} }; And a class that inherits from it // Barfight.h // ... #include "../Players/Player.h" #include "Card.h" class Barfight : public Card { public: Barfight() {} void applyEncounter(Player& player) const override; void printInfo() const override; virtual ~Barfight() {}; private: static const int LOSE_HP = 10; }; // Barfight.cpp #include "Card.h" #include "Barfight.h" #include "../Players/Player.h" void Barfight::applyEncounter(Player& player) const override { } void Barfight::printInfo() const override { std::cout << "I don't get printed at all" << endl; } But when I run in a main() function: Barfight myBarfightCard; myBarfightCard.printInfo(); Command Line (from the root directory): g++ -std=c++11 -Wall -Werror -pedantic-errors -DNDEBUG -g *.cpp -o my_test This gives me the error: <...>/test.cpp:145: undefined reference to `Barfight::printInfo() const' /usr/bin/ld: /tmp/ccNVNgLR.o: in function `Barfight::Barfight()': <...>/Cards/Barfight.h:14: undefined reference to `vtable for Barfight' /usr/bin/ld: /tmp/ccNVNgLR.o: in function `Barfight::~Barfight()': <...>/Cards/Barfight.h:35: undefined reference to `vtable for Barfight' collect2: error: ld returned 1 exit status However, if I do this: // Barfight.h // ... void applyEncounter(Player& player) const override {}; void printInfo() const override {}; // ... I don't get an error, but it doesn't print what is inside of the Barfight.cpp. How do I still do an implementation that works in the .cpp? Files: test.cpp (has main()) Players Player.h Player.cpp Cards Cards.h Barfight.h Barfight.cpp
You are building your project in wrong way. You've have shown this: g++ -std=c++11 -Wall -Werror -pedantic-errors -DNDEBUG -g *.cpp -o my_test What is scary you have a wild card here and your code uses relative paths. This is straight way to forgot some file, what will lead to linking issue. Note that wild card is not recursive it doesn't reach into sub directories. However, if I do this: // Barfight.h // ... void applyEncounter(Player& player) override {}; void printInfo() override {}; // ... I don't get an error, but it doesn't print what is inside of the Barfight.cpp. This means that when you did build it you didn't liked code properly and result of compilation of Barfight.cpp was not used. Learn some build manager ASAP. cmake is most common used tool. There are other tools like bazel, Make, Ninja or IDE specific project files.
72,521,471
72,521,628
Strange output when use Pointers in c++
Considere the following code in c++: #include <iostream> using namespace std; int main() { int x=2, y; int *p = &x; int **q = &p; std::cout << p << std::endl; std::cout << q << std::endl; std::cout << *p << std::endl; std::cout << x << std::endl; std::cout << *q << std::endl; *p = 8; *q = &y; std::cout << "--------------" << std::endl; std::cout << p << std::endl; std::cout << q << std::endl; std::cout << *p << std::endl; std::cout << x << std::endl; std::cout << *q << std::endl; return 0; } The output of code is (of course the list numbers is not the part of output): 0x7fff568e52e0 0x7fff568e52e8 2 2 0x7fff568e52e0 '-----------' 0x7fff568e52e4 0x7fff568e52e8 0 8 0x7fff568e52e4 Except for 7 and 9, all outputs were expected for me. I appreciate someone explaining them to me.
The variable y was not initialized int x=2, y; So it has an indeterminate value. As the pointer q points to the pointer p int **q = &p; then dereferencing the pointer q you get a reference to the pointer p. So this assignment statement *q = &y; in fact is equivalent to p = &y; That is after the assignment the pointer p contains the address of the variable y. So this call std::cout << p << std::endl; now outputs the address of the variable y. 0x7fff568e52e4 and this call std::cout << *p << std::endl; outputs the indeterminate value of y that happily is equal to 0. 9. 0
72,521,499
72,529,948
What is the difference between glPolygonMode GL_LINE and glDrawElements GL_LINE_LOOP mode?
The following code snippets give me exactly the same result: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDrawElements(GL_LINE_LOOP, vbo.rows(), GL_UNSIGNED_INT, 0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDrawElements(GL_LINE_LOOP, vbo.rows(), GL_UNSIGNED_INT, 0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glDrawElements(GL_TRIANGLES, vbo.rows(), GL_UNSIGNED_INT, 0); So is there a different purpose for each option? (or is GL_LINE_LOOP just an override of the polygon mode)? EDIT: I'm playing around with libigl example project. The following is the screenshot of the output:
glPolygonMode change the rasterization mode, but does not change the primitive. The primitive type stays the same and there are still GL_TRIANGLES primitive drawn. glPolygonMode has no effect on other primitives than triangles. GL_LINE_LOOP is a different primitive type. It connects all the vertices to a single line. If you try to draw multiple separated triangles (with a gap between the triangles), then you'll see the difference. You can draw multiple separate outlines of triangles with glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) and GL_TRIANGLES primitives, but you cannot with a GL_LINE_LOOP primitive.
72,521,879
72,522,947
How to display text (sf::Text) from a class with SFML?
I'm trying to create a button class, with some text in it. I encountered an issue with the text inside the button, it simply does not display. After much trouble debugging my code, I managed to isolate the faulty code portion. (In examples below, I recreated the issue with a minimal code) someText.h class someText{ private: Font _font; Text _text; public: someText(); someText(string); ~someText(); void drawText(RenderWindow&); }; someText.cpp someText::someText() {} someText::someText(string str) { this->_font.loadFromFile("Manjari-Thin.otf"); this->_text.setFont(this->_font); this->_text.setString(str); this->_text.setFillColor(Color::Black); } someText::~someText(){}; void someText::drawText(RenderWindow& win) { win.draw(this->_text); } main.cpp int main() { //create a window RenderWindow window(VideoMode(500, 500), "SFML", Style::Default); window.setFramerateLimit(10); string textValue[3] = {"un","dos","tres"}; someText textArray[3]; //create someText objects and store them in an array for (int i = 0; i < 3; i++) { someText obj(textValue[i]); textArray[i] = obj; } //main loop while (window.isOpen()) { window.clear(Color::White); //draw text for (int i = 0; i < 3; i++) { textArray[i].drawText(window); } window.display(); } return 0; } In the main.cpp file, I create several someText objects (each object containing a Font object and a Text object) and store them in an array. Then, at the end of the code, I draw the someText objects from the array. When I execute the program, a point appear instead of the text (meaning that the Text object is present) I discovered that by creating a someText object after the loop, the text was written properly. main.cpp int main() { //create a window RenderWindow window(VideoMode(500, 500), "SFML", Style::Default); window.setFramerateLimit(10); string textValue[3] = {"un","dos","tres"}; someText textArray[3]; //create someText objects and store them in an array for (int i = 0; i < 3; i++) { someText obj(textValue[i]); textArray[i] = obj; } // vvv // vvv added an object here someText anotherObject(""); // ^^^ // ^^^ //main loop while (window.isOpen()) { window.clear(Color::White); //draw text for (int i = 0; i < 3; i++) { textArray[i].drawText(window); } window.display(); } return 0; } My guess is : Because the draw method, in main.cpp, take a Text object reference as parameter rather than a Text object, and as I was creating my someText objects in a loop (so the destructor was called at the end of each iteration), so, with no objects pointed by the reference, the draw method would just draw ... points. I'm not 100% sure my conclusion is fully accurate (or even true), but I'm reaching my limits of C++ comprehension anyway. So, my question is : How do I fix this, as cleanly as possible ? (As I don't want to have a useless line in my program because ... well it's useless)
You are victim of sf::Text class behaviour: It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text). taken from sf::Text reference. When the loop works, at line [1] for (int i = 0; i < 3; i++) { someText obj(textValue[i]); textArray[i] = obj; // [1] } obj has text which refers to font. While assignment, font and text are copied. text in target object will reference to the font of source object which at the end of loop is deleted. As a result you have dangling reference in sf::Text instance when referencing to sf::Font. Instead of relying on defaulted generated assignment operator for someText class which makes troubles you should define your own version: someText& operator=(const someText& other) { this->_font = other._font; this->_text = other._text; // copies all old properties this->_text.setFont(this->_font); // [2], update font refernece return *this; } since [2] _text in target object will reference to its own font instance not to other._font which will be dangled. Another solution could be to mark copy assignment operator and copy constructor as delete functions. And stores someText instances by smart pointers like unique_ptr/smart_ptr - you will avoid implementation of copy operations.
72,521,923
72,521,990
Is it possible to assign address value directly to a pointer?
I'm learning C++ from www.learncpp.com. The tutorials are good and I could ask the author myself by commenting but it takes some time to get a reply. So, here is something I'm confused in lesson 23.7 near the end of the lesson. A warning about writing pointers to disk While streaming variables to a file is quite easy, things become more complicated when you’re dealing with pointers. Remember that a pointer simply holds the address of the variable it is pointing to. Although it is possible to read and write addresses to disk, it is extremely dangerous to do so. This is because a variable’s address may differ from execution to execution. Consequently, although a variable may have lived at address 0x0012FF7C when you wrote that address to disk, it may not live there any more when you read that address back in! For example, let’s say you had an integer named nValue that lived at address 0x0012FF7C. You assigned nValue the value 5. You also declared a pointer named *pnValue that points to nValue. pnValue holds nValue’s address of 0x0012FF7C. You want to save these for later, so you write the value 5 and the address 0x0012FF7C to disk. A few weeks later, you run the program again and read these values back from disk. You read the value 5 into another variable named nValue, which lives at 0x0012FF78. You read the address 0x0012FF7C into a new pointer named *pnValue. Because pnValue now points to 0x0012FF7C when the nValue lives at 0x0012FF78, pnValue is no longer pointing to nValue, and trying to access pnValue will lead you into trouble. It's written as if we could store an address like 0x0012ff78 and retrieve it directly back to a pointer. Hence the question, since I couldn't find an answer anywhere.
Yes you can, and in C++ it looks something like: auto ptr = reinterpret_cast<ptr_type>(0x0012FF7C); Where ptr_type is a valid pointer type, like int* for example. To add a bit more clarity to the problem outlined in the lesson: Memory addresses are constantly being reclaimed and reused as required by the different programs running on a system. When your program starts running, the OS keeps track of which memory addresses your program is allowed to access. When your program ends, those memory address are reclaimed by the OS for use by another process which might need it. If you restart your program and attempt to modify or access (de-reference) the information stored at a particular address, which your program did not explicitly request for, the OS will/should detect this and may decide to end the program.
72,521,938
72,522,313
Implementing LRU Cache using doubly linked list and unordered map in c++
I have implemented LRU cache after watching multiple online sources but am unable to understand why the code outputs value "alpha" for 3 , please suggest how to cure this in the LRU cache implementation . I have checked multiple online sources but all of them are for implementing int to int mapping , here i want to give input as integer and store a string which hasnt been covered anywhere Here is the code : #include <iostream> #include<bits/stdc++.h> // we have used doubly linked list as it was readily availaible in the c++ stl library #include <list> // we do not need ordered map , unordered map is enough for hashing #include <unordered_map> using namespace std; class LRU_Cache{ public: // this cache stores strings // integers are mapped to strings , i.e. we can access data using integers list<string> L; unordered_map<int,list<string>::iterator > M; int capacity ; LRU_Cache(int cap){ capacity = cap; L.clear(); M.clear(); } int size(){ return capacity; } void feedin(int key , string data){ // if key not present in cache already if(M.find(key)==M.end()){ // when cache is full then remove last then insert else just insert // so we just need if rather than if else if(L.size()==capacity){ // remove the last element first from map then from list // removing from map for(auto it:M){ if((it.second) == L.end()){ // M[it.first] = M.end(); M.erase(it.first);//it.first break; } } // removing from list L.pop_back(); } // key is not present and cache is not full case else{ } // now insertion L.push_front(data); M[key]=L.begin(); return; } // key is present in cache already else{ // erase the already present data for that key in the list L.erase(M[key]); // add the data to the list L.push_front(data); // reassign the value of iterator in the map for that key M[key]=L.begin(); // we do not need to remove the last value here , // since size of cache remains same after this operation return; } } string gettin(int key){ if(M.find(key)==M.end()){ return "0"; } else{ return *M[key]; } } }; int main() { // Declaring a LRU Cache LRU_Cache lru1(2); // Checking the size cout<<"The size of this LRU Cache is : " <<lru1.size()<<endl; // Adding data to it lru1.feedin(3,"beta"); lru1.feedin(1,"alpha"); lru1.feedin(8,"gamma"); // checking the data now cout<<lru1.gettin(1)<<endl; cout<<lru1.gettin(3)<<endl; cout<<lru1.gettin(6)<<endl; cout<<lru1.gettin(8)<<endl; return 0; } And here is the output alpha gamma 0 gamma EDIT : The doubt has been solved now and the code is now available at https://github.com/ayush-agarwal-0502/LRU-Cache-Implementation for anyone who was trying to implement a LRU Cache and needs explanation or code
In feedin replace if((it.second) == L.end()) with if((it.second) == --L.end()) and ensure capacity can never be zero. This shouldn't be much of a restriction because there is no point to a LRU cache that can't cache anything. Explanation: I believe the mistake is in believing that L.end() returns an iterator referring to the last item in L. It doesn't. end() returns a sentinel marking the end of the list. It doesn't correspond to any elements in the list, and this is why it is useable as the item not found case in searches. In feedin, if((it.second) == L.end()) compares L iterators stored in M to an iterator that is guaranteed to not be in L and thus will not be in M. Nothing is ever found. To get an iterator for the last item in L, you need --L.end(). Note that --L.end() is valid when the list is not empty, something guaranteed by a capacity greater than 0.
72,522,263
72,538,581
Issue with 3d rotation along the X axis
I'm working on a project that required a 3d cube to be rotated along 3 axes. The cube is made up of 12 triangles, each with an instance of the Triangle class. Each triangle has a p0, p1, and p2 with the type sf::Vector3f. The triangles also have a float* position and a float* rotation. The position and rotation of a triangle is updated using this method. void Triangle::update() { position; p0 = originalP0; p1 = originalP1; p2 = originalP2; sf::Vector3f rotatedP0; sf::Vector3f rotatedP1; sf::Vector3f rotatedP2; // along z rotatedP0.x = p0.x * cos((*rotation).z * 0.0174533) - p0.y * sin((*rotation).z * 0.0174533); rotatedP0.y = p0.x * sin((*rotation).z * 0.0174533) + p0.y * cos((*rotation).z * 0.0174533); rotatedP0.z = p0.z; rotatedP1.x = p1.x * cos((*rotation).z * 0.0174533) - p1.y * sin((*rotation).z * 0.0174533); rotatedP1.y = p1.x * sin((*rotation).z * 0.0174533) + p1.y * cos((*rotation).z * 0.0174533); rotatedP1.z = p1.z; rotatedP2.x = p2.x * cos((*rotation).z * 0.0174533) - p2.y * sin((*rotation).z * 0.0174533); rotatedP2.y = p2.x * sin((*rotation).z * 0.0174533) + p2.y * cos((*rotation).z * 0.0174533); rotatedP2.z = p2.z; p0 = rotatedP0; p1 = rotatedP1; p2 = rotatedP2; // along y rotatedP0.x = p0.x * cos((*rotation).y * 0.0174533) + originalP0.z * sin((*rotation).y * 0.0174533); rotatedP0.y = p0.y; rotatedP0.z = p0.x * -sin((*rotation).y * 0.0174533) + originalP0.z * cos((*rotation).y * 0.0174533); rotatedP1.x = p1.x * cos((*rotation).y * 0.0174533) + originalP1.z * sin((*rotation).y * 0.0174533); rotatedP1.y = p1.y; rotatedP1.z = p1.x * -sin((*rotation).y * 0.0174533) + originalP1.z * cos((*rotation).y * 0.0174533); rotatedP2.x = p2.x * cos((*rotation).y * 0.0174533) + originalP2.z * sin((*rotation).y * 0.0174533); rotatedP2.y = p2.y; rotatedP2.z = p2.x * -sin((*rotation).y * 0.0174533) + originalP2.z * cos((*rotation).y * 0.0174533); p0 = rotatedP0; p1 = rotatedP1; p2 = rotatedP2; // along x rotatedP0.x = p0.x; rotatedP0.y = p0.y * cos((*rotation).x * 0.0174533) - p0.z * sin((*rotation).x * 0.0174533); rotatedP0.z = p0.y * sin((*rotation).x * 0.0174533) + p0.z * cos((*rotation).x * 0.0174533); rotatedP1.x = p1.x; rotatedP1.y = p1.y * cos((*rotation).x * 0.0174533) - p1.z * sin((*rotation).x * 0.0174533); rotatedP1.z = p1.y * sin((*rotation).x * 0.0174533) + p1.z * cos((*rotation).x * 0.0174533); rotatedP2.x = p2.x; rotatedP2.y = p2.y * cos((*rotation).x * 0.0174533) - p2.z * sin((*rotation).x * 0.0174533); rotatedP2.z = p2.y * sin((*rotation).x * 0.0174533) + p2.z * cos((*rotation).x * 0.0174533); p0 = rotatedP0 + *position; p1 = rotatedP1 + *position; p2 = rotatedP2 + *position; } This method works well for all axes except the X axis. The cube has two red faces intersecting the Z axis, two green faces intersecting the Y axis, and two blue faces intersecting the X axis. Rotating the cube along the Z and Y axes works fine. The cube is rotating around the red and green faces. When rotating along the X axis, the cube is not rotated around the blue faces, but rather the global X axis. Am I doing something wrong? Is it supposed to be this way? Is there any way to fix it? I searched all over and couldn't find anything helpful.
bro you did it all wrong. use this 3D point rotation algorithm. i know it is javascript but the math still the same
72,522,679
72,522,716
c++ how to overwrite method in subclass
I have some code I'm trying to get to work, I'm open to other suggestions on how to do this. Basically, I have some base class that I want a bunch of subclasses to inherit. I then have a function that needs to call the subclass version of this method. #include <iostream> using namespace std; //my base class class BaseClass { public: void myMethod(){ std::cout << "Base class?" << std::endl; } }; /my subclass class SubClass1: public BaseClass{ public: void myMethod(){ std::cout << "Subclass?" << std::endl; } }; //method that I want to call SubClass.myMethod(). I cannot declare this as //SubClass1 because there will be multiple of these. void call_method(BaseClass object){ return object.myMethod(); } int main() { BaseClass bc; SubClass1 sb1; //works how I expect it to sb1.myMethod(); //I want this to also print "Subclass?" //but it prints "Base class?". call_method(sb1); return 0; } Thanks for your help
You need to declare the member function in the base class as virtual. For example virtual void myMethod() const { std::cout << "Base class?" << std::endl; } And in the derived class to override it void myMethod() const override { std::cout << "Subclass?" << std::endl; } And the function call_method must have a parameter that represents a reference to base class object void call_method( const BaseClass &object){ object.myMethod(); }
72,523,157
72,533,955
Strange/inconsistent behavior with armadillo with `copy_aux_mem` and solving with a triangular matrix
Consider the following C++ code // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> // [[Rcpp::export(rng = false)]] void possible_bug(arma::vec &x, arma::mat const &sig_chol){ if(x.n_elem != sig_chol.n_rows * sig_chol.n_cols) throw std::runtime_error("boh"); arma::mat x_mat(x.begin(), sig_chol.n_rows, sig_chol.n_rows, false); x_mat = arma::solve (arma::trimatu(sig_chol), arma::solve(arma::trimatu(sig_chol), x_mat).t()); } I am using Rcpp::sourceCpp() as this is the easiest way for me to set the example up. With a 3D matrix I get set.seed(1) n <- 3L x <- rnorm(n * n) sig_chol <- rWishart(1, n, diag(n)) |> drop() |> chol() x_cp <- x + 0. possible_bug(x = x_cp, sig_chol) all.equal(x_cp, x) #R> [1] "Mean relative difference: 1.000271" all.equal(x_cp, solve(sig_chol, t(solve(sig_chol, matrix(x, n)))) |> c()) #R> [1] TRUE This exactly what I will expect (the input argument is changed as it is used for the memory for the result). It also works with n <- 4L. However with a 5D matrix I get set.seed(1) n <- 5L x <- rnorm(n * n) sig_chol <- rWishart(1, n, diag(n)) |> drop() |> chol() x_cp <- x + 0. possible_bug(x = x_cp, sig_chol) all.equal(x_cp, x) #R> [1] TRUE all.equal(x_cp, solve(sig_chol, t(solve(sig_chol, matrix(x, n)))) |> c()) #R> [1] "Mean relative difference: 2.041895" This is unlike what I would expect (the input argument is not changed). Are my expectations wrong? The above is with RcppArmadillo version 0.11.1.1.0. The reason I am posting this is because of a unit test which failed after I upgraded to the new version of RcppArmadillo. I get a consistent and expected behavior with version 0.10.8.1.0. The difference persists if I remove the arma::trimatu() calls.
This is an intended change in version 11.1.1. See https://gitlab.com/conradsnicta/armadillo-code/-/issues/210#note_974299524 The way to go is to set strict to true in the constructor of arma::mat and other objects.
72,523,412
72,523,426
Storing numbers manually into int ** makes some numbers random | c++
I'm trying to fill an array of int array to create a tilemap for a videogame. However I've used switch case and I tried to fill the map when initializing it but some of the number are random for an unknown reason. Here's the code: int **Process::get_story_map(int lvl) { int **map = new int *[10]; switch (lvl) { case (0): { int line01[10] = {5, 0, 1, 1, 2, 2, 1, 1, 0, 5}; int line02[10] = {0, 0, 1, 1, 2, 2, 1, 1, 0, 0}; int line03[10] = {1, 1, 1, 1, 2, 2, 1, 1, 1, 1}; int line04[10] = {1, 1, 1, 1, 0, 0, 1, 1, 1, 1}; int line05[10] = {2, 2, 1, 0, 0, 0, 0, 1, 2, 2}; int line06[10] = {2, 2, 1, 0, 0, 0, 0, 1, 2, 2}; int line07[10] = {1, 1, 1, 1, 0, 0, 1, 1, 1, 1}; int line08[10] = {1, 1, 1, 1, 2, 2, 1, 1, 1, 1}; int line09[10] = {0, 0, 1, 1, 2, 2, 1, 1, 0, 0}; int line10[10] = {5, 0, 1, 1, 2, 2, 1, 1, 0, 5}; map[0] = line01; map[1] = line02; map[2] = line03; map[3] = line04; map[4] = line05; map[5] = line06; map[6] = line07; map[7] = line08; map[8] = line09; map[9] = line10; } case (1): { int line01[10] = {5, 0, 1, 1, 1, 1, 1, 1, 0, 5}; int line02[10] = {0, 0, 1, 1, 2, 2, 1, 1, 0, 0}; int line03[10] = {1, 1, 1, 1, 2, 2, 1, 1, 1, 1}; int line04[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int line05[10] = {2, 2, 2, 1, 2, 2, 1, 2, 2, 2}; int line06[10] = {2, 2, 2, 1, 2, 2, 1, 2, 2, 2}; int line07[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int line08[10] = {1, 1, 1, 1, 2, 2, 1, 1, 1, 1}; int line09[10] = {0, 0, 1, 1, 2, 2, 1, 1, 0, 0}; int line10[10] = {5, 0, 1, 1, 2, 2, 1, 1, 0, 5}; map[0] = line01; map[1] = line02; map[2] = line03; map[3] = line04; map[4] = line05; map[5] = line06; map[6] = line07; map[7] = line08; map[8] = line09; map[9] = line10; break; } default: return (NULL); } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { std::cout << map[i][j] << " "; std::cout << std::endl; } std::cout << "--------------------------------" << std::endl; return (map); } Here's where I call it int main(void) { // Initialization //-------------------------------------------------------------------------------------- Process *process = new Process(); // int **map = process->generate_arcade_map(); int **map = new int *[10]; map = process->get_story_map(1); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { std::cout << map[i][j] << " "; } std::cout << std::endl; } } And here's the output: 5 0 1 1 1 1 1 1 0 5 0 0 1 1 2 2 1 1 0 0 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 1 2 2 1 2 2 2 2 2 2 1 2 2 1 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 0 0 1 1 2 2 1 1 0 0 5 0 1 1 2 2 1 1 0 5 -------------------------------- 5 0 1 1 1 1 1 1 0 5 0 0 1 1 2 2 -2070125006 32711 0 0 1 1 -2068490400 32711 5 0 1 0 1 0 -2068507136 32711 -2070171513 32711 1 1 0 0 -116061664 32766 -2066141792 32711 32711 0 0 0 -2068490400 32711 1 0 1 0 -1835315192 22061 -2068507136 32711 -2070171513 32711 53 0 3432 22061 -1835306944 22061 1 0 0 0 -116061680 32766 -1835322135 22061 0 0 -1835306944 22061 -1835306936 22061 -116061695 32766 -1835306944 32711 -125382144 99592016 1 2 0 0 -1835315192 22061 -116061152 22061 0 0 -2062934976 32711 -2067049860 32711 -1835322135 22061 I don't see what's causing this problem since the first few numbers are right. (I know my code looks kinda spaghetti and I'm open to any advice :D)
{ case (0): { int line01[10] = {5, 0, 1, 1, 2, 2, 1, 1, 0, 5}; int line02[10] = {0, 0, 1, 1, 2, 2, 1, 1, 0, 0}; int line03[10] = {1, 1, 1, 1, 2, 2, 1, 1, 1, 1}; int line04[10] = {1, 1, 1, 1, 0, 0, 1, 1, 1, 1}; int line05[10] = {2, 2, 1, 0, 0, 0, 0, 1, 2, 2}; int line06[10] = {2, 2, 1, 0, 0, 0, 0, 1, 2, 2}; int line07[10] = {1, 1, 1, 1, 0, 0, 1, 1, 1, 1}; int line08[10] = {1, 1, 1, 1, 2, 2, 1, 1, 1, 1}; int line09[10] = {0, 0, 1, 1, 2, 2, 1, 1, 0, 0}; int line10[10] = {5, 0, 1, 1, 2, 2, 1, 1, 0, 5}; map[0] = line01; map[1] = line02; map[2] = line03; map[3] = line04; map[4] = line05; map[5] = line06; map[6] = line07; map[7] = line08; map[8] = line09; map[9] = line10; } You are storing pointers to local objects. As soon as you hit the }, line01 no longer exists because it is no longer in scope. So map[0] contains a pointer to nothing valid. You should never dereference a pointer to an object that no longer exists. You can only access objects during their lifetimes.
72,523,775
72,693,638
C++ Microsoft docs - File handling / Get folder path
I have learned C/C++ Basics and practiced , but I have hard time understanding Microsoft documentation and find it confusing Documention example for example : I try to create command line program that should let the user open folder dialog and choose folder , as result the folders path should be stored in variable did research and found that there is many ways to achieve this goal but the best way is using IFileDialog::GetFolder method (shobjidl_core.h) what the difference between file dialogs? The main question : How to get folders path as string variable based on user choice from file dialog? There is c++ resources with practical tutorials ? I try to understand how I use the following dialog : Folder dialog it refernces me to: BROWSEINFOA structure Would be very helpful if someone could explain how I can use this folder dialog or something better any great tutorial of windows/linux file system handling
I used to wcout to print out path TCHAR path[260]; BROWSEINFO bi = { 0 }; LPITEMIDLIST pidl = SHBrowseForFolder(&bi); SHGetPathFromIDList(pidl, path); wcout << path << '\n'; We can use com interface as well : int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow); { HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (SUCCEEDED(hr)) { IFileOpenDialog* pFileOpen; // Create the FileOpenDialog object. hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen)); // if object created ( that's com object ) if (SUCCEEDED(hr)) { // Show the Open dialog box. hr = pFileOpen->Show(NULL); // Get the file name from the dialog box. if (SUCCEEDED(hr)) { IShellItem* pItem; hr = pFileOpen->GetResult(&pItem); if (SUCCEEDED(hr)) { PWSTR pszFilePath; hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); // Display the file name to the user. if (SUCCEEDED(hr)) { MessageBoxW(NULL, pszFilePath, L"File Path", MB_OK); CoTaskMemFree(pszFilePath); cout << pszFilePath; std::string stringtoconvert; std::wstring temp = std::wstring(stringtoconvert.begin(), stringtoconvert.end()); LPCWSTR lpcwstr = temp.c_str(); } pItem->Release(); } } pFileOpen->Release(); } CoUninitialize(); } return 0; } Important to mention : Open and Save As common dialog boxes ( commdlg.h ) have been superseded by the Common Item Dialog For linux and other platforms there is cross platforms libraries like Qt and more , here is a link for UI solutions and about Microsoft documentation : I think there should be simpler examples and explanations its complicated & frustrating to learn this way.
72,523,818
72,524,105
Unable to Launch Child Process with command line arguments C++
I am trying to code a program that launches a child process and the child process will execute the program with the arguments entered in the command line. This is what the command line should look like. ./launch program arg1 arg2 arg3 argv[0] = "./launch" argv[1] = "program" --> This is the program I want the child process to run. (program.cpp is already compiled when ./launch runs) argv[2] = "arg1" argv[3] = "arg2" argv[4] = "arg3" I want to be able to pass argv[2],argv[3],argv[4] into the child process. I do this using the execve method. When I run "./launch program arg1 arg2 arg3 " The child process does spawn and run but only argv[1] and argv[2] show in the child processes char*argv[]. LaunchProcess.cpp #include <unistd.h> #include <sys/wait.h> #include <iostream> pid_t spawnChild(const char* program, char** arg_list) { pid_t ch_pid = fork(); if(ch_pid < 0){ exit(EXITFAILURE); } else if (ch_pid >0){ std::cout <<"Spawned Child with Process Identification: " << ch_pid<< std::endl; return ch_pid; } else { execve(program,arg_list,nullptr); } } int main(int argc, char *argv[]){ char *arguments[argc-2]; std::string program_name = argv[1]; for (int i = 2; i < argc; i++) { arguments[i-2] = argv[i]; //std::cout << arguments[i-2] << std::endl; } } char *arg_list[] = {const_cast <char *>(program_name.data()), *arguments, nullptr}; spawnChild(program_name.c_str(), arg_list); } program.cpp #include <stdio.h> using namespace std; int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) printf("Argument %d is %s\n", i, argv[i]); return 0; } Output Spawned Child with Process Identification: 44331 Argument 0 is program Argument 1 is arg1 child 44331 terminated I think I am passing in args_list into execve wrong. That would be my guess. This question may be trivial but I have been stuck on it for some time. Any help would be appreciated.
You appear to assume that *arguments will expand to multiple items, but this is a Python list unpacking feature that C++ does not have. Instead, C/C++ uses * here for pointer dereferencing. Your statement will therefore declare a nullptr-terminated list of two arguments, rather than N arguments the way you appear to intend: char *arg_list[] = {const_cast <char *>(program_name.data()), *arguments, nullptr}; Rewrite your code to correctly build the argument list, e.g. by adding them to a std::vector<char*>. You can use a debugger or something like for(int i=0; arg_list[i] != nullptr; i++) printf("Arg %d: %s\n", i, arg_list[i]); to verify that the list is correct.
72,523,844
72,524,641
How to read a 2d triangle array from txt file?
I want to read 2d triangle array from a txt file. 1 8 4 2 6 9 8 5 9 6 I wrote this code. At the end I wanted to print it out if I got the array right. When I run it it does not print the array, but in debug it prints. So there is a problem, but I cannot find it. Sometimes it gives segmentation fault, but I dont understand. #include <iostream> #include <fstream> #include <cstdlib> #include <string> int main() { std::ifstream input_file("input_file.txt"); int size{1}; int **arr = (int**)malloc(3*sizeof(int)); int *lineArr = (int*) malloc(size*sizeof(int)); int temp{}; int index{}; while(input_file >> temp){ lineArr[index] = temp; index++; if(index == size){ index = 0; arr[size-1] = new int[size-1]; for(int i{}; i<size; i++){ arr[size-1][i] = lineArr[i]; } size++; lineArr = (int*) realloc(lineArr, size*sizeof(int)); } } input_file.close(); for(int a{}; a<size-1; a++){ for(int j{}; j<=a; j++){ std::cout << arr[a][j] << " "; } std::cout << std::endl; } return 0; }
You can just use vector instead of malloc. Like this: #include <iostream> #include <fstream> #include <cstdlib> #include <string> #include <vector> using namespace std; int main() { ifstream input_file("input_file.txt"); vector<string> numbers; if (input_file.is_open()) { string line; while (getline(input_file, line)) { numbers.push_back(line); } input_file.close(); } for (vector<string>::iterator t=numbers.begin(); t!=numbers.end(); ++t) { cout<<*t<<endl; } return 0; }
72,523,879
72,525,427
add to queue a template function c++
i search on google how to store and to execute functions (template function or not) passing in queue but i didn't find an enough good answer... this is my code Window.h struct QueueEventFunction { std::vector<std::function<void()>> v; // stores the functions and arguments // as zero argument lambdas template <typename F,/*template <typename U, typename = std::allocator<U> >*/ typename ...Args> void Enqueue(F (*f), Args... args) { v.push_back([=] { f(args...); }); // add function and arguments // as zero argument lambdas // that capture the function and arguments } void CallAll() { for (auto f : v) f(); // calls all the functions } }; class Window : public sf::RenderWindow { public: Window(sf::VideoMode window, const std::string& title, sf::Uint32 style = 7U, sf::ContextSettings settings = sf::ContextSettings()); ~Window(); template <typename F, /*template <typename ...U > */typename ...Args> void addQueue(F (*f), Args...args); void execQueue(); private: QueueEventFunction queue; } template <typename F, /*template <typename ...U >*/ typename ...Args> void Window::addQueue(F (*f), Args...args) { queue.Enqueue(f, std::forward<Args>(args)...); } void Window::execQueue() { queue.CallAll(); } TestWindow.cpp template<typename T> void add(T a, T b) { return a + b; } class foo{ public: template<typename T> T add( T a, T b){ return a+ b;} }; int main() { Window window(sf::VideoMode(600, 600), "Test Window",7U,sf::ContextSettings()); window.addQueue(add<int>,1,2); // doesn't work foo bar; window.addQueue(&foo::add<int>,1,2); // doesn"t work window.addQueue(bar.add<int>(1,2)); // doesn"t work return 0; } i got a external symbol error. and if i put a function member class it simply doesn't work. (compilation error) have you got an idea to correctly make the function addQueue<> with args ?
The big problem with your code is that you take the function pointer as a pointer template <typename F, typename ...Args> void Enqueue(F (*f), Args... args) and template <typename F, typename ...Args> void addQueue(F (*f), Args...args); What you really want is template <typename F, typename ...Args> void Enqueue(F f, Args... args) and template <typename F, typename ...Args> void addQueue(F f, Args...args); And then you can pass any callable thing. Then you can use it with results of bind, lambdas, class member functions, class static member functions, and normal functions. Then you can use it like template<typename T> int add(T a, T b) { std::cout << "add(" << a << "," << b << ") -> " << a+b << "\n"; return a + b; } class foo{ public: template<typename T> T add( T a, T b) { std::cout << "foo::add(" << a << "," << b << ") -> " << a+b << "\n"; return a + b; } template<typename T> static T static_add( T a, T b) { std::cout << "foo::static_add(" << a << "," << b << ") -> " << a+b << "\n"; return a + b; } }; int main() { Window window(sf::VideoMode(600, 600),"Test Window",7U,sf::ContextSettings()); foo bar; auto bar_add = [&bar](auto a,auto b){ return bar.add<int>(a,b); }; auto bind_add = std::bind(&foo::add<int>, &bar, std::placeholders::_1, std::placeholders::_2); window.addQueue(bind_add,5,2); window.addQueue(bar_add,5,2); window.addQueue(add<int>,5,2); window.addQueue(foo::static_add<int>,5,2); window.execQueue(); return 0; } Try it here https://www.onlinegdb.com/t9WczrL-c
72,524,438
72,525,656
simplify template interface, remove redundant typenames
#include <cstddef> #include <utility> template <size_t N, typename... V> struct T { int test(size_t n, const char** ss) { if (N > n) return 1; return []<size_t... I>(const char* ss[N], std::index_sequence<I...>) { return test_impl(ss[I]...); }(ss, std::make_index_sequence<N>{}); } // Ideally this would be templated, solving my problem: // i.e. move "typename... V" from the struct to this function. virtual int test_impl(V...) = 0; }; template <typename U, size_t N, typename... V> struct T1 : T<N, V...> { U value; int (*tester)(U*, V...); int test_impl(V... v) { return tester(&value, v...); } // virtual is not an aggregate T1(U value, int (*tester)(U*, V...)) : value{value}, tester{tester} {}; }; int test1(int* v, const char* s1, const char* s2) { return 1; } template <typename... V> int test2(int* v, V... ss) { return 1; } C++ is very good at deducing template function parameters from function arguments, but virtual function templates are not allowed. I am forced to move the function template parameters to the struct template, and find that C++ is not good at deducing template struct parameters from member variables. In the end I am forced to specify redundant information to the template which makes the T1/T interface difficult to use? How can I fix this? For example, here we know that: sizeof...(V) == N decltype(V) must be const char* template parameter U can be deduced solely from the argument of the T1 constructor template parameter V... can be deduced solely from the argument of the T1 constructor from which it follows that template parameter N can be deduced solely from the argument of the T1 constructor. int main() { // The '2' and the 'const char*'... are redundant T1 a = T1<int, 2, const char*, const char*>(10, test1); T1 b = T1<int, 2, const char*, const char*>(10, test2); // There is enough information here to deduce the values T1 c = T1(10, test1); // There is enough information here to deduce the values T1 d = T1<..., 2, ...>(10, test2); }
sizeof...(V) == N No, the compiler doesn't know it. (Take a look at the error messages) Since you have this prequisite, you don't have to have the template parameter N. template <typename... V> struct T { int test(size_t n, const char** ss) { constexpr int N = sizeof...(V); if (N > n) return 1; return []<size_t... I>(const char* ss[N], std::index_sequence<I...>) { return test_impl(ss[I]...); }(ss, std::make_index_sequence<N>{}); } // Ideally this would be templated, solving my problem: // i.e. move "typename... V" from the struct to this function. virtual int test_impl(V...) = 0; }; See online demo
72,525,107
72,525,391
How to force C++ linker to catch conflict of enum definitions?
I have these two source files that compile and link without any problem. a.cpp enum class numbers { one, two, }; const char* getName(numbers number) { switch (number) { case numbers::one: return "one"; break; case numbers::two: return "two"; break; } } b.cpp #include <iostream> enum class numbers { zero, one, two, }; const char* getName(numbers number); void print(numbers number) { std::cout << getName(number); } int main() { print(numbers::one); return 0; } As you can see the same enum class is defined differently in each file. I am looking for a way to catch these kind of conflicts of enum classes (causing bugs in our very very big code base) in different translation units. Does any compiler/linker has the capability to generate error in such situation?
The shown error is a violation of the One Definition Rule. The C++ standard does not require either the compiler or a linker to report a diagnostic when the One Definition Rule is violated. I.e. "no diagnostic required". In other words: your C++ compiler is not required to report this specific error. This is because in many cases it's simply not possible to technically detect a violation of the one definition rule, due to low-level technical implementation details of how code gets compiled and linked on some particular operating system, or platform. In general: it is in every modern C++ compiler's interest to report as many useful diagnostics as possible. In other words: if it's possible for a C++ compiler to detect an ODR violation, it would readily do so without being prodded into it. If your C++ compiler does not produce a diagnostic for an ODR violation, it is unlikely that there's any hidden switch or a button that can be pushed in order to make the error come out.
72,525,307
72,525,499
When 'nested stack unwinding' is OK?
AS I understand that we can not throw exceptions from dtor, and the reason is said like: "if an exception was thrown inside 'stack unwinding', then there is no clear way to handle 'nested unwinding', thus 'throwing from dtor' is prohibited.". What makes me confuse is that, to obey above rule, we write codes like this: #include <stdexcept> #include <string> #include <stdio.h> void some_cleanup_stuff_that_may_throw(); class Bar { public: virtual ~Bar(){ try { some_cleanup_stuff_that_may_throw(); } catch (std::exception& e){ fprintf(stderr, "Exception: %s from %s\n", e.what(), __FUNCTION__); } } }; //{{ implementation of 'some_cleanup_stuff_that_may_throw' void level1(); void level2(); void some_cleanup_stuff_that_may_throw() { level1(); } void level1() { level2(); } void level2() { throw std::runtime_error("Yes thrown when stack unwinding"); } //}} implementation of 'some_cleanup_stuff_that_may_throw' void Foo1() { Bar b1; throw std::runtime_error("Let's start stack unwinding"); } int main() { try { Foo1(); } catch (std::exception& e){ fprintf(stderr, "Exception: %s from %s\n", e.what(), __FUNCTION__); } return 0; } So in some circumstance, 'nested stack unwinding' is possible. My question is: when 'nested stack unwinding' is 'OK' ?
Throwing an exception while stack unwinding is in progress is fine. But throwing an exception from a destructor of an object that is being unwound from the stack or from any other function invoked by the exception handling mechanism (e.g. a catch parameter constructor) causes a call to std::terminate. Throwing from a function here is supposed to mean that the thrown exception is not caught inside its body (or function try-catch block) and actually escapes the function. In your example, no exception is leaving the destructor. So there is no problem. It is allowed to have nested exceptions being handled or being in the process of stack unwinding. Once the nested exception is caught, handled and the destructor finishes, the original stack unwinding can continue calling the next destructor moving up the stack again. There is even API for this. For example you can use std::uncaught_exceptions() which gives you the number of currently uncaught exceptions. The implementation of the C++ runtime just has to make sure to keep track of all of the exception objects currently alive. (I assume that you are not really interested in the exact implementation details of the unwind implementations. If you are, then please clarify this in the question.)
72,525,482
72,525,732
Why does constinit allow UB?
Say I initialize variables like this: #include <cstdint> constexpr uint16_t a = 65535; constinit int64_t b = a * a; // warning: integer overflow in expression of type 'int' results in '-131071' [-Woverflow] constexpr int64_t c = a * a; // error: overflow in constant expression [-fpermissive] Both b and c produce undefined behavior because of integer overflow. With constinit the variable is constant initialized. Which makes no guarantee about UB. With constexpr the variable is initialized with a constant expression. Constant expression guarantee not to have any UB. So here the signed integer overflow in an error. But the variable is also automatically const. So how do I best initialize a non-const variable with a constant expression? Do I have to write constexpr int64_t t = a * a; // error: overflow in constant expression [-fpermissive] constinit int64_t b = t; or constinit int64_t b = []()consteval{ return a * a; }(); // error: overflow in constant expression every time?
This is related to CWG issue 2543. As it stands currently, because the compiler is allowed to replace any dynamic initialization with static initialization if it can and because constinit is only specified to enforce "no dynamic initialization", it might still allow an initializer which is not a constant expression (maybe dependent on the interpretation as discussed in the linked issue). constinit therefore reflects whether there will actually be initialization at runtime (which is relevant to avoiding dynamic initialization order issues). It does not necessarily reflect whether the initializer is a constant expression. As stated in the issue description, this is practically not really implementable though because the dynamic/static initialization choice is made too late in the compilation process to always make constinit reflect it properly. With one possible resolution of the issue, the specification of constinit might be changed to actually require the variable to be constant-initialized instead of just requiring that there is no dynamic initialization. If that was the resolution taken, then your first example for the initialization of b would also require the compiler to diagnose the UB and all of the other solutions would become obsolete. The issue description doesn't seem to really favor any direction though. For the current situation (and if the resolution is taken in another direction), an alternative to the solutions you gave is: template<typename T> consteval auto force_compiletime(T&& t) { return std::forward<T>(t); } or template<typename To, typename T> consteval To force_compiletime2(T&& t) { return std::forward<T>(t); } and then constinit auto t = force_compiletime(static_cast<int64_t>(a * a)); or constinit auto t = force_compiletime2<int64_t>(a * a); Note that you need to include the target type in this way in the initializer, otherwise any potentially UB in the conversion will not be diagnosed. If you don't care about that constinit int64_t t = force_compiletime(a * a); would also be fine. Technically the solution with the consteval lambda from your question is ill-formed, no diagnostic required, because the lambda is marked consteval but can never produce a constant expression when called. But I would expect any non-malicious compiler to still diagnose such a call.
72,526,095
72,526,244
Why does inheriting constructors break aggregate initialization?
Why does inheriting constructors from a base class break aggregate initialization? For example, this works: struct MyArray : std::array<int, 2ul> {}; MyArray a{1, 2}; but this doesn't work: struct MyArray : std::array<int, 2ul> { using std::array<int, 2ul>::array; }; MyArray a{1, 2};
Since C++17, aggregates can have base classes, so that for such structures being derived from other classes/structures list initialization is allowed: struct MoreData : Data { bool done; }; MoreData y{{"test1", 6.778}, false}; In C++17 an aggregate is defined as either an array or a class type (class, struct, or union) with: no user-declared or explicit constructor no constructor inherited by a using declaration no private or protected non-static data members no virtual functions no virtual, private, or protected base classes For more details you can refer to Chapter 4 Aggregate Extensions from C++17 - The Complete Guide By Nicolai M. Josuttis
72,526,361
72,526,881
Difference between inheriting from std::iterator and explicitly typedefing its member types
I thought there are no differences, but I'm confused because while reading the draft of C++ standard, 24.5.1.1, reverse_iterator, I found that the reverse_iterator is inherited from iterator and also has explicit typedefs difference_type, pointer, and reference. template <class Iterator> class reverse_iterator : public iterator<typename iterator_traits<Iterator>::iterator_category, typename iterator_traits<Iterator>::value_type, typename iterator_traits<Iterator>::difference_type, typename iterator_traits<Iterator>::pointer, typename iterator_traits<Iterator>::reference> { public: typedef Iterator iterator_type; typedef typename iterator_traits<Iterator>::difference_type difference_type; typedef typename iterator_traits<Iterator>::reference reference; typedef typename iterator_traits<Iterator>::pointer pointer; Why is it written like this?
This has been in the standard since C++98, so it is going to be a bit hard to find some context for how it came about. Here is a just a guess: They may have wanted to inherit the iterator from std::iterator as a matter of policy to inherit all iterators from it (not sure about that). But if you were to simply copy the exposition as is and try to use it as a definition of the interface of reverse_iterator, then these typedefs are required. If you removed e.g. the typedef for difference_type, then you couldn't use it later in e.g. the declaration reverse_iterator operator+ (difference_type n) const; That is because iterator<...> is a dependent base class of the class, meaning the actual type of the base depends on a template parameter. It has a difference_type member, but members of dependent base classes cannot be named directly, since the compile can't know yet at the point of the template's definition what members the dependent base class has. They must be qualified, i.e. for a type like here you need to write typename iterator_traits<Iterator>::difference_type to access it. They probably didn't want to repeat that long thing every time they mention difference_type but still keep it proper C++ code. So they simply introduce the typedef for convenience. From the outside when referring to a reverse_iterator<...>::difference_type the typedef doesn't change anything. In terms of the interface, there isn't really any practical difference between inheriting from iterator and declaring the type aliases manually. The only difference is that you can test whether the iterator is inherited from std::iterator. And as discussed in the comments under the question, std::iterator has been deprecated in C++17 anyway and shouldn't be used anymore at all. That would also explain why only the members that are referred to later are typedef'ed and not e.g. iterator_category and value_category.
72,527,224
72,545,381
aeron 1.37 pingpong(c) test gets a slightly higher latency number compare to 1.31.2
I've been using real-logic/Aeron(c/c++ version) for almost 2 years. Recently I was thinking of upgrading Aeron from 1.31.2 to 1.37.0. But after run the pingpong test, I got a slightly higher latency number(around 0.1 us rtt) from 1.37.0. I ran the Ping on one server, and Pong on another server. I tested version by version (from 1.31.2 to 1.37.0). all the hardware and how I ran the pingpong are exactly the same, the only differences is the Aeron version. Here are the latency number(warmup 10,000, message 1,000,000): 1.31.2 -> 7.4452 mean us rtt 1.32.0 -> 7.4886 mean us rtt 1.33.0 -> 7.5054 mean us rtt 1.34.0 -> 7.5145 mean us rtt 1.35.0 -> 7.5459 mean us rtt 1.36.0 -> 7.5297 mean us rtt 1.37.0 -> 7.5462 mean us rtt Anybody knows if I did something wrong, or has anyone experienced the same thing? is it possible to upgrade the version to 1.37.0 and keep latency number as good as 1.31.2?
Aeron 1.38.2 has some significant changes which improve the performance.
72,527,510
72,528,242
Why does each instantiation of a lambda function result in a unique type?
Recently I asked a question about some code I had which was causing my compiler to run out of heap space. This code contained a recursive template function which was being passed a lambda function. Each instantiation of the template function caused (via the recursive call) another instantiation of the same template function with it's lambda function parameter. It was explained that each instantiation of the lambda function results in a unique type, so an infinite loop of instantiations results and the compiler runs out of heap. Note that the logic of the program is such that there would be no infinite loop at runtime. Here's an example of the code, this code does not compile on any of the major compilers. This code is a heavily cut down version of my real code, it's just for illustrative purposes. struct Null { template <typename SK> static int match(int n, SK sk) { return 0; } }; template <typename T> struct Repetition { template <typename SK> static int match(int n, SK sk) { return T::match(0, [n]() { return match(0, [n](){ return n; }); }); } }; int main() { using Test = Repetition<Null>; Test::match(0, [](){ return 0; }); } When this was explained it occurred to me that I could break the infinite loop by using a functor instead of a lambda function, since each instantiation of a the functor would not be a unique type. Here's that code, this compiles fine struct Null { template <typename SK> static int match(int n, SK sk) { return 0; } }; template <typename T> struct Repetition { template <typename SK> static int match(int n, SK sk) { return T::match(0, [n]() { return match(0, RepetitionSK<T>(n)); }); } }; template <typename T> struct RepetitionSK { RepetitionSK(int n) : n(n) {} int operator()() { return n; } int n; }; int main() { using Test = Repetition<Null>; Test::match(0, [](){ return 0; }); } EDIT [=] captures have been replaced by the more explicit [n] My question is that why do lambda functions behave this way? The lambda functions in Repetition::match do not depend the template parameter SK in any way. What's the benefit in having each instantiation of a lambda function result in a unique type? Another question, is it possible to write this code using only lambda functions, no functors or other auxiliary classes?
The question is more easily answered by considering the opposite. If it were not true, then some lambda's would have the same type. Furthermore, the Standard should then say which lambda's have the same type, and which lambda's have distinct types. Note that with "type" we mean more than just the signature of operator(). Lambda's have real type, e.g. they've got a sizeof (which has to include the captured state). For that reason, you can't just define the type in terms of tokens; the token T may be the same but the meaning varies across instantiations. This idea isn't entirely unique; non-inline functions are also unique even if they contain the exact same tokens (but then the function type will be the same - the correspondence isn't exact. And functions don't have a sizeof)
72,527,536
72,527,741
AND Operation for -1
While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement. It turns out that this is the AND (&&) operation of -1 and natural numbers. I don't know why the value 1 is printed in the same code below. I ran direct calculations such as 1's complement and 2's complement, but no 1 came out. #include <iostream> using namespace std; int main() { int a = 10; int b = -1; int c = a && b; printf("test = %d",c); return 0; }
The expression a && b is a bool type and is either true or false: it is true if and only if both a and b are non-zero, and false otherwise. As your question mentions complementing schemes (note that from C++20, an int is always 2's complement), -0 and +0 are both zero for the purpose of &&. When assigned to the int type c, that bool type is converted implicitly to either 0 (if false) or 1 (if true). (In C the analysis is similar except that a && b is an int type, and the implicit conversion therefore does not take place.)
72,527,627
72,528,716
Updating map values in place
How could I simplify this code to update the int value in the map in place? Basically I want to leave the exceeds unchanged (which is the bool) and just update the int value. std::map<OrderInfo, std::pair<int, bool>> ncpOrders; int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) { auto it = ncpOrders.find(ordInfo); const bool firstTimeProcessing = it == ncpOrders.end(); auto v = it->second; const int newAttempts = (firstTimeProcessing ? 0 : v.first) + 1; const bool exceeds = firstTimeProcessing ? false : v.second; ncpOrders[ordInfo] = std::pair(newAttempts, exceeds); return newAttempts; }
You make this over-complicated. Note that default construction of std::pair<int, bool> meets your requirement, so you can just do: std::map<OrderInfo, std::pair<int, bool>> ncpOrders; int NotCompletelyProcessedOrders::IncAttempts(OrderInfo& ordInfo) { return ++ncpOrders[ordInfo].first; } and outcome should be exact the same. https://godbolt.org/z/c1Ghsb4Ps
72,527,822
72,528,027
Why is the address of the same pointer different?
I was trying linked list on C++ and when I try to print the data of the list, it gives funny result which tells me that the list is null. When I print the address of the variable in main and print the address of the parameter of the same variable in the function, it gives different results. Could anyone please explain it for me, thank you! Here is the code: #include <iostream> using namespace std; typedef struct link_node{ int data; link_node* next; }; void iter(link_node* head){ link_node* cur = head; cout<<"The address of head in function: "<<&head<<endl; while(cur!=NULL){ cur = cur->next; cout<<cur->data<<' '; } } link_node *create(int a){ link_node* head; link_node* cur; head =(link_node*) malloc(sizeof(link_node)); cur = head; for(int i=a;i<a+10;i+=2){ link_node * node = (link_node*) malloc(sizeof(link_node)); node->data = i; cur->next = node; cur = node; } cur->next = NULL; return head; } int main(){ link_node* head_1 = create(0); link_node* head_2 = create(1); link_node* result = (link_node*) malloc(sizeof(link_node)); cout<<"The address of head_1: "<<&head_1<<endl; iter(head_1); return 0; } And here is the output of the program: The address of head_1: 0x61ff04 The address of head in function: 0x61fef0 0 2 4 6 8 Thanks!
head and head_1 are two different variables so they have two different addresses. But the values of those variables are also addresses (or pointers) and those values are the same. When you are dealing with pointers it's easy to get the address of a variable and the value of a variable mixed up because they are both pointers (but different pointer types). Put it another way, all variables have addresses, but only pointer variables have values which are also addresses. Try this code instead cout<<"The value of the head pointer: "<<head<<endl; cout<<"The value of the head_1 pointer: "<<head_1<<endl;
72,528,728
72,590,334
Bazel Android c++_shared/c++_static issues
We have a project that uses a library that is built on top of Google's Mediapipe, which is built using the Bazel build system. The project itself is an Android Native Library, built using Gradle with CMake externalNativeBuild { cmake { cppFlags "-std=c++17 -fopenmp -static-openmp -fexceptions -frtti -Wl,-s -Wno-unused-command-line-argument" arguments "-DANDROID_STL=c++_shared", "-DOpenCV_DIR=${opencvDir}", "-DANDROID_ARM_NEON=TRUE" } } So we end up with 2 (or more later, also dependent on OpenCV for example) shared object libraries - the actual SDK & the Mediapipe project. We're seeing issues that are similar to this, which lead me to look into the runtime part of our project. E/libc++abi: terminating with uncaught exception of type std::bad_cast: std::bad_cast I saw this comment on that issue thread, and adding System.loadLibrary("c++_shared"); Solved the crash. However, this is not a practical solution as the project we're building would provide a native SDK in the form of multiple .so files and I wouldn't want to force our clients to have to explicitly load the shared runtime library before using our library. The gradle library has "-DANDROID_STL=c++_shared" flag, so this is using the shared one, but I couldn't find any way to compile Mediapipe (with Bazel) using c++_shared. I couldn't find any reference to using shared runtime when compiling Bazel projects (except for this, which isn't exactly relevant and the solution didn't help me) We might be able to work around this by setting -DANDROID_STL=c++_static, but this has other issues, mainly, it violates Android's guidelines for using multiple shared libraries, though it might be possible for for middleware vendors So the question is, Is it possible to build Mediapipe (or any other Bazel based) using c++_shared Android STL If not, are there any other options to solve the runtime conflicts Is it even a runtime conflict or something else?
I managed to get it working as suggested by using c++_static on all of our shared objects (SDK, Mediapipe, OpenCV and others)
72,529,160
72,529,204
Create copy of self in base destructor
I want to write a family of classes that create copies of themselves under certain conditions when getting destructed. Please see the code below #include <string> #include <iostream> bool destruct = false; class Base; Base* copy; class Base { public: virtual ~Base() { if (!destruct) { destruct = true; copy = nullptr; /* How to modify this line? */ std::cout << "Copying" << std::endl; } else { std::cout << "Destructing" << std::endl; } } }; class Derived : public Base { public: Derived(const std::string& name) : name(name) {} std::string name; }; int main() { { Derived d("hello"); } std::cout << dynamic_cast<Derived*>(copy)->name << std::endl; delete copy; return 0; } How do I need to change the line copy = nullptr; such that it performs a full copy of this and the output becomes as shown below? Copying hello Destructing
You can't. By the time the base destructor runs, the derived destructor has already run and destroyed information that the copying would need to preserve. You need to change your approach.
72,529,167
72,529,206
error: redefinition of polymorphic class with a pointer in constructor
i'm curretly trying to make a game of battleship in c++ and i am in the procces of coding three cpu levels with polymorphism,targetet board object is passed as a pointer into constructor and it works up until i try to make a drived class and i keep receiving this error : error: redefinition of 'cpu_medium::cpu_medium(board&)' sample of cpu_battleships.h: #ifndef CPU_BATTLESHIPS_H #define CPU_BATTLESHIPS_H #include "board.h" class cpu_easy { public: cpu_easy(board &e); virtual ~cpu_easy(); protected: board* enemy; }; class cpu_medium : public cpu_easy { public: cpu_medium(board &e):cpu_easy(e){}; }; #endif // CPU_BATTLESHIPS_H sample of cpu_battleships.cpp #include "cpu_battleships.h" #include "board.h" #include <cstdlib> using namespace std; cpu_easy::cpu_easy(board &e) { enemy=&e; } cpu_medium::cpu_medium(board &e):cpu_easy(e){} { }
You define cpu_medium::cpu_medium(board &e) twice, exactly as the error message says. In cpu_battleships.h change cpu_medium(board &e):cpu_easy(e){}; to cpu_medium(board &e); That way the constructor is only defined in cpu_battleships.cpp
72,529,411
72,548,158
Cocos 2dx 4.x. Enable C++17 in Android Studio
I am trying to learn Cocos 2dx game engine. I generated a simple project with this command: cocos new -l cpp -p com.testgame1 -d path_to_dir testgame1 Next, I try to build an android project. Everything is successful. Then I wrote a lot of code that uses C++ standard 14, 17. Example (file main.cpp): void cocos_android_app_init(JNIEnv* env) { LOGD("cocos_android_app_init"); std::string vec; std::transform(std::begin(vec), std::end(vec), std::begin(vec), [](auto& elem) { return elem; } ); appDelegate.reset(new AppDelegate()); } Here I using auto in lambda function (standart C++ 14). I enable support for the standard in the usual way for Android Studio in build.gradle: defaultConfig { applicationId "com.testgame1" minSdkVersion PROP_MIN_SDK_VERSION targetSdkVersion PROP_TARGET_SDK_VERSION versionCode 1 versionName "1.0" externalNativeBuild { cmake { targets 'MyGame' cppFlags "-std=c++17 -frtti -fexceptions -fsigned-char" arguments "-DCMAKE_FIND_ROOT_PATH=", "-DANDROID_STL=c++_static", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE" } } ndk { abiFilters = [] abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String}) } } But it doesn't have any effect. On a clean project (no Cocos 2dx game engine) everything works flawlessly. I am getting an error in Android Studio: ..\..\..\..\jni\hellocpp\main.cpp:42:72: error: 'auto' not allowed in lambda parameter NDK: 21.4.7075529 How to fix it?
In your game project folder, open up CMakeLists.txt, and add the following after the include(CocosBuildSet) statement: set(CMAKE_CXX_STANDARD 17) If you want to apply C++17 to the cocos2d engine code as well, then adding this may work: set_target_properties(cocos2d PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) Source: cocos2dx forum
72,529,929
72,531,852
Unable to compile example code from AWS SDK for C++ - Developer Guide
I am trying to upload a file using an encrypted client and i`m having a hard time setting the body of the PutObjectRequest object. I am using the sample code. PutObjectRequest putObjectRequest; putObjectRequest.WithBucket("BUCKET_NAME") .WithKey(AES_MASTER_KEY); std::shared_ptr<Aws::IOStream> input_data = Aws::MakeShared<Aws::FStream>("SampleAllocationTag", FILE_NAME, std::ios_base::in | std::ios_base::binary); putObjectRequest.SetBody(input_data); but I am getting the following error: no suitable user-defined conversion from "std::shared_ptrAws::FStream" to "std::shared_ptrAws::IOStream" exists The original code can be found at https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/aws-sdk-cpp-dg.pdf , page 180 This is the full function: #include <aws/core/Aws.h> #include <aws/core/utils/logging/LogLevel.h> #include <aws/s3/S3Client.h> #include <aws/s3-encryption/materials/SimpleEncryptionMaterials.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/s3-encryption/S3EncryptionClient.h> #include <aws/s3-encryption/CryptoConfiguration.h> #include <aws/core/utils/HashingUtils.h> #include <aws/s3/model/PutObjectRequest.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <iostream> using namespace Aws; using namespace Aws::S3::Model; bool PutObject(const Aws::String& bucketName, const Aws::String& objectName) { // Verify that the file exists. struct stat buffer; if (stat(objectName.c_str(), &buffer) == -1) { std::cout << "Error: PutObject: File '" << objectName << "' does not exist." << std::endl; return false; } Aws::Client::ClientConfiguration config; Aws::S3::S3Client s3_client(config); Aws::S3::Model::PutObjectRequest request; request.SetBucket(bucketName); //We are using the name of the file as the key for the object in the bucket. //However, this is just a string and can set according to your retrieval needs. request.SetKey(objectName); std::shared_ptr<Aws::IOStream> input_data = Aws::MakeShared<Aws::FStream>("SampleAllocationTag", objectName.c_str(), std::ios_base::in | std::ios_base::binary); request.SetBody(input_data); Aws::S3::Model::PutObjectOutcome outcome = s3_client.PutObject(request); if (outcome.IsSuccess()) { std::cout << "Added object '" << objectName << "' to bucket '" << bucketName << "'."; return true; } else { std::cout << "Error: PutObject: " << outcome.GetError().GetMessage() << std::endl; return false; } } That is the only error I get Image showing build error
As the code is missing #include <fstream> Aws::FStream (which is a typedef for std::fstream) is an incomplete type and the compiler doesn't know that std::fstream is derived from std::iostream so doesn't know how to convert from std::shared_ptr<Aws::FStream> to std::shared_ptr<Aws::IOStream>. Visual studio isn't very helpful here, clang and GCC at least tell you that std::fstream is an incomplete type: https://godbolt.org/z/Paeqj5saW
72,531,078
72,540,370
Where is code of the instantiation of C++ vector?
I have a very simple code as below, which uses a C++ vector: #include <iostream> #include <vector> using namespace std; int main() { vector<int> g1; return 0; } By coping the code to the website https://godbolt.org/, I know the generated assembly code is as below: main: stp x29, x30, [sp, -64]! mov x29, sp str x19, [sp, 16] add x0, sp, 40 bl std::vector<int, std::allocator<int> >::vector()** [complete object constructor] mov w19, 0 add x0, sp, 40 bl std::vector<int, std::allocator<int> >::~vector() [complete object destructor] mov w0, w19 ldr x19, [sp, 16] ldp x29, x30, [sp], 64 ret __static_initialization_and_destruction_0(int, int): stp x29, x30, [sp, -32]! mov x29, sp str w0, [sp, 28] str w1, [sp, 24] ldr w0, [sp, 28] cmp w0, 1 bne .L27 ldr w1, [sp, 24] mov w0, 65535 cmp w1, w0 bne .L27 adrp x0, _ZStL8__ioinit add x0, x0, :lo12:_ZStL8__ioinit bl std::ios_base::Init::Init() [complete object constructor] adrp x0, __dso_handle add x2, x0, :lo12:__dso_handle adrp x0, _ZStL8__ioinit add x1, x0, :lo12:_ZStL8__ioinit adrp x0, _ZNSt8ios_base4InitD1Ev add x0, x0, :lo12:_ZNSt8ios_base4InitD1Ev bl __cxa_atexit .L27: nop ldp x29, x30, [sp], 32 ret _GLOBAL__sub_I_main: stp x29, x30, [sp, -16]! mov x29, sp mov w1, 65535 mov w0, 1 bl __static_initialization_and_destruction_0(int, int) ldp x29, x30, [sp], 16 ret DW.ref.__gxx_personality_v0: .xword __gxx_personality_v0 Now my question is where I can find the code of std::vector<int, std::allocator >::vector(). If I define a new template class in my code as below: #include <iostream> using namespace std; template <class T, class U> class A { T x; U y; public: A() { cout << "Constructor Called" << endl; } }; int main() { A<char, char> a; A<int, double> b; return 0; } I know the code of A<char, char> and A<int, double> is generated in the object file of my own code. But for the template class and template function of C++ STL, where is the code of their instantiated object? There is in the library file of the C++ standard library, e.g. libstdc++.so, but I think the compiler will not generate the code inside that .so file. Thanks!
You are simply confused because godbolt.org doesn't show standard library functions by default in the assembly view. Click on "Filter..." and then deselect "Library functions". Then you will get the missing symbols, for example the std::vector<int> default constructor and destructor. They are not shown by default because there is usually no interest in them and there can be many library functions cluttering the output. In some instances the standard library uses explicit instantiation into the .so instead of implicit instantiation into the translation unit using the standard library template. Libstdc++ does this for std::string (which is std::basic_string<char>) if I remember correctly, but I don't think any standard library implementation does this for std::vector.
72,531,618
72,533,194
Const correctness of operator* in std::unique_ptr
Why can 'operator*' member function of std::unique_ptr be marked const (https://en.cppreference.com/w/cpp/memory/unique_ptr/operator*) while functions like 'front()', 'back()', 'operator[]' etc in std::vector not be marked const? Both are returning non-const references to the resources they are managing. The core problem is I can't understand the 1st part i.e. why we're able to mark 'operator*' as const i.e. how can the return type be 'T&' when the '*this' pointer in that function would be a const pointer (due to the function being marked const)?
The difference lies in the definition of a container. A std::vector is considered a container. This means that the objects managed by a std::vector are considered parts of the vector. The references returned from front(), back() and operator[] must be const if the vector is const. Modifying those objects will modify the vector. A std::unique_ptr, however, is not a container. The object it manages is not considered to be part of the std::unique_ptr. This means that modifying the managed object is not considered modifying the pointer. Therefore, using operator* on a pointer type will never change the pointer itself, and therefore the operation can always be considered const. std::optional may provide some helpful context to this difference. Despite having a syntax that resembles a pointer, it is effectively a container (with max_size of 1). Because it contains its managed object, its operator* must obey the same const rules that a container does.
72,531,788
72,531,885
Using iterator to initialize string, get "transposed pointer range" exception
Maybe a noob question but why these two lines: vector<char> v{"h","i"}; string s1(v.cbegin(), v.cend()); won't compile? It says "debug assertion failed, exception:transposed pointer range".
Debug assetions happen in run-time, not compile time. In any case, you should change: vector<char> v{"h","i"}; to: vector<char> v{ 'h','i' }; char literals should be enclosed with ', not ". This way your code should compile and run properly. See also @Eljay's comment above for more info how the compiler actually interpreted your current code. Side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
72,531,849
72,532,230
Why isn´t my If-Else statement working properly?
I have a project where I have to change some parametres depending on the field of rotation I want for a magnetic field generator. I am not a developer and c++ is not my program of expertice, but I need to find a way to change between two different configurations using a toggle function. I tried using an If-Else statement, but it doesn´t work. Changing the parameters manually does work, so I believe the if-else may not be loading or something. Any input would be greatly appreciated. void ParticleControlPanel::processTimer() { //original field orientation (B-field aligned with z-axis) tf::Vector3 field_orientation(0.,0.,1.); //original rotiation axis; (rotation axis aligned with x-axis) tf::Vector3 rot_axis(1.,0.,0.); rot_axis.setX(cos(azimuth_/180.*pi)); rot_axis.setY(sin(azimuth_/180.*pi)); rot_axis.setZ(0); //toggle drill and cube if (toggle_) { tf::Vector3 field_orientation(1.,0.,0.); tf::Vector3 rot_axis(0.,0.,1.); rot_axis.setX(0); rot_axis.setY(sin(azimuth_/180.*pi)); rot_axis.setZ(cos(azimuth_/180.*pi)); } else { tf::Vector3 field_orientation(0.,0.,1.); tf::Vector3 rot_axis(1.,0.,0.); rot_axis.setX(cos(azimuth_/180.*pi)); rot_axis.setY(sin(azimuth_/180.*pi)); rot_axis.setZ(0); } edit: I define the toggle_ function at the beginning of the code. namespace mag_control { ParticleControlPanel::ParticleControlPanel(QWidget *parent) : rviz::Panel(parent), magfield_topic_("/desired_field"), magfield_grad_topic_("/desired_field_grad"), holding_lock_(false), activated_(false), controlling_(false), wobble_(false), toggle_(false), frequency_(0.00), azimuth_(0.0), rot_angle_(0.0), t_prev_(0.0), pi(std::acos(-1)), gradient_(0.,0.,0.), position_(0.,0.,0.), z_control_(false), gradient_z_(0.0), thresh_bin_(0), thresh_hough_(0), config_("demo.yaml") { Edit: I hear that the variables field_orientation and rot_axis are not the same inside of the if-else and below it. How can I change this? Again, this is something I have not a lot experience with, but I need to fix because of work circunstances. void ParticleControlPanel::processCheckboxToggle(int value) { if(value){ toggle_ = true; } else { toggle_ = false; } }
Variables field_orientation and rot_axis you declare inside if or else blocks are completely unrelated to variables field_orientation and rot_axis you declared before if statement. Because they share names, variables inside smaller scopes shadow the names in the outer scope, and you can only access variables from smaller scope. Also, since these are variables with automatic lifetime, their are destroyed when their scope ends (in this case - when } closing if block is reached). See a simplified example of your code: #include <iostream> int main(void) { int myVar = 5; std::cout << "myVar before if: " << myVar << '\n'; if (true) { int myVar = 13; // a new myVar, completely different than the first myVar std::cout << "myVar inside if: " << myVar << '\n'; } // myVar from inside if is gone here std::cout << "myVar after if: " << myVar << '\n'; } The output is (see it online) myVar before if: 5 myVar inside if: 13 myVar after if: 5 If you want to change the values of original field_orientation and rot_axis, do not declare new variables in if scope, simply refer to those variables: void ParticleControlPanel::processTimer() { //original field orientation (B-field aligned with z-axis) tf::Vector3 field_orientation(0.,0.,1.); //original rotiation axis; (rotation axis aligned with x-axis) tf::Vector3 rot_axis(1.,0.,0.); rot_axis.setX(cos(azimuth_/180.*pi)); rot_axis.setY(sin(azimuth_/180.*pi)); rot_axis.setZ(0); //toggle drill and cube if (toggle_) { field_orientation.setX(1.); // I guess, I don't know the library you are using field_orientation.setY(0.); field_orientation.setZ(0.); rot_axis.setX(0); rot_axis.setY(sin(azimuth_/180.*pi)); rot_axis.setZ(cos(azimuth_/180.*pi)); } else { field_orientation.setX(0.); field_orientation.setY(0.); field_orientation.setZ(1.); rot_axis.setX(cos(azimuth_/180.*pi)); rot_axis.setY(sin(azimuth_/180.*pi)); rot_axis.setZ(0); }
72,532,148
72,532,247
Calling a function with parameters of vector<int> and lambda function in main() with an anonymous lambda
Question: Using the following unfinished function (finish it), call it in the main function with an anonymous lambda function as a parameter and print all numbers that are NOT divisible by 2, 3 and 5. vector<int> izdvoji(vector<int>& x, function<bool(int)> kriterij); int main() { vector<int> brojevi = { 1, 4, 5, 7, 3, 6, 12, 65, 32, 8, 87, 55, 23, 22, 1, 1, 433, 66, 7, 433, 3, 32, 76, 8, 72, 256, 42 }; vector<int> rez = izdvoji(brojevi, /*lambda function*/); for (int i = 0; i < rez.size(); i++) cout << rez[i] << " "; //output: 1 7 23 1 1 433 7 433 return 0; } My Answer: #include <iostream> #include <vector> #include <string> #include <map> #include <iterator> #include <functional> using namespace std; //2 3 5 djeljivvost vector<int> izdvoji(vector<int>& x, function<bool(int)> kriterij) { vector<int> rez; for (int i = 0; i < x.size(); i++) { if (kriterij(x[i])) { rez.push_back(x[i]); } } return rez; } int main() { vector<int> brojevi = { 1, 4, 5, 7, 3, 6, 12, 65, 32, 8, 87, 55, 23, 22, 1, 1, 433, 66, 7, 433, 3, 32, 76, 8, 72, 256, 42 }; vector<int> rez = izdvoji(brojevi, [](int x)->bool { return !(x % 2 || x % 3 || x % 5); }); for (int i = 0; i < rez.size(); i++) cout << rez[i] << " "; //output: 1 7 23 1 1 433 7 433 return 0; } When I compile it, it says there are no issues found, but also it informs me from the build output (VS 2019) that there is a signed/unsigned mismatch in my for loops, and it doesn't print anything. I have no clue why.
Your condition is wrong. Try for example 31, which is not divisible by 2, 3 or 5: return !(31 % 2 || 31 % 3 || 31 % 5); return !( 1 || 1 || 1 ); return !( true ); return false; Check divisiblity by x % n == 0: return !(x % 2 == 0 || x % 3 == 0 || x % 5 == 0); For the warning about unsigned vs signed comparison, you need to consider that size() returns an unsigned value. Use size_t as the type of the loop counter.
72,532,225
72,532,358
Passing Class Objects as Arguments of Classes
I have been working on a tetris game and I have to pass an object into a function as its argument to use the object inside the function. I made this function and it should be able to control the Board object from Main.cpp to update the coordinate. void BlockInfo::send(Board board) { for (int i = y; i < y + 4; i++) { for (int j = x; j < x + 4; j++) { if (block[blockType][rotation][j][i]) { board.setBoard(j, i, true); } } } } Main.cpp Board board; while (true) { Board board; BlockInfo blcInf; blcInf.send(board); board.draw(); } This should have drawn a tetris block in the terminal but it didn't. So I tried changing the send function to this: void BlockInfo::send(Board board) { board.setBoard(3, 3, true); } This should have drawn a single block at (3,3) in the console, but it didn't. Assuming that everything except this works properly (I checked and I am pretty sure), what is the problem here? If you think there are no problems in this part, what do you think might be the problem?
With void BlockInfo::send(Board board) and blcInf.send(board); you always make a copy of board and inside send you modify that copy - but not the original board from main. You need to pass the Board by reference, not by value. With void BlockInfo::send(Board& board) you are not making a copy but a reference. So send is working directly on the passed board from main and you will see the change when you call draw.
72,532,530
72,532,574
Can't update values of members when constructor is invoked
I've created two classes, 'Cylinder' and 'random', with 'Cylinder' publicly inherited by 'random'. So I created an object of 'random' and tried to change values of member variables of "Cylinder'. Couldn't get it to work #include "constants.h" #include<iostream> class Cylinder{ public: double r,h; public: Cylinder(){ r = 2.0; h = 2.0; std::cout<<"\nConstructor Invoked!"; }; Cylinder(double radius, double height){ r= radius; h = height; std::cout<<"Constructor Invoked!"; }; void display(){ std::cout<<"\n"<<"Radius:"<<r<<"\nHeight:"<<h; } ~Cylinder(){ std::cout<<"\nDestructor Invoked!"; } }; class random : public Cylinder { public: random() = default; random(double r,double h) { Cylinder(r,h); } void disp_cy() { display(); } }; Main file #include "cylinder.h" #include<iostream> int main() { random R1(10.0,10.0); R1.disp_cy(); } Output: Constructor Invoked!Constructor Invoked! Destructor Invoked! Radius:2 Height:2 Destructor Invoked!
You need to delegate to the superclass constructor in the member initializer list for your constructor, not in the body of the constructor itself: random(double r,double h) : Cylinder(r, h) {} As is, the default superclass constructor got invoked implicitly (thus seeing default values on your random instance), and the Cylinder(r, h) in the body of the constructor just created a brand new Cylinder that was immediately thrown away.
72,533,139
72,572,297
Libtorch errors when used with QT, OpenCV and Point Cloud Library
I am trying to use libtorch, qt widgets, point cloud library(pcl) and opencv in a project. For this project I am using cmake lists. The issue is that when I am using all four libraries together, errors are thrown by libtorch. If I use libtorch, opencv and qt everything works fine, also if I use pcl qt and opencv everything also works well. The errors that I get are listed bellow: /libtorch/include/torch/csrc/jit/api/object.h: In member function ‘size_t torch::jit::Object::num_slots() const’: /libtorch/include/torch/csrc/jit/api/object.h:173:28: error: expected unqualified-id before ‘(’ token 173 return _ivalue()->slots().size(); /libtorch/include/ATen/core/ivalue_inl.h: In member function ‘c10::intrusive_ptr c10::IValue::toCustomClass() const &’: /libtorch/include/ATen/core/ivalue_inl.h:1642:3: error: expected unqualified-id before ‘(’ token 1642 | TORCH_CHECK( /libtorch/include/ATen/core/ivalue_inl.h: In member function ‘c10::intrusive_ptr c10::IValue::toCustomClass() &&’: /libtorch/include/ATen/core/ivalue_inl.h:1624:3: error: expected unqualified-id before ‘(’ token 1624 | TORCH_CHECK( | ^~~~~~~~~~~ /libtorch/include/ATen/core/ivalue_inl.h:1419:36: error: expected unqualified-id before ‘)’ token 1419 | const std::vector& slots() const { Does anyone know why libtorch is throwing these errors?
After many tries I have managed to bind the four libraries together and make them work. There were many issues that had to be solved even after solving the error mentioned in the original question. I will describe in short what I did such that if anyone will ever face this issue to know how to solve it. There are many conflicts between qt pcl and libtorch due to methods or structures with the same names. First I removed all using namespace someLibrary; from the code and used the scope resolution operator in front of every function or structure called from a certain library(i.e. someLibrary::some_function()). I added all the contents related to libtorch in a shared library. Here one should note that all the libtorch files and directories that were mentioned in the CMakeLists.txt file of the library have to be present in the CMakeLists.txt of the main project file. The guards mentioned bellow have to be added in the files where libtorch is used. These will remove the errors like the ones from the original question. The errors are caused by qt slots conflicting with libtorch structures with the same name. #undef slots #include <torch/torch.h> #include <torch/script.h> #define slots Q_SLOTS All the deep learning operations that were related to libtorch were added in a class and each of them had the static keyword in front (so I made them static functions). The operations were then called like any other static method from a class : "className::libtorchOperation()". I had to add the ${TORCH_INCLUDE_DIRS} to the include directories of the CMakeLists files and also had to add the following line in the main CMakeLists.txt set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -luuid"). One link that helped is Here And that was about it...It fixed the errors from the original question and made the four frameworks function together.
72,533,147
72,535,012
Get image from a fingerprint using Python and Ctypes
I'm trying to get an image from the fingerprint scanner Futronic FS88h, here is what I've been doing until now. from ctypes import windll, wintypes from os import device_encoding import ctypes lib = ctypes.WinDLL('ftrScanAPI.dll') FTRHANDLE = ctypes.c_void_p # classes class FTRSCAN_DEVICE_INFO(ctypes.Structure): _fields_ = [ ("dwStructSize", FTR_DWORD), ("byDeviceCompatibility", FTR_BYTE), ("wPixelSizeX", FTR_WORD), ("wPixelSizeY", FTR_WORD) ] PFTRSCAN_DEVICE_INFO = ctypes.POINTER(FTRSCAN_DEVICE_INFO) class FTRSCAN_FAKE_REPLICA_PARAMETERS(ctypes.Structure): _fields_ = [ ("bCalculated", FTR_BOOL), ("nCalculatedSum1", ctypes.c_int), ("nCalculatedSumFuzzy", ctypes.c_int), ("nCalculatedSumEmpty", ctypes.c_int), ("nCalculatedSum2", ctypes.c_int), ("dblCalculatedTremor", ctypes.c_double), ("dblCalculatedValue", ctypes.c_double), ] PFTRSCAN_FAKE_REPLICA_PARAMETERS = ctypes.POINTER(FTRSCAN_FAKE_REPLICA_PARAMETERS) fake_replica = FTRSCAN_FAKE_REPLICA_PARAMETERS(0, 0, 0, 0, 0, 0, 0) class FTRSCAN_FRAME_PARAMETERS(ctypes.Structure): _fields_ = [ ("nContrastOnDose2", ctypes.c_int), ("nContrastOnDose4", ctypes.c_int), ("nDose", ctypes.c_int), ("nBrightnessOnDose1", ctypes.c_int), ("nBrightnessOnDose2", ctypes.c_int), ("nBrightnessOnDose3", ctypes.c_int), ("nBrightnessOnDose4", ctypes.c_int), ("FakeReplicaParams", FTRSCAN_FAKE_REPLICA_PARAMETERS), ] PFTRSCAN_FRAME_PARAMETERS = ctypes.POINTER(FTRSCAN_FRAME_PARAMETERS) if __name__ == "__main__": lib.ftrScanOpenDevice.argtypes = [] lib.ftrScanOpenDevice.restype = FTRHANDLE h_device = lib.ftrScanOpenDevice() frame_parameters = FTRSCAN_FRAME_PARAMETERS(0, 0, 0, 0, 0, 0, 0, fake_replica, 0) lib.ftrScanIsFingerPresent.argtypes = [FTRHANDLE, PFTRSCAN_FRAME_PARAMETERS] lib.ftrScanIsFingerPresent.restype = FTR_BOOL if lib.ftrScanIsFingerPresent(h_device, ctypes.byref(frame_parameters)): print("\nFinger parameters") print(f"1: {frame_parameters.nContrastOnDose2}") print(f"2: {frame_parameters.nContrastOnDose4}") print(f"3: {frame_parameters.nDose}") print(f"4: {frame_parameters.nBrightnessOnDose1}") print(f"5: {frame_parameters.nBrightnessOnDose2}") print(f"6: {frame_parameters.nBrightnessOnDose3}") print(f"7: {frame_parameters.nBrightnessOnDose4}\n") With this I'm able to check if the finger is present and it actually retrieves some info, but I need to get the image from the device and I'm not quite sure how to do it, I've been trying this: lib.ftrScanGetImage.argtypes = [FTRHANDLE] lib.ftrScanGetImage.restypes = wintypes.BOOL get_image = lib.ftrScanGetImage(h_device) print(get_image) But this only returns a bool, I'd love to know how to get the image or some data that I can convert into a image. This is the .dll that I'm using. ftrScanAPI.h I've found this piece of code that gets the image, however, I don't know how I should port it to Python, here's the piece of code from this question. int getRawImage(unsigned char *pBuffer); int writeJPEGBFile(unsigned char *idata, char *ofile); int main(int argc, char** argv) { unsigned char *rawData; // Removed the NULL assignment char filename[MAXPATHLEN] = "/home/user/tst/img.jpg"; // Set the size of rawData - loadImageSize() sets the value of the ImageSize class variable. loadImageSize(); rawData = (unsigned char *) malloc(ImageSize.nImageSize); getRawImage(rawData); // This works now writeJPEGBFile(rawData, filename); free(rawData); return 0; } int getRawImage(unsigned char *pBuffer) { void *hDevice; hDevice = scanOpenDevice(); // Removed code for simplification scanGetFrame(hDevice, pBuffer, NULL) scanCloseDevice(hDevice); return 0; } int writeJPEGBFile(unsigned char *idata, char *ofile) { // JPEG code goes here return 0; }
There's a C# example here. Using it as a reference: # Relevant definitions from the library header: # #define FTR_API_PREFIX # #define FTR_API __stdcall # # typedef void* FTRHANDLE; # typedef void* FTR_PVOID; # typedef int FTR_BOOL; # # typedef struct # { # int nWidth; # int nHeight; # int nImageSize; # } FTRSCAN_IMAGE_SIZE, *PFTRSCAN_IMAGE_SIZE; # # FTR_API_PREFIX FTRHANDLE FTR_API ftrScanOpenDevice(); # FTR_API_PREFIX void FTR_API ftrScanCloseDevice( FTRHANDLE ftrHandle ); # FTR_API_PREFIX FTR_BOOL FTR_API ftrScanGetImageSize( FTRHANDLE ftrHandle, PFTRSCAN_IMAGE_SIZE pImageSize ); # FTR_API_PREFIX FTR_BOOL FTR_API ftrScanGetImage( FTRHANDLE ftrHandle, int nDose, FTR_PVOID pBuffer ); import ctypes as ct # A type-safe handle class FTRHANDLE(ct.c_void_p): pass class FTRSCAN_IMAGE_SIZE(ct.Structure): _fields_ = (('nWidth', ct.c_int), ('nHeight', ct.c_int), ('nImageSize', ct.c_int)) PFTRSCAN_IMAGE_SIZE = ct.POINTER(FTRSCAN_IMAGE_SIZE) lib = ct.WinDLL('./ftrScanAPI') # due to __stdcall, only matters if 32-bit Python and DLL lib.ftrScanOpenDevice.argtypes = () lib.ftrScanOpenDevice.restype = FTRHANDLE lib.ftrScanCloseDevice.argtypes = FTRHANDLE, lib.ftrScanCloseDevice.restype = None lib.ftrScanGetImageSize.argtypes = FTRHANDLE, PFTRSCAN_IMAGE_SIZE lib.ftrScanGetImageSize.restype = ct.c_int lib.ftrScanGetImage.argtypes = FTRHANDLE, ct.c_int, ct.c_void_p lib.ftrScanGetImage.restype = ct.c_int handle = lib.ftrScanOpenDevice() try: size = FTRSCAN_IMAGE_SIZE() # allocate output parameter storage if not lib.ftrScanGetImageSize(handle, ct.byref(size)): raise RuntimeError('get size failed') NDos = 4 # I don't know what this parameter means, from C# example buffer = ct.create_string_buffer(size.nImageSize) # storage for image if not lib.ftrScanGetImage(handle, NDos, buffer): raise RuntimeError('get image failed') # buffer contains the image data now finally: lib.ftrScanCloseDevice(handle)
72,533,385
72,533,511
Get type of instantiated unnamed struct
I'm writing an app in C++ that interfaces with some code written in C. The following is a simplified version of a struct defined in C code that I can't modify. struct event{ uint8_t type; union { struct /* WishThisHadAName */ { // ... } connect; struct { // ... } disconnect; }; }; I'm trying to be able to define functions that take a pointer to the different unnamed structs, connect, disconnect, and all the others not listed above. To look something like the following. void onConnect( struct WishThisHadAName *evt ); Is it possible to create this prototype without modifying the original C struct? Is there an easy way to create a wrapper for the unnamed structs to give them a name? Am I forced to create named structs that mirror the unnamed ones I'm trying to use? I know you can get the type of an instantiated variable with decltype but I can't figure out how I could use that or declval in order to create the function prototype I'm looking for.
Simple as using event_connect_t = decltype(event::connect);. Then you can use it as void onConnect( event_connect_t *evt );. You can't declare a compatible type, but you can just extract the existing type declaration from the definition. decltype can resolve static member references just fine.
72,533,435
72,533,531
error: zero as null pointer constant while comparing template class using spaceship operator (<=>)
Similar question: warning: zero as null pointer constant while comparing iterators - that is about comparing iterators, this question is about comoparing template classes. I was migrating c++14 codebase to c++20. however using spaceship operator gives an warning zero as null pointer constant, which i can't figure out why it's happening and what does the error mean. used clang++14 with -std=c++20 -Werror -Wzero-as-null-pointer-constant. below is the minimal reproducible example, also runnable on godbolt. #include <compare> template<typename V, typename U> class quantity { public: using value_type = V; using unit_type = U; using this_type = quantity<value_type, unit_type>; constexpr quantity() : value_() {} constexpr quantity( const value_type &v, unit_type ) : value_( v ) {} constexpr auto operator<=>( const this_type &rhs ) const = default; private: value_type value_; }; class energy_in_joule_tag{}; using energy = quantity<int, energy_in_joule_tag>; int main() { const energy lo = energy(0, energy::unit_type{} ); const energy hi = energy(1000, energy::unit_type{} ); energy out = energy(20, energy::unit_type{} ); if( out < lo || out > hi ) { return 1; } } <source>:14:74: error: zero as null pointer constant [-Werror,-Wzero-as-null-pointer-constant] constexpr auto operator<=>( const this_type &rhs ) const = default; ^ nullptr <source>:29:13: note: in defaulted three-way comparison operator for 'quantity<int, energy_in_joule_tag>' first required here if( out < lo || out > hi ) { ^ 1 error generated. Compiler returned: 1 this is the entirity of the error message.
Here's a more minimal example: #include <compare> struct quantity { int i; constexpr auto operator<=>( const quantity& ) const = default; }; bool f(quantity a, quantity b) { return a < b; } What's actually happening here is that a < b evalutes as (a <=> b) < 0. The way that comparison categories are specified is that they can only be compared to specifically the literal 0. The only way you can really implement that in C++ is with some unspecified function pointer type - which means that 0 is really a null pointer constant, which this warning flags as saying you shouldn't use it. But of course, you're not the one using 0, the language is. And it's not really a null pointer constant, it's kind of a hack to make the specification work and a hypothetical future language future might obviate the need for having to implement this with a pointer type. The point is: your code is fine, this is a bad warning. Reported an issue.
72,533,601
72,534,455
Conditionally compile function if `std::optional` exists
I am having a mixed C++14/C++17 codebase and I want to enable a function isEmpty only if I am having std::optional at hand. So, I tried SFINAE: template <typename T, typename int_<decltype(std::nullopt)>::type = 0> inline bool isEmpty(const std::optional<T>& v) { return !v; } However, that doesn't work. How can I conditionally compile isEmpty if std::optional is there?
If your compiler is recent enough (e.g. GCC >= 9.1 or Clang >= 9.0.0), you may include header <version> and conditionally compile your function template if macro __cpp_lib_optional is defined: #include <version> // provides, among others, __cpp_lib_optional #ifdef __cpp_lib_optional template <typename T> inline bool isEmpty(const std::optional<T>& v) { return !v; } #endif This way, isEmpty will only be compiled if you're in -std=c++17 mode (or higher).
72,533,614
72,544,035
C++20 import modules with dot notation from main file in Clang
In a C++20 project built with Clang (stdlib=libc++), I have the next structure: testing_core.cppm export module testing.core; export namespace testing { class TestSuite { public: static constexpr const char* var [] = { "Hi, constexpr!" }; }; void say_hello(); } clang++ -c --std=c++20 -stdlib=libc++ -fmodules -fimplicit-modules -fbuiltin-module-map -fimplicit-module-maps -Xclang -emit-module-interface --precompile -o ./out/modules/interfaces/testing_core.pcm ./zero/ifc/testing/testing_core.cppm testing_core.cpp module testing.core; import <iostream>; namespace testing { void say_hello() { std::cout << "Hi, from the testing module!" << std::endl; } } clang++ -c --std=c++20 -stdlib=libc++ -fmodules -fimplicit-modules -fbuiltin-module-map -fimplicit-module-maps zero/src/testing_core.cpp -o ./out/modules/implementations/testing_core.o -fmodule-file=./out/modules/interfaces/testing_core.pcm // Driver code main.cpp import testing.core; import <iostream>; using namespace zero; int main() { testing::say_hello(); // Prints const char* first element memory address std::cout << testingTestSuite::var << std::endl; // Prints the deferenced value of the const char* constexpr std::cout << *testingTestSuite::var << std::endl; return 0; } clang++ --std=c++20 -stdlib=libc++ -fmodules -fimplicit-modules -fbuiltin-module-map -fimplicit-module-maps -o ./out/zero.exe main.cpp ./out/modules/interfaces/testing_core.pcm ./out/modules/interfaces/zero.pcm ./out/modules/interfaces/testing.pcm ./out/modules/implementations/testing.o ./out/modules/implementations/testing_core.o -fprebuilt-module-path=./out/modules/interfaces The error: main.cpp:3:8: fatal error: module 'testing.core' not found import testing.core; ~~~~~~~^~~~~~~ 1 error generated. I am not being able of import modules from the main file if they have a dot in its identifier. I am able to import them without having a dot (import testing), when the module name is testing, not testing.core. Also, I am also able to export import testing.core from another module interface file (for ex: testing.cppm), but I can only import it on the main.cpp file as testing. This last ones makes perfect sense to me, but I got trapped thinking in why I can export import in a module interface unit a module with dots in its identifier, but I can't on a regular cpp source file. What I am missing with Clang here? Thanks. Note: Code it's compiled with Clang 14.0.4, under a Manjaro 5.13.
Solution it's pretty straightforward. In Clang, (at least in versions up to 14.0.4), you must explicitly include the -fmodule-file=<some_interface> for the module files that includes the dot notation in it's identifier. So, for the main.cpp file build process, it must include -fmodule-file=./out/modules/interfaces/testing_core.pcm in the command line arguments. Note: When an interface or implementation file depends on another module interface unit, you also must include the -fmodule-file indicating the dependency, even if the module identifier does not contains any dot in it's export module module_name.
72,533,711
72,536,213
Removing last trailing comma from the arguments of a macro
I need to remove the last trailing comma from a list of macro arguments (because they will be eventually expanded into template arguments where the trailing comma is not admitted). So I need a macro remove_trailing_comma() which called like remove_trailing_comma(arg1, arg2, arg3, ) expands to arg1, arg2, arg3. I've tried with different combinations of varargs and __VA_OPT__ but I seem to not be able to do it. For example: #define discard_trailing_comma(arg, ...) \ arg __VA_OPT__(,) discard_trailing_comma(__VA_ARGS__) discard_trailing_comma(1, 2, 3, ) does not work (with g++ 10) because expands to 1 , discard_trailing_comma(2, 3,), I do not know why (are macro not expanded recursively?) Is this possible in C++20?
You'll probably should go with @eljay's answer, but if you need to support way more arguments, here is one that supports ~2000 arguments in 22 lines and adding more lines grows that number exponentially. #define E4(...) E3(E3(E3(E3(E3(E3(E3(E3(E3(E3(__VA_ARGS__)))))))))) #define E3(...) E2(E2(E2(E2(E2(E2(E2(E2(E2(E2(__VA_ARGS__)))))))))) #define E2(...) E1(E1(E1(E1(E1(E1(E1(E1(E1(E1(__VA_ARGS__)))))))))) #define E1(...) __VA_ARGS__ #define EMPTY() #define TUPLE_AT_2(x,y,...) y #define TUPLE_TAIL(x,...) __VA_ARGS__ #define CHECK(...) TUPLE_AT_2(__VA_ARGS__,0,) #define EQ_END_END ,1 #define SCAN(...) __VA_ARGS__ #define CAT(a,b) CAT_(a,b) #define CAT_(a,b) a##b #define LOOP_() LOOP #define LOOP(x,y,...) CAT(LOOP, CHECK(EQ_END_##y))(x,y,__VA_ARGS__) #define LOOP1(x,...) (TUPLE_TAIL x) #define LOOP0(x,y,...) LOOP_ EMPTY() ()((SCAN x, y),__VA_ARGS__) #define DTC(...) E4(LOOP((), __VA_ARGS__ END)) DTC (1, 2, 3, 4, 5, 6, 7, 8, 9,) // expands to: (1, 2, 3, 4, 5, 6, 7, 8, 9) Let me try to explain this. Firstly, when LOOP is called inside E4() it can recursively call itself, which is done in LOOP0. The simplest example for this would be #define LOOP(...) __VA_ARGS__ LOOP_ EMPTY() ()(__VA_ARGS__) which repeats the argument until the recursion limit, which is bound by the nesting of E4. Understanding DEFER and OBSTRUCT macros already explains the behavior quite well, so I'll skip that part of the explanation. Now the idea is the following: We loop over every argument until we reach the last one, where we've inserted an END mark. Whilst doing that, we construct a new argument list, but this also stops when we reach the END mark. CAT(LOOP, CHECK(EQ_END_##y)) branches to LOOP1 if the argument y holds the end mark END and otherwise to LOOP0. LOOP1 appends a new argument to our argument list in x using (SCAN x, y). Since we start off with an empty argument list, we'll end up with a leading empty argument, which we can trivially remove on LOOP0. PS: This concept can be trivially extended to E5, E6, ..., although there is a larger overhead using that because once the recursion ends the preprocessor still needs to rescan the result till the recursion limit. If you want to remedy that, you can use something like the continuation machine from order-pp, which can actually terminate, but it's about 150 loc. Edit, I just revisited this and realized that using x to build up the tuple is quite inefficient, here is a version that doesn't do that: #define E4(...) E3(E3(E3(E3(E3(E3(E3(E3(E3(E3(__VA_ARGS__)))))))))) #define E3(...) E2(E2(E2(E2(E2(E2(E2(E2(E2(E2(__VA_ARGS__)))))))))) #define E2(...) E1(E1(E1(E1(E1(E1(E1(E1(E1(E1(__VA_ARGS__)))))))))) #define E1(...) __VA_ARGS__ #define EMPTY() #define FX(f,x) f(x) #define TUPLE_AT_2(x,y,...) y #define TUPLE_TAIL(x,...) __VA_ARGS__ #define CHECK(...) TUPLE_AT_2(__VA_ARGS__,0,) #define EQ_END_END ,1 #define CAT(a,b) CAT_(a,b) #define CAT_(a,b) a##b #define LOOP_() LOOP #define LOOP(x,...) CAT(LOOP, CHECK(EQ_END_##x))(x,__VA_ARGS__) #define LOOP1(x,...) #define LOOP0(x,...) LOOP_ EMPTY() ()(__VA_ARGS__),x #define DTC(...) (FX(TUPLE_TAIL,E4(LOOP(__VA_ARGS__ END)))) DTC (1, 2, 3, 4, 5, 6, 7, 8, 9,) // expands to: (1, 2, 3, 4, 5, 6, 7, 8, 9)
72,534,040
72,534,239
How to provide multiple options to link a function
I have 3 object files : main.o general.o specific.o in main.o there is a call to function : void handle(void), general.o implement a generic functionality to handle() , specific.o might or might not have an implementation to handle() , I want to specify in my cmake that "search to link handle with specific.o if fail then try with general.o" Is that possible ?
There certainly is nothing in standard C++ which allows this. For Gcc/clang toolchain you can define handle as a weak symbol in general TU with __attribute__((weak)) and as ordinary symbol in specific. Be very careful with this though, ensure that handle itself is not called in general. Because if it is, the call might be inlined before the linker sees anything, resulting in some code calling the general method, the rest specific. Link-time optimization might be actually more safe here.
72,534,240
72,534,896
C++ vector sorting and mapping from unsorted to sorted elements
I have to perform the following task. Take a std::vector<float>, sort the elements in descending order and have an indexing that maps the unsorted elements to the sorted ones. Please note that the order really matters: I need a map that, given the i-th element in the unsorted vector, tells me where this element is found in the sorted one. The vice-versa has been achieved already in a pretty smart way (through c++ lambdas) e.g., here: C++ sorting and keeping track of indexes. Nevertheless, I was not able to find an equally smart way to perform the "inverse" task. I would like to find a fast way, since this kind of mapping has to be performed many times and the vector has big size. Please find in the following a simple example of what I need to achieve and my (probably suboptimal, since it relies on std::find) solution of the problem. Is it the most fast/efficient way to perform this task? If not, are there better solutions? Example Starting vector: v = {4.5, 1.2, 3.4, 2.3} Sorted vector: v_s = {4.5, 3.4, 2.3, 1.2} What I do want: map = {0, 3, 1, 2} What I do not want: map = {0, 2, 3, 1} My solution template <typename A> std::vector<size_t> get_indices(std::vector<A> & v_unsorted, std::vector<A> & v_sorted) { std::vector<size_t> idx; for (auto const & element : v_unsorted) { typename std::vector<A>::iterator itr = std::find(v_sorted.begin(), v_sorted.end(), element); idx.push_back(std::distance(v_sorted.begin(), itr)); } return idx; } Thanks a lot for your time, cheers!
You can use the code below. My version of get_indices does the following: Create a vector of indices mapping sorted -> unsorted, using code similar to the one in the link you mentioned in your post (C++ sorting and keeping track of indexes). Then by traversing those indices once, create the sorted vector, and the final indices mapping unsorted -> sorted. The complexity is O(n * log(n)), since the sort is done in O(n * log(n)), and the final traversal is linear. The code: #include <iostream> #include <vector> #include <algorithm> #include <numeric> template <typename T> std::vector<size_t> get_indices(std::vector<T> const & v_unsorted, std::vector<T> & v_sorted) { std::vector<size_t> idx_sorted2unsorted(v_unsorted.size()); std::iota(idx_sorted2unsorted.begin(), idx_sorted2unsorted.end(), 0); // Create indices mapping (sorted -> unsorted) sorting in descending order: std::stable_sort(idx_sorted2unsorted.begin(), idx_sorted2unsorted.end(), [&v_unsorted](size_t i1, size_t i2) { return v_unsorted[i1] > v_unsorted[i2]; }); // You can use '<' for ascending order // Create final indices (unsorted -> sorted) and sorted array: std::vector<size_t> idx_unsorted2sorted(v_unsorted.size()); v_sorted.resize(v_unsorted.size()); for (size_t i = 0; i < v_unsorted.size(); ++i) { idx_unsorted2sorted[idx_sorted2unsorted[i]] = i; v_sorted[i] = v_unsorted[idx_sorted2unsorted[i]]; } return idx_unsorted2sorted; } int main() { std::vector<double> v_unsorted{ 4.5, 1.2, 3.4, 2.3 }; std::vector<double> v_sorted; std::vector<size_t> idx_unsorted2sorted = get_indices(v_unsorted, v_sorted); for (auto const & i : idx_unsorted2sorted) { std::cout << i << ", "; } return 0; } Output: 0, 3, 1, 2,
72,534,844
72,535,338
removing alphebatical reordering of key value pairs in nlohmann json
nlohmann::json payload = {{"type", "market"}, {"side", "buy"}, {"product_id",market}, {"funds", size}}; std::cout << payload.dump() << std::endl; out : {"funds":"10","product_id":"BTC-USD","side":"buy","type":"market"} As you can see json is alphabetically reordered, which I dont want... How do I solve this ? thanks in advance!
You can use nlohmann::ordered_json instead of nlohmann::json to preserve the original insertion order: nlohmann::ordered_json payload = {{"type", "market"}, {"side", "buy"}, {"product_id","market"}, {"funds", "size"}}; std::cout << payload.dump() << std::endl; Result: {"type":"market","side":"buy","product_id":"market","funds":"size"} I'd note, however, that in general, such mappings in json are inherently unordered, so if you really care about the order, this may not be the best choice for representing your data. You might be better off with (for example) an array of objects, each of which defines only a single mapping.
72,534,881
72,535,261
Macro expansion ignores some tokens in MSVC
I have some problems with macro expansion in msvc compiler. I expect the following code to be expanded to F x, which it does on gcc and clang. But msvc expands it to just F ignoring x token. What's going on here? #define S(s) s #define F() #define M() S(S(F) x) M() // expands to 'F' on msvc However, without defining F() it expands to F x on msvc too, as expected. #define S(s) s // #define F() #define M() S(S(F) x) M() // expands to 'F x' on msvc I'm using Compiler Explorer site to check this code. Compiler version is x64 msvc v19.latest.
Use /Zc:preprocessor to switch to the new, standard-conformant preprocessor. It behaves as you expect.
72,535,005
72,535,109
Lifetime extension of temporary objects: what is the full expression containing a function call?
Introduction Say there is a Container class which stores Widget objects. There is an iterator class in charge of navigating such container. This iterator class (MyIterator) takes a const-reference to a vector of Stuff in its constructor, which it needs to iterate over the right elements in the container. The code may look like this: class MyIterator { public: MyIterator( const Container& container, // Container to be navigated const std::vector<Stuff>& vec) // Parameter which controls the behaviour of the iteration : container(container) , stuffVector(vec) {} ... private: const Container& container; const std::vector<Stuff>& stuffVector; }; The problem I'm curious about the binding of rvalues to const references, and how the lifetime extensions work. While vec can be bound to a temporary rvalue, that will cause stuffVector to be a dangling reference once the rvalue's lifetime is over. So code like this, aimed to create an iterator for object myContainer is wrong: MyIterator it = {myContainer, {stuff1, stuff2, stuff3}}; // Here it.stuffVector is a dangling reference! Reading up on lifetime extension of temporary objects in cppreference I found: Whenever a reference is bound to a temporary object or to a subobject thereof, the lifetime of the temporary object is extended to match the lifetime of the reference (...) There are following exceptions to this lifetime rule: (...) a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference. The question The highlighted part leads me to this question: would this piece of code succeed in getting a filtered version of the contents of myContainer? std::vector<Widget> filteredWidgets; std::copy_if ( MyIterator{myContainer, {stuff1, stuff2, stuff3}}, MyContainer.end(), std::back_inserter(filteredWidgets), [&](Widget w) { return ...; }); The second argument is an rvalue, so there is the danger of creating a dangling reference, but my understanding of the documentation is that the rvalue's lifetime will be extended untill the end of std::copy_if, so it would be fine. Which one is it? NOTE: I am aware the problem and the design, as stated, might seem a bit strange, but it's inspired in real code I've found in the wild. I'm interested in the limits of the lifetime extension, not so much in coming up with different designs which would make the question irrelevant.
Yes, the whole std::copy_if call is the full-expression and the temporary std::vector<Stuff> will be destroyed only after the call returns. This is different from by-value function parameters. If the constructor took a std::vector<Stuff> instead of a const std::vector<Stuff>&, then it would be implementation-defined whether the object lives that long or is destroyed immediately when the constructor returns. A full-expression is one of the expressions listed in [intro.execution]/5. None of the specific cases (such as unevaluated operands, immediate invocations, etc.) apply here and so falling through, the relevant condition is: an expression that is not a subexpression of another expression and that is not otherwise part of a full-expression. The copy_if call expression is the only one in that statement to which this applies (outside of the lambda body).
72,536,308
72,536,531
C++ How can I convert a string to enum to use it in a switch?
I have a list of commands that if a user inputs then it will call separate functions. Talking to a friend he said I should use switch, which is faster and easier to read over "if, else if, else" statements. When checking how to implement this I realised that I wouldn't be able to because the input is a string and for a switch to work I would need to cast it to an enum and it seems like the most straightforward option I have is to map each of the options like below. header enum class input { min, max, avg, count, stdev, sum, var, pow }; map<string, input> inMap { { "min", input::min }, { "max", input::max }, { "avg", input::avg }, { "count", input::count }, { "stdev", input::stdev }, { "sum", input::sum }, { "var", input::var }, { "pow", input::pow } }; Is there a more accessible option to use enum where I don't have to map each value? This is very time-consuming and I'm not seeing any benefits at the moment. cpp file void test::processInput(vector<string> input) { switch (inMap[input[0]]) { case inMap::min: MIN(input); break; case inMap::max: MAX(input); break; case inMap::avg: AVG(input); break; case inMap::count: COUNT(input); break; case inMap::stdev: STDEV(input); break; case inMap::sum: SUM(input); break; case inMap::var: VAR(input); break; case inMap::pow: POW(input); break; default: std::cout << "Error, input not found" << std::endl; } } I read some posts about hashing the value instead, is this a good option? At this point wouldn't be just better to continue using if, else if, else? Thanks!
Why not have a map of string to function. Then you don't need to convert to an enum. using Action = void(std::vector<std::string>); using ActionFunc = std::function<Action>; using ActionMap = std::map<std::string, ActionFunc>; void MIN(std::vector<std::string>){} ... etc ActionMap inMap { { "min", MIN }, { "max", MAX }, { "avg", AVG }, { "count", COUNT }, { "stdev", STDDEV }, { "sum", SUM }, { "var", VAR }, { "pow", POW } }; void test::processInput(std::vector<std::string> input) // May want a ref here. { auto find = inMap.find(input[0]); if (find == inMap.end()) { std::cout << "Error, input not found" << std::endl; return; } find->second(input); }
72,536,465
72,536,725
std::transform with variant
I have two vectors: A vector of a type that acts as a union, whose type I can retrieve. The other vector is a vector of variants of another type. I want to use std::transform to do a conversion to one of my variant types. However, I receive a compile error that std::transform or rather the lambda can not deduce the return type. Here is an example: #include <variant> #include <vector> #include <algorithm> #include <stdexcept> // third party types struct fooData {}; struct barData {}; struct baz { int foo_or_bar; fooData f; barData b; fooData* asFoo() { return &f; } barData* asBar() { return &b; } }; //my types struct bar { }; struct foo { }; //converter struct converter { bar operator()(const barData& b) { return bar{}; } foo operator()(const fooData& f) { return foo{}; } }; int main() { using entry = std::variant<bar,foo>; //vector of third party type std::vector<baz> bazzs{}; //vector of my variant type std::vector<entry> target{}; std::transform(bazzs.begin(),bazzs.end(),std::back_inserter(target), [](baz& bazzer){ //both foo and bar are part of the variant, but it refuses to compile switch(bazzer.foo_or_bar) { case 0: return converter{}(*(bazzer.asBar())); case 1: return converter{}(*(bazzer.asFoo())); default: throw std::runtime_error("ERROR"); } }); } How can I make this work?
Add a trailing return type specifier to your lambda: // vvvvvvvv -- Add This [](baz& bazzer) -> entry { // ... } A lambda, like any function, has to return one single type. As it currently stands it returns different types though depending on which case gets chosen: either bar in case 0 or foo in case 1. Since not all code paths return the same type, the compiler can't decide which type the lambda should return unless you tell it.
72,536,471
72,536,949
Using Designated Initializer on member of inherited base class
I created a class Something which holds a member variable. I am able to do this, which works as intended: struct Something { bool Works; }; int main() { Something s = { .Works = false, }; } Now, I want to created a struct inherited from Something, named Something2, and want to do the same thing, but I want to be able to have access to Something::Works (which I renamed DoesntWork, since it doesn't work!): struct Something { bool DoesntWork; }; struct Something2 : public Something { bool Works; }; int main() { Something2 s2 = { .Works = true, .DoesntWork = false, }; } https://godbolt.org/z/rYT3br467 I am not looking for an alternative, I can already think of some. I am only wondering if this is possible, and if yes then how. If it is not possible, I would really like to know the low-level reason, so don't hesitate! UPDATE: Thanks to Nathan Oliver's comment, you can read: Designated initializers in C++20
C++ is much stricter when it comes to designated initializers than C. cppreference: out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the C programming language, but are not allowed in C++. C doesn't have the inheritance concept at all which makes C's version of designating (at least untill C++20) impossible. One possible, future, version would be to designate it "forward" as often done in constructors with delegating constructors. In that case, I'd expect the proper initialization to be this: Something2 s2 = { Something = { .Works = false }, .DoesntWorks = true }; That's however not part of C++ as of C++20. You can however create constructors in C++ to accommodate (part of) your needs without designated initializers: struct Something { bool DoesntWork; }; struct Something2 : public Something { Something2(bool Doesnt, bool Does) : Something{Doesnt}, Works{Does} {} bool Works; }; int main() { Something2 s2 { true, false }; } or initialize each object without user defined constructors at all: struct Something { bool DoesntWork; }; struct Something2 : public Something { bool Works; }; int main() { Something2 s2{ // You could just make it `{true}` below, but mentioning the // subobject fits the purpose of a designated initializer for clarity: Something{true}, // this must however be left unmentioned in C++20 since you can't // mix regular initializers with designated ones: false }; }
72,536,995
72,538,587
candidate template ignored: could not match 'const char' against 'const char'
I am using a sequence of string from this link: here template<typename Char, Char... Cs> struct char_sequence { static constexpr const Char c_str[] = {Cs..., 0}; }; // That template uses the extension template<typename Char, Char... Cs> constexpr auto operator"" _cs() -> char_sequence<Char, Cs...> { return {}; } Then, I would make a call : call_lib("Test"_cs); where template<char... Cs> void call_lib(char_sequence<char, Cs...> url){ const_str(url.c_str); // this gives an error } // a Class from library class const_str{ const char* const begin_; template<unsigned N> constexpr const_str(const char (&arr)[N]): begin_(arr); { } } The error when constructing the class const_str error: no matching conversion for functional-style cast from 'const char const[]' to 'const_str' const_str(url.c_str); The complainer then complains of no matching copy constructor or move constructor (This is expected since this is not the one we need for constructing it). However, the other note from the compiler is: note: candidate template ignored: could not match 'const char' against 'const char' which is referring to the template constructor template<unsigned N> constexpr const_str(const char (&arr)[N]) Why is the compiler saying that it could not match const char to const char. It sounds a bit counter intuitive. How can I solve this problem without having to edit the class const_str
Once I fixed the many typos in your code (please don't post rubbish), the fix was simple enough. Just change this: constexpr auto operator"" _cs() -> char_sequence<Cs...> { ... to this: constexpr auto operator"" _cs() -> char_sequence<Char, Cs...> { ... // ^^^^ and then it compiles. Whether it does what you want or not is another thing. I didn't check that because I don't claim to understand it. And the code is specific to gcc, note, and fails to compile if you specify -pedantic-errors as many people here recommend.
72,537,103
72,537,151
How to resolve ambiguous overload for 'operator=' in string
I am trying to create a class that can be implicity cast to a variety of different types, both primitives and custom defined classes. One of the types that I want to be able to cast to is an std::string. Below is an example class that can cast to various different types. It throws the error "error: ambiguous overload for ‘operator=’". This is because std::string has an assignment operator from a CharT which the compiler can create from an int. My question is, is it possible to have a class that can both implicity convert to an integer or a string type? class Test { public: operator double() const { return 3.141592; } operator std::int64_t() const { return -999; } operator std::uint64_t() const { return 999; } operator bool() const { return true; } operator std::string() const { return "abcd"; } }; int main(int argc, char** argv) { std::string test_str = Test(); test_str = Test(); std::cout << test_str; } Interestingly, when I assign to test_str on the same line that I define it, the compiler throws no errors because it's using the simple constructor rather than an assignment operator, but it errors on the following line. Any help would be much appreciated.
std::string has several overloaded operator=s with following parameters: std::string, const char *, char, std::initializer_list. For your code to work, the compiler needs to choose one, but at least two are potentially suitable: the std::string one; and the char one, using an implicit conversion from one of your scalar operators. Even though the latter would cause an ambiguity later on, the compiler doesn't seem to reach that point. The solution is to make a single templated conversion operator, and to restrict it to specific types with SFINAE: Then following works: template <auto V, typename, typename...> inline constexpr auto value = V; template <typename T, typename ...P> concept one_of = (std::is_same_v<T, P> || ...); class Test { public: template <one_of<int, float, std::string> T> operator T() const { if constexpr (std::is_same_v<T, int>) return 42; if constexpr (std::is_same_v<T, float>) return 42; else if constexpr (std::is_same_v<T, std::string>) return "foo"; else static_assert(value<false, T>, "This shouldn't happen."); } }; The static_assert isn't really necessary, since we already have requires. It merely provides a nicer error if you add more types to the requires and forget a branch. Note value<false, T> instead of false. Trying to put false there directly would cause some compilers to emit an error unconditionally, even if the branch is not taken (this is allowed, but not required). Using an expression dependendent on T convinces the compiler to delay the test until an actual instantiation (because for all it knows, value could be specialized to become true for some T). when I assign to test_str on the same line that I define it This is an initialization, not assignment. It calls a constructor, not operator=.
72,537,141
72,537,179
C++: Always-Throw function in conditional expression
Conditional expressions allow throw expressions as operands. I would like to have a conditional expression where one of the operands is an always-throw function, however it appears that this is not possible. #include<exception> [[ noreturn ]] void foo() { throw std::exception(); } int main() { int a = true ? 1 : throw std::exception(); int b = true ? 1 : foo(); // This will not compile } I've tried inlining foo as well, but it wouldn't compile either. The error is the same: test.cc: In function 'int main()': test.cc:9:18: error: third operand to the conditional operator is of type 'void', but the second operand is neither a throw-expression nor of type 'void' int b = true ? 1 : foo(); // This will not compile Is there a way to achieve calling that function inside the expression? My use case is a transpiler from a language to C++ and that other language supports case expressions where if no case is hit in the expression, an exception is thrown. Case expressions I'm trying to support are similar to this: http://zvon.org/other/haskell/Outputsyntax/caseQexpressions_reference.html
You can use the comma operator like so: int a = true ? 1 : (throw std::exception(), 0); int b = true ? 1 : (foo(), 0); See it working on godbolt.org.
72,537,523
72,537,681
Supporting custom hooks in existing cpp class
I am designing support for custom hooks in existing C++ class. class NotMyClass { public: void DoSomething() { // Needs custom logic here. hook_.DoSomethingCustom(); } protected: Hook hook_; int not_my_class_inner_variable_1_; Node not_my_class_inner_variable_2_; ...... More Class vars..... } class Hook { public: void DoSomethingCustom() { // Some custom logic that needs to access not_my_class_inner_variable_1_, not_my_class_inner_variable_2 etc. . } } Adding some more context here after initial comments: NotMyClass class is autogenerated and no custom logic can be added to this class. We want to be able to add custom hooks inside the autogenerated classes. So the plan was to instead pass/ingect in a Hook class that will be able to provide some custom processing. The autogenerated NotMyClass class will have hook_. DoSomethingCustom(). What's the best way to access NotMyClass member variables inside Hook ? I don't want to change the class structure(that is use inheritence) of NotMyClass due to additional constraints. Is making Hook a friend of NotMyClass a good option and then passing NotMyClass as this to Hook functions ? Thanks in advance!
The problem cannot be solved as stated, i.e., without breaking the Open-Closed-Principle (OCP), which says that "classes (and other things) should be open for extension but closed for modification." In this case, this means that you shouldn't try to both (a) leave MyClass unchanged and (b) access its private or protected members from outside. Private (or protected) signal things that are not accessed from the outside, that's literally what private (or protected) are designed for. You can circumvent this (old ways, new ways) but you shouldn't. The answer by sanitizedUser modifies MyClass, which is undesirable as per the question. A hacky but straight-forward suggestion to your problem might be to pass the fields to be modified explicitly to the method by reference: class MyClass { public: void DoSomething() { // Pass references to the fields you want to modify. hook_.DoSomethingCustom(my_class_inner_variable_1_, my_class_inner_variable_2_); } protected: Hook hook_; int my_class_inner_variable_1_; Node my_class_inner_variable_2_; } class Hook { public: void DoSomethingCustom(int &inner_variable_1, Node& inner_variable_2_) { // Use the data members. } } To signal that your Hook class explicitly is allowed to access members of MyClass, you could declare it as a friend. Example: #include <iostream> class Node {}; class MyClass; class Hook { public: void DoSomethingCustom(MyClass &m); }; class MyClass { friend Hook; // Allows the Hook class to access our members! public: MyClass(Hook h): hook_(h) {} void DoSomething() { // Pass references to the fields you want to modify. hook_.DoSomethingCustom(*this); } void print_my_class_inner_variable_1_() { std::cout << my_class_inner_variable_1_ << std::endl; } protected: Hook hook_; int my_class_inner_variable_1_; Node my_class_inner_variable_2_; }; void Hook::DoSomethingCustom(MyClass &m) { // Allowed to access private member because we are a friend! m.my_class_inner_variable_1_ = 42; } int main() { MyClass c{Hook{}}; c.print_my_class_inner_variable_1_(); c.DoSomething(); c.print_my_class_inner_variable_1_(); } Note: your whole design with this "Hook" looks very weird to me. How do you "add hooks" to this thing (which imho is one of the defining requirements for calling something a "hook")? I'm sure if you posted a lot more context, people here would suggest a very different larger-scale design.
72,537,705
72,537,802
Why don't elements from my list get erased
I have to write a function that erases an element out of the list if it's bigger than the previous element.(The previous element is the one which points to the next element before deletion) I think I've basically finished it but I don't know why it doesn't erase 5 out of my list. void deleteBigger(list<int> s){ list<int>::iterator test; for(test = s.begin(); test != s.end(); test++){ int sk1=*test; cout<<sk1<<endl; test--; int sk2=*test; cout<<sk2<<endl; if(sk1>sk2){ cout<<"Im here!\n"; s.erase(test); } test++; } } It doesn't give an error or anything it just doesn't erase. I tried to test the erase method in the main function of the program, and there it worked fine.
There are three problems with your code: Your list is passed by value, not reference. So you are changing a copy of your list and it doesn't alter the original container You try to remove an element from a list while iterating it. Edit: As @Remy Lebeau mentioned in the comments, to be more precise it's a problem because you don't update the iterator properly, but not a problem on its own. Be advised, that when you remove an element from a list, the iterator which pointed to the erased element is considered invalidated. Upon the first iteration, you decremented the iterator out of the container's bounds Summing it up, what you might want to have here looks something like this: void deleteBigger(std::list<int> &s) { using namespace std; if (s.empty()) { return; } for(auto test = next(s.cbegin()); test != s.cend(); ++test){ while ((*test > *prev(test)) && (test != s.cend())) { test = s.erase(test); } } }
72,537,928
72,538,158
Writing a custom input manipulator
I need to make a custom istream manipulator that reads 5 characters from input, then skip 5 characters from input, and does it to the end of the string. Example: string line; cin >> skipchar >> line; This is that I did, but it doesn't work for some reason. Also, it would be better, if I don't use <sstream> struct membuf : streambuf { membuf(char* begin, char* end) { this->setg(begin, begin, end); } }; istream& skipchar(istream& stream) { string temp; getline(stream, temp); char *str = new char[temp.size() + 1]; strcpy(str, temp.c_str());//get string and convert to char* char* res = new char[strlen(str)]; for (int i=0,j=0;i<strlen(str);i++) if ((i / 5) % 2 == 0) //get first 5, then 5 skip, etc res[j++] = str[i]; membuf b(res, res + strlen(res)); //copy str to buffer stream.rdbuf(&b); return stream; } int main() { string str; cout << "enter smth:\n"; cin >> skipchar >> str; cout << "entered string: " << str; return 0; }
You did not show your input, but I don't think getline() would be appropriate to use in this situation. operator>> is meant to read a single word, not a whole line. In any case, you are leaking both char[] arrays that you allocate. You need to delete[] them when you are done using them. For the str array (which FYI, you don't actually need, as you could just copy characters from the temp string directly into res instead), you can just delete[] it before exiting. But for res, the membuf would have to hold on to that pointer and delete[] it when the membuf itself is no longer being used. But, more importantly, your use of membuf is simply wrong. You are creating it as a local variable of skipchar(), so it will be destroyed when skipchar() exits, leaving the stream with a dangling pointer to an invalid object. The streambuf* pointer you assign to the stream must remain valid for the entire duration that it is assigned to the istream, which means creating the membuf object with new, and then the caller will have to remember to manually delete it at a later time (which kind of defeats the purpose of using operator>>). However, a stream manipulator really should not change the rdbuf that the stream is pointing at in the first place, since there is not a good way to restore the previous streambuf after subsequent read operations are finished (unless you define another manipulator to handle that, ie cin >> skipchar >> str >> stopskipchar;). In this situation, I would suggest a different approach. Don't make a stream manipulator that assigns a new streambuf to the stream, thus affecting all subsequent operator>> calls. Instead, make a manipulator that takes a reference to the output variable, and then reads from the stream and outputs only what is needed (similar to how standard manipulators like std::quoted and std::get_time work), eg: struct skipchars { string &str; }; istream& operator>>(istream& stream, skipchars output) { string temp; if (stream >> temp) { for (size_t i = 0; i < temp.size(); i += 10) { output.str += temp.substr(i, 5); } } return stream; } int main() { string str; cout << "enter smth:\n"; cin >> skipchars{str}; cout << "entered string: " << str; return 0; } Online Demo Alternatively: struct skipcharsHelper { string &str; }; istream& operator>>(istream& stream, skipcharsHelper output) { string temp; if (stream >> temp) { for (size_t i = 0; i < temp.size(); i += 10) { output.str += temp.substr(i, 5); } } return stream; } skipcharsHelper skipchars(string &str) { return skipcharsHelper{str}; } int main() { string str; cout << "enter smth:\n"; cin >> skipchars(str); cout << "entered string: " << str; return 0; } Online Demo
72,538,132
72,546,882
Is there a way to see what's inside a ".rodata+(memory location)" in an object file?
So I'm taking a class where I am given a single object file and need to reverse engineer it into c++ code. The command I'm told to use is "gdb assignment6_1.o" to open it in gdb, and "disass main" to see assembly code. I'm also using "objdump -dr assignment6_1.o" myself since it outputs a little more information. The problem I'm running into, is that using objdump, I can see that the program is trying to access what I believe is a variable or maybe a string, ".rodata+0x41". There are multiple .rodata's, that's just one example. Is there a command or somewhere I can look to see what that's referencing? I also have access to the "Bless" program. Below is a snippet of the disassembled code I have. a3: 48 8d 35 00 00 00 00 lea 0x0(%rip),%rsi # aa <main+0x31> a6: R_X86_64_PC32 .rodata+0x41 aa: 48 8d 3d 00 00 00 00 lea 0x0(%rip),%rdi # b1 <main+0x38> ad: R_X86_64_PC32 _ZSt4cout-0x4 b1: e8 00 00 00 00 callq b6 <main+0x3d> b2: R_X86_64_PLT32 _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc-0x4 b6: 48 8d 35 00 00 00 00 lea 0x0(%rip),%rsi # bd <main+0x44> b9: R_X86_64_PC32 .rodata+0x53 bd: 48 8d 3d 00 00 00 00 lea 0x0(%rip),%rdi # c4 <main+0x4b> c0: R_X86_64_PC32 _ZSt4cout-0x4 c4: e8 00 00 00 00 callq c9 <main+0x50> c5: R_X86_64_PLT32 _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc-0x4 c9: 48 8d 35 00 00 00 00 lea 0x0(%rip),%rsi # d0 <main+0x57> cc: R_X86_64_PC32 .rodata+0x5e d0: 48 8d 3d 00 00 00 00 lea 0x0(%rip),%rdi # d7 <main+0x5e> d3: R_X86_64_PC32 _ZSt4cout-0x4 d7: e8 00 00 00 00 callq dc <main+0x63> d8: R_X86_64_PLT32 _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc-0x4 dc: 48 8d 35 00 00 00 00 lea 0x0(%rip),%rsi # e3 <main+0x6a> df: R_X86_64_PC32 .rodata+0x6e e3: 48 8d 3d 00 00 00 00 lea 0x0(%rip),%rdi # ea <main+0x71> e6: R_X86_64_PC32 _ZSt4cout-0x4 ea: e8 00 00 00 00 callq ef <main+0x76> eb: R_X86_64_PLT32 _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc-0x4```
Is there a way to see what's inside a ".rodata+(memory location)" in an object file? Sure. Both objdump and readelf can dump contents of any section. Example: // x.c #include <stdio.h> int foo() { return printf("AA.\n") + printf("BBBB.\n"); } gcc -c x.c objdump -dr x.o ... 9: 48 8d 05 00 00 00 00 lea 0x0(%rip),%rax # 10 <foo+0x10> c: R_X86_64_PC32 .rodata-0x4 ... 1f: 48 8d 05 00 00 00 00 lea 0x0(%rip),%rax # 26 <foo+0x26> 22: R_X86_64_PC32 .rodata+0x1 ... Note that because the RIP used in these instructions is the address of the next instruction, the actual data we care about is at .rodata+0 and .rodata+5 (in your original disassembly, you care about .rodata+45, not .rodata+41). So what's there? objdump -sj.rodata x.o x.o: file format elf64-x86-64 Contents of section .rodata: 0000 41412e0a 00424242 422e0a00 AA...BBBB... or, using readelf: readelf -x .rodata x.o Hex dump of section '.rodata': 0x00000000 41412e0a 00424242 422e0a00 AA...BBBB...
72,538,291
72,538,338
What am I missing to make this int to char conversion produce the intended effect?
I am making a game in SDL2, and I've decided to add an FPS counter. The number for the counter needs to update every second, and here's how I've accomplished that bool updateFPS() { if (fpsDTime == 1) { // time between update has been one second frameCounterS++; // add an extra frame fpsTime = currentTime; // reset timer // My attempt at converting my int to a char to display char SframeCounterS[MAX_DIGITS + sizeof(char)]; std::to_chars(SframeCounterS, SframeCounterS + MAX_DIGITS, frameCounterS); // Rendering the text message = TTF_RenderText_Blended(HPusab, SframeCounterS, White); // Loading text to a variable std::cout << SframeCounterS << std::endl; // Console Debugging if (message == NULL) { std::cout << "Could not create message! " << SDL_GetError() << std::endl; return false; // code will stop running here because I used a return statement } // Error Checking Function slotEight = SDL_CreateTextureFromSurface(gRenderer, message); // Creating a texture from my surface if (slotEight == NULL) { std::cout << "Could not create Message! " << SDL_GetError() << std::endl; return false; // code will stop running here because I used a return statement } // More error checking! rslotEight.x = 30; // controls the rect's x coordinate rslotEight.y = 10; // controls the rect's y coordinte rslotEight.w = message->w; // controls the width of the rect rslotEight.h = message->h; // controls the height of the rect frameCounterS = 0; // Reset the FPS counter } The reason I am trying to convert to a char and not a string is because the TTF_RenderText method requires a char as input for the text. It does display the numbers like I want it to, but it has a bunch of garbage characters at the end. Here's my console output:
I suspect you're just seeing uninitialized bytes from SframeCounterS. You should either clear the buffer with a memset(SframeCounterS, 0, sizeof(SframeCounterS));, or work with a string, which would simplify the code as well: TTF_RenderText_Blended(HPusab, std::to_string(frameCounterS).c_str(), White);
72,538,652
72,538,665
Type mismatch when returning an int value from an int function with str parameter
I have the following functions: // Created by onur on 06/06/22. #include <iostream> #include <fstream> #include <opencv2/opencv.hpp> #include <opencv2/videoio.hpp> #include "VideoProcessing.h" VideoProcessing::VideoProcessing() = default; int VideoProcessing::getFPS(const std::string& video_path) { int FPS; //Declaring an integer variable to store the number of total frames// cv::VideoCapture cap(video_path); //Declaring an object to capture stream of frames from default camera// FPS = cap.get(cv::CAP_PROP_FPS);//Getting the total number of frames// cap.release();//Releasing the buffer memory// return FPS; } unsigned long VideoProcessing::getSize(const std::string& video_path) { std::uintmax_t size = std::filesystem::file_size(video_path); return size; } These functions return int values but they take strings as parameters. This is how I'm using them: #include <iostream> #include "src/VideoProcessing.h" int main() { VideoProcessing vid; int fps = vid.getFPS('mesh.mp4'); unsigned long size = vid.getSize('mesh.mp4'); std::cout << fps << std::endl; std::cout << size << std::endl; return 0; } But there is a red underline under 'mesh.mp4' which reads: Reference to type 'const std::string' (aka 'const basic_string<char>') could not bind to an rvalue of type 'int' My return type and the assigned variables match. Where am I going wrong?
You are using a multicharacter literal that has the type int (and conditionally supported) instead of a string literal in these calls int fps = vid.getFPS('mesh.mp4'); unsigned long size = vid.getSize('mesh.mp4'); Instead write int fps = vid.getFPS( "mesh.mp4" ); unsigned long size = vid.getSize( "mesh.mp4" );
72,538,967
72,539,477
C++ Map with customized comparator does not work correctly
Map with a customized comparator does not work as expected. Code: struct Comp { const bool operator()(const int x, const int y) const { return abs(x) < abs(y); } }; map<int, int, Comp> func(vector<int>& arr) { map<int, int, Comp> mp; for (int x : arr) { mp[x]++; } return mp; }; int main() { vector<int> arr = { 4, -2, 2, -4 }; map<int, int, Comp> res = func(arr); for (auto it : res) { cout << it.first << " -> " << it.second << endl; } return 0; } Output: -2 -> 2 4 -> 2 Expected: -4 -> 1 -2 -> 1 2 -> 1 4 -> 1 Does anyone know if C++ is wrong or my expected result is wrong?
map uses the comparator to test ordering, but also to know if two keys are equal, i.e., if comp(a,b) == false and comp(b,a) == false, then it means that the 2 keys are equal and that they should be considered the same, even though the bits in memory are different. In your case, comp(-2,2) and comp(2,-2) are both false so it considers it as a single entry. Same thing for -4 and 4. Since the two first inserted keys are 4 and -2, these are the two keys that are set in the map. And since both negative and positive keys point to the same entry, then it increments each value twice.
72,539,619
72,539,712
Is there a way to get the methods of a class if you send class as <T>?
I've the following code class Person { public: string fname, lname; string getName() { return fname + " " + lname; } }; template<class T> class A { ... }; int main() { A<Person>* a = new A<Person>(); } Since for template class A, I have T saved as Person. Is there any way I can use the methods and variable in the Person class? Like, template<class T> class A { public: A() { T* person = new T(); person->fname = "John"; person->lname = "Doe"; } }; Is there some way something like this could be done?
Have you tried? I see no problem with this code. Templates are not like Java's generics, you can use the types directly as if it was normal code. #include <string> #include <iostream> class Person{ public: std::string fname, lname; std::string getName(){ return fname + " " + lname; } }; template<class T> class A{ public: A(){ T person = T(); person.fname = "John"; person.lname = "Doe"; std::cout << person.fname << " " << person.lname << "\n"; } }; int main(){ A<Person> a = A<Person>(); } Output: John Doe Live example Remind yourself though that the template must be implemented in the header files. The compiler has to have access to implementation to instantiate the templates.
72,540,612
72,546,807
Eligible special member functions and triviality
Consider the following code: #include <type_traits> template<typename T> concept Int = std::is_same_v<T, int>; template<typename T> concept Float = std::is_same_v<T, float>; template<typename T> struct Foo { Foo() requires Int<T> = default; // #1 Foo() requires Int<T> || Float<T> = default; // #2 }; static_assert(std::is_trivial_v<Foo<float>>); For static assert to be satisfied, Foo<float> needs to be a trivial type, so, since it is a class type, be a trivial class. Thus, apart from being trivially copyable (which it is), it has to have an eligible default constructor (and all such constructors have to be trivial, class.prop#2), which is a special case of eligible special member function, defined by special#6: An eligible special member function is a special member function for which: the function is not deleted, the associated constraints ([temp.constr]), if any, are satisfied, and no special member function of the same kind is more constrained ([temp.constr.order]). Rigorously, Foo<float> does not have an eligible default constructor, because constraints of #1 are unsatisfied and for #2 there's a more constrained default constructor (#1). Thus, Foo<float> is not a trivial class. However, the code above compiles successfully on gcc, clang and msvc (godbolt). Intuitively, it probably should, but then, it seems, the third clause of the definition above should be no special member function of the same kind with satisfied associated constraints (if any) is more constrained ([temp.constr.order]) to allow #2 not to be "shadowed" by #1 (which would never be chosen during overload resolution for default constructor of Foo<float> anyway) and become eligible, making (due to being trivial and only one eligible) Foo<float> trivial. So, is my analysis correct? If so, is this a compiler bug or the wording of the aforementioned clause is imprecise and it actually implies my version of it?
So, is my analysis correct? Definitely. My intent in writing this wording in P0848 was very much that #2 is eligible - that's the one overload resolution would pick and it's not deleted, so it should be eligible. I opened a CWG issue request which is now CWG 2595.
72,541,077
72,541,172
Converting std::list<int> iterator to an CString (MFC)
Newbie in world of MFC and MS Windows C++. I am trying to populate a ComboBox dynamically. But I am not able to convert the iterator pointer to CString or an std::string. Here is my sample code: bool single_digit (const int& value) { return (value >= 60); } int numArr[] = {10,20,30,40}; int size = sizeof(numArr)/sizeof(numArr[0]); std::list<int> numList (numArr, numArr+size); numList.remove_if(single_digit); for(std::list<int>::iterator it=numList.begin(); it!=numList.end(); ++it) { std::cout << ' ' <<*it; /* std::string s2(*it); //Not sure of conversion to CString or std::string. string *pelement = &*it; */ //End goal: _ccomboBoxnumType.AddString(*it); } Can anyone please suggest any other STL to satisfy this requirement?
This is essentially asking how to convert an integer to its string representation. The simplest way to go about this is to call std::to_wstring, that provides an overload taking an int value. The following code does what you're looking for: for(std::list<int>::iterator it=numList.begin(); it!=numList.end(); ++it) { // Get value by dereferencing the iterator int value = *it; // Convert integer to string std::wstring display = std::to_wstring(value); // Extract a C-style string pointer compatible with the interface wchar_t const* ptr = display.c_str(); _ccomboBoxnumType.AddString(ptr); } Of course, you should be using a range-based for loop instead, i.e. for(auto value : numList) { _ccomboBoxnumType.AddString(std::to_wstring(value).c_str()); } In case this doesn't compile make sure to set the character set to Unicode in the project settings. There's no reason not to. Update to account for the C++98 requirement std::to_wstring requires C++11. If that is not something that's available to you, you can get the same functionality through e.g. MFC's CString type by using its Format member. Things get slightly more verbose, but not much: for(std::list<int>::iterator it=numList.begin(); it!=numList.end(); ++it) { // Get value by dereferencing the iterator int value = *it; // Convert integer to CString CString display; display.Format(_T("%d"), value); // CString can implicitly be converted to LPCTSTR // If you like explicit, pass `display.GetString()` instead _ccomboBoxnumType.AddString(display); } Note that this is using generic-text mappings (in disguise), a holdover from the days when targeting both Windows NT and Windows 9x was relevant. It is not recommended today, but should fit right in to a code base that requires a C++98 compiler. A few recommendations to follow: A std::list has unique properties (such as constant time insertion and splicing), at the expense of having to allocate each element on the heap. Since you don't care about any of this, use a std::vector instead. If you need to get the integer value back (e.g. in response to user input) you can store that value inside the Combo Box item. There's CComboBox::SetItemData for that. Alternatively use a CComboBoxEx instead, and set both the text and data in one go by calling CComboBoxEx::InsertItem. Another approach would be setting the item data only, and request the control to retrieve a string representation on demand. That, too, requires using a CComboBoxEx and setting pszText to LPSTR_TEXTCALLBACK in the InsertItem call. The control parent is now responsible for handling the CBEN_GETDISPINFO notification, producing a string representation for the given item.
72,541,591
72,541,754
n is 0 after passing it as an argument to the function, What seems to be the problem here?
Here the question is to put all the zeroes to the end of the array. I've written the code below, but after passing (arr, n) to the pushzero() function, when I try to print the array, it does nothing, and the value of n changes to zero after calling the pushzero() function. #include <bits/stdc++.h> using namespace std; void pushzero(int arr[], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < i + 1; j++) { if (arr[j] == 0) { swap(arr[j+1], arr[j]); } } } } int main() { int arr[] = { 2, 6, 0, 0, 1, 9, 0, 8, 0 }; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < n; i++) { cout << arr[i] << " " << "\n"; } pushzero(arr, n); for (int j = 0; j < n; j++) { // n is 0 here cout << arr[j] << " "; } return 0; }
You could do it by using 0 as a pivot element and whenever you see a non zero element you will swap it with the pivot element. So all the non zero element will come at the beginning. void pushzero(int arr[], int n) { int j =0; for (int i = 0; i < n; i++) { if(arr[i] != 0) { swap(arr[i], arr[j]); j++; } } } Demo: https://godbolt.org/z/oMdxfdWjG
72,542,365
72,543,175
two vector same pointer, delete, memory loss
https://github.com/gameprogcpp/code/blob/master/Chapter02/Game.cpp std::vector<Actor*> deadActors; for (auto actor : mActors) { if (actor->GetState() == Actor::EDead) { deadActors.emplace_back(actor); } } // Delete dead actors (which removes them from mActors) for (auto actor : deadActors) { delete actor; } how is it okay? when pointers in deadActors are deleted, their is no memory loss in mActors?
// Delete dead actors (which removes them from mActors) This is incorrect; deleting the Actors does not modify the original vector. It only results in dereferencing the pointers to those Actors to be undefined behaviour. You'd need an additional step removing the pointers from the original vector for this reason. You could simply iterate through the vector removing the dead elements in one go though: auto writePos = std::find_if(mActor.begin(), mActor.end(), [this](Actor* actor) {return actor->GetState() == Actor::EDead; }); if (writePos != mActor.end()) { delete *writePos; // delete first // move actors and delete dead ones for (auto readPos = writePos + 1, end = mActor.end(); readPos != end; ++readPos) { if ((**readPos).GetState() == Actor::EDead) { delete *readPos; } else { // move non dead actor *writePos = *readPos; ++writePos; } } // remove unneeded space from the end mActor.erase(writePos, mActor.end()); } Note that this becomes much simpler, if you use an element type for the mActor vector that manages the lifetime of the Actor object. std::unique_ptr<Actor> would do the trick. This way any element erased from the vector automatically results in the deletion of the Actor object: std::vector<std::unique_ptr<Actor>> actors = ...; // remove all dead actors moving the remaining actors to the front auto removeEnd = std::remove_if(actors.begin(), actors.end(), [](std::unique_ptr<Actor> const& actor) { return actor->GetState() == Actor::EDead; }); // remove extra space std::actors.erase(removeEnd, actors.end()); Or with C++20: std::vector<std::unique_ptr<Actor>> actors = ...; std::erase_if(actors.begin(), actors.end(), [](std::unique_ptr<Actor> const& actor) { return actor->GetState() == Actor::EDead; });
72,542,616
72,546,131
C++: can I get a "generic" (non-template) pointer (or reference) to a template class?
I have the following problem: I have a class template where each instance represents an array of values (type of values is the template argument, of course). each instance has a name and that name is stored in the instance itself and in a static std::map Something along the lines: #include <cstddef> #include <string> #include <map> template <class T> class block { private: T *ptr; std::string name; std::size_t size; static std::map<std::string, block<T>&> blocks; public: block(std::string _name, T *_ptr, std::size_t _size) : name(_name) , ptr(_ptr) , size(_size) { blocks[_name] = this; } virtual ~block() {} static block<T> &find(std::string key) { return blocks[key]; } }; Now I have the following problem: write a function that, given the block name, an index and a unsigned char [], should fill a single element element in the right block taking as many bytes "as needed". Signature of such a function (or member) should be something like: void set_element(std::string block_name, int index, void *source); Is there a clean way to do this? Ideally the only prerequisite should be there actually are enough bytes in the pointed array (I can add a std::size_t available_bytes to function signature to actually check and throw an error if there aren't enough bytes available). If useful: reason why I need this is the I receive "unstructured" data from network and that's a byte stream I need to parse piece by piece. To be more precise: the input stream i get is composed by a sequence of: a "C string" (null-terminated) representing the block name a single byte representing the index (0..255) "element" binary representation There may be multiple "blocks" stick back-to-back in the input stream so it would be useful to have a return value stating either the number of bytes used or a pointer to first unused. It's assumed binary data it comes from a compatible architecture and thus it is a correct representation. The block name implicitly gives the size and characteristics of the element. Incoming data is not supposed to be aligned; OTOH array pointed in block::ptr is supposed to be correctly aligned so I can access it with normal pointer arithmetic. Note: the above example code is not good because it will produce separate blocks for different template arguments while I need all names to be thrown in the same bag; I assume I will need to implement a parent class, but it's unclear exactly how to do it: I will update if I come to it.
I went through the exercise of deriving from a base class. Here is a piece of code actually compiling: #ifndef AWBLOCK_H_ #define AWBLOCK_H_ #include <stdexcept> #include <cstddef> #include <string> #include <map> namespace AW { class generic_block { private: static std::map<std::string, generic_block*> blocks; protected: std::string name; std::size_t size; virtual int _set(int, void *) = 0; public: generic_block(std::string _name, std::size_t _size) : name(_name) , size(_size) { blocks[_name] = this; } virtual ~generic_block() {} static generic_block *find(std::string key) { return blocks[key]; } void *set(std::string _name, int _index, void *data) { if (blocks.find(_name) == blocks.end()) { throw std::invalid_argument("Unknown block '"+_name+"'"); } if (_index >= (int)size) { throw std::out_of_range("Index "+std::to_string(_index)+" exceeds size of block '"+_name+"' ("+std::to_string(size)+")"); } int n = blocks[_name]->_set(_index, data); return ((char *)data)+n; } virtual int count(void) { return size; } }; template <class T> class AWblock: public generic_block { private: T *ptr; public: AWblock(std::string _name, T *_ptr, std::size_t _size) : generic_block(_name, _size) , ptr(_ptr) { } virtual ~AWblock() {} int _set(int _index, void *_data) { int n = sizeof(*ptr); memcpy(ptr+_index, _data, n); return n; } }; } /* namespace AW */ #endif /* AWBLOCK_H_ */ Minimal test program: #include "gtest/gtest.h" #include "AWblock.h" #define countof(__) (sizeof(__)/sizeof(__[0])) namespace AW { std::map<std::string, generic_block*> generic_block::blocks; int int_block[22]; AWblock<int32_t> _int_block("int-block", int_block, countof(int_block)); TEST(AWblock, HandleCount) { EXPECT_EQ(_int_block.count(), 22); } } /* namespace AW */ apparently works fine: Running main() from /usr/src/googletest/googletest/src/gtest_main.cc [==========] Running 1 test from 1 test suite. [----------] Global test environment set-up. [----------] 1 test from AWblock [ RUN ] AWblock.HandleCount [ OK ] AWblock.HandleCount (0 ms) [----------] 1 test from AWblock (0 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test suite ran. (0 ms total) [ PASSED ] 1 test. If there's a better approach I will gladly accept it, otherwise I will accept my own answer in a few days.
72,542,649
72,545,369
How can i divide a Boost Polygon into regions to get random points in c++?
I have a Boost Polygon made like this : Polygon2D create_polygon(Point2D const& p1, Point2D const& p2, Point2D const& p3, Point2D const& p4) { return {{p1, p2, p3, p4, p1}}; } int main() { auto const& polygon = create_polygon({0., 0.}, {0., 4.}, {7., 4.}, {7., 0.}); return 0; } (not exactly my code but really similar and a lot more simple so i think it's better to understand). And basically, i want to divide my polygon into regions and get a random coordinate (x & y) from each region (or just select specific regions). Something like this : Of course i know it's not going to be square, because a polygon is not everytime simple like this. Do boost c++ have a specific "algorithm" or tool used to divide a Polygon into areas without impacting the whole Polygon ? I have read that voronoi can do something similar to that, but when i'm looking to the example (https://www.boost.org/doc/libs/1_59_0/libs/polygon/doc/voronoi_main.htm) it's not really looking good for my problem. Or maybe another "famous" algorithm can do something similar without the use of boost c++ ? The requirement about regions are : We don't need a specific numbers of regions. The polygon can change size and form so it's more simple without "limits". If we can have regions with equal areas, it's better (but not mandatory, if an algorithm exists without a perfect equality, but a good repartition of areas, it's ok for me).
If you only want to use the subdivision to get the random points in your polygon, you can avoid that by combining the idea of marching squares with Monte Carlo: Take the bounding box of your polygon and divide it into squares of equal size. For each square, determine if it is wholly or partially inside the polygon. Generate random points inside each square until you find one inside the polygon.
72,543,119
72,557,127
Hide a rectangular block temporarily from the main window in QML
I created a nested rectangular block i.e. a rectangle inside a main rectangular block in QML. Now I have to hide the inner rectangular block on some operation and once the operation is finished make it visible again. I am trying the following: Rectangle { id: window width: 450 height: 550 property bool isTopToolBarAreaVisible : true Rectangle { id: toolBarArea width: 1 height: parent.height color: toolBarColor visible : isTopToolBarAreaVisible ToolButton { contentItem: Text { text: "Save as" } onClicked: { ... isTopToolBarAreaVisible = false // hide the inner rectangule window.grabToImage(function(result) { result.saveToFile(fileName); }, Qt.size(window.width*2,window.height*2)); isTopToolBarAreaVisible = true // show the inner rectangle again } } } } I created a boolean isTopToolBarArea to control the visibility but it does not work. Can anyone help.
This seems to work. I'm hiding the Rectangle containing the ToolButton when onClicked is triggered and show it again inside the callback assigned to grabToImage(callback, targetSize). Adding the RowLayout was just to make the ToolButton horizontally centered in the Rectangle. import QtQuick import QtQuick.Controls import QtQuick.Layouts Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Rectangle { id: window anchors.fill: parent color: "green" Rectangle { id: toolBarArea width: parent.width height: 40 color: "red" RowLayout { anchors.fill: parent ToolButton { contentItem: Text { text: "Save as" } onClicked: { toolBarArea.visible = false window.grabToImage(function(result) { result.saveToFile("test.png") toolBarArea.visible = true }, Qt.size(window.width * 2, window.height * 2)) } } } } } }
72,544,065
72,558,644
Edit file (html) in a stream (C++)
I'm looking for some help for my new project and I'm absolute new in programming in C++. I've a html template (size ~ 8kb) with some placeholders inside. My task is to read this template edit the placeholders and add some or less containers depending on my source. I tried different ways but always get stucked on a different point. 1: void readHTML1() { stringstream text; ifstream in_file("index.html"); text << in_file.rdbuf(); string str = text.str(); string str_search = "[CREATE_DATE]"; string str_replace = "12:19 24.05.2022"; size_t pos = str.find(str_search); str.replace(pos, string(str_search).length(), str_replace); in_file.close(); ofstream out_file("index_edit.html"); out_file << str; } void readHTML2() { FILE * stream; stream = fopen("index_edit.html", "r+"); char line [1000]; if (stream) { if (fgets(line, sizeof(line), stream) == NULL) { printf("fgets error\n"); } else { fseek(stream, 31, SEEK_CUR); char input[] = "hugo"; fwrite(input, 4, 1, stream); } fclose(stream); } } The replace of the placeholder works fine, but only a part of the whole stream (html file) will be stored in the "out_file". The rest get lost. I speake about a file size of 8kb but it seems to me that is not the problem. The output is "complete" so the whole stream will be written. But replacing the placeholders overwrites some parts that I don't want to. Is the placeholder smaller then the new value, the rest signs after the placeholder overwrites parts after the placeholders. I prefere the first variant because it is easier for me to replace the placeholders with the new inputs. But I hope you can help me to understand my first, maybe faulty, steps in this new world (for me). Thank you for your time. I appreciate it. I'm ready to learn ...
I found a solution or better the problem. I always test the first point by using the debug function. And always stop at the line after out_file << str; But to this position, for whatever reason (maybe someone can explain!?), only a part of the file was written. So I had never run my code to the end. Now I have run it through and it works. Thanks anyway for your time.
72,544,399
72,544,468
Using a static_cast on non-pointer related types
I discover this compiler trick and I cannot find a name for. Have you any idea? On an Intel processor, I can cast a variable from its base class to an inherited class. It works with MSVC, gcc and clang and I am very confused. #include <string> #include <iostream> class A { public: virtual std::string print() const { return "A"; } }; class B : public A { public: std::string print() const override { return "B"; } std::string printOther() const { return "other"; } }; int main() { A a; std::cout << a.print() << std::endl; // print A std::cout << static_cast<const B&>(a).print() << std::endl; // print A std::cout << static_cast<const B&>(a).B::print() << std::endl; // print B std::cout << static_cast<const B&>(a).printOther() << std::endl; // print other try { std::cout << dynamic_cast<const B&>(a).printOther() << std::endl; // throw std::bad_cast } catch (const std::bad_cast& e) { std::cout << e.what() << std::endl; // print std::bad_cast } std::cout << ((const B&)a).print() << std::endl; // print A std::cout << ((const B&)a).B::print() << std::endl; // print B std::cout << ((const B&)a).printOther() << std::endl; // print other std::cout << reinterpret_cast<const B&>(a).print() << std::endl; // print A std::cout << reinterpret_cast<const B&>(a).B::print() << std::endl; // print B std::cout << reinterpret_cast<const B&>(a).printOther() << std::endl; // print other // error: invalid 'const_cast' from type 'A*' to type 'const B*' //std::cout << const_cast<const B&>(a).print() << std::endl; // print A //std::cout << const_cast<const B&>(a).printOther() << std::endl; // print other return 0; }
Yes, static_cast can cast a class to a reference to a derived class. That is not a trick or compiler-specific. That is one of the specified purposes of static_cast in the C++ standard. However, this cast has undefined behavior if the object isn't actually a base subobject of a derived class object. In your case here you never created a B object, only a A object. Therefore all of the static_cast have undefined behavior and your program is broken. (const B&)a effectively is defined to do the same as static_cast<const B&>(a) if the type B is a derived class type of the type of a. So all of them in your code also have undefined behavior and are broken. dynamic_cast<const B&>(a) is allowed here since your class is polymorphic (has a virtual member function). It will work correctly and fail with an exception if a isn't actually a base subobject of a B object rather than causing undefined behavior. dynamic_cast is the only cast that you may use if you are not sure that a actually is a base subobject of a B. reinterpret_cast<const B&>(a) does something completely different than the above and also causes undefined behavior, because your classes are not standard layout and therefore definitively not pointer-interconvertible.
72,544,712
72,544,866
confused with the fowarding reference
In the c++ std type_traits file below the first overloaded function, the comment says: forward an lvalue as either an lvalue or an rvalue However the return value is just an rvalue reference, I wonder how it could be either an lavlue or an rvalue? Does it mean the returned value is a universal reference? If so what decides how to deduce it to an lvalue reference or an rvalue reference? Also the second overload returns exactly the same thing, why does it say in the comment only forwarding as a rvalue reference without lvalue reference? template <class _Ty> _NODISCARD constexpr _Ty&& forward( remove_reference_t<_Ty>& _Arg) noexcept { // forward an lvalue as either an lvalue or an rvalue return static_cast<_Ty&&>(_Arg); } template <class _Ty> _NODISCARD constexpr _Ty&& forward(remove_reference_t<_Ty>&& _Arg) noexcept { // forward an rvalue as an rvalue static_assert(!is_lvalue_reference_v<_Ty>, "bad forward call"); return static_cast<_Ty&&>(_Arg); }
If _Ty is either a rvalue reference or a non-reference, then _Ty&& is (by reference collapsing rules) a rvalue reference. Hence the function call expression will be a xvalue (a kind of rvalue). If _Ty is however an lvalue reference to type T, i.e. _Ty = T&, then the reference collapsing rules imply that also _Ty&& = T & && = T&. So then the function call will be an lvalue expression. This is an implementation of std::forward. The template argument for _Ty is not intended to (and can't be) deduced. Instead it must be given explicitly. Normally std::forward should only be used in the form std::forward<U>(u); where u is a forwarding reference parameter of the form U&& u in a function template with U a template parameter. Under these conditions, if a rvalue was passed for u, U will be deduced to a non-reference and if an lvalue was passed U will be deduced to an lvalue reference. Then std::forward<U>(u) will pass either a non-reference or an lvalue reference type as template argument for _Ty to std::forward accordingly and by the rule above, std::forward<U>(u) will have the same value category (rvalue or lvalue) as the argument to the forwarding reference u had. (However, it maps both prvalues and xvalues to xvalues.) In the second overload the comment doesn't mention forwarding as lvalue, because the static_assert will trigger if the user tried to use it that way. It should not be allowed to call std::forward with a lvalue reference template argument while the argument is a rvalue. That would not match the intended usage I discussed above.
72,545,509
72,545,701
Is it still valid when the variable passed to `std::async` is out of scope?
Is the code snippet below legal? What worries me is when factorial is invoked the fut_num may be already out of scope. #include <future> #include <vector> #include <iostream> //int factorial(std::future<int> fut) //works, because there is a move constructor int factorial(std::future<int>&& fut) { int res = 1; int num = fut.get(); for(int i=num; i>1; i--) { res *= i; } return res; } int main() { std::promise<int> prs; std::vector<std::future<int>> vec; { std::future<int> fut_num{prs.get_future()}; vec.push_back(std::async(std::launch::async, factorial, std::move(fut_num))); } //`fut_num` is out of range now. prs.set_value(5); for(auto& fut: vec) { std::cout << fut.get() << std::endl; } } And the same question about similar code snippet: #include <future> #include <vector> #include <iostream> //int factorial(std::future<int> fut) //works, because there is a move constructor int factorial(std::future<int>& fut) { int res = 1; int num = fut.get(); for(int i=num; i>1; i--) { res *= i; } return res; } int main() { std::promise<int> prs; std::vector<std::future<int>> vec; { std::future<int> fut_num{prs.get_future()}; vec.push_back(std::async(std::launch::async, factorial, std::ref(fut_num))); } //`fut_num` is out of range now. prs.set_value(5); for(auto& fut: vec) { std::cout << fut.get() << std::endl; } } My two cents about these code snippets: 1.The former code snippet is legal, since std::async copies std::move(fut_num)(i.e. std::move(fut_num) is passed by value to std::async). So there is a local fut_num when fcatorical is called. 2.The latter one is illegal, since fut_num is passed as a reference to std::async. When fut_num is out of scope, it's illegal to call functions which uses fut_num.
The first one is fine, the second one is not. std::async with std::launch::async uses the same procedure of invoking the thread function as the constructor of std::thread does. Both effectively execute std::invoke(auto(std::forward<F>(f)), auto(std::forward<Args>(args))...); in the new thread, but with the auto(...) constructions executing in the context of the calling thread. Here F/Args... are the (other) template parameters with corresponding forwarding-reference function parameters F&& f/Args&&... args and auto has the new C++23 meaning which creates a prvalue/temporary of the decayed argument's type from the argument. See [futures.async]/4.1. This means there will be unnamed copies constructed for all arguments which live in the new thread until after the thread function invocation returns. So with std::move(fut_num), there will actually be another std::future<int> object which will be move-constructed from fut_num and live until the thread ends execution. factorial will be passed a reference to this unnamed object. With std::ref(fut_num) you are explicitly by-passing this mechanism protecting you from passing references to the objects in the constructing thread. The constructor will still make a decayed copy of type std::reference_wrapper<std::future<int>> from the argument, but that object will just contain a reference referring to fut_num in the main thread. std::invoke will then unwrap the std::reference_wrapper before passing to factorial and the fut argument will refer to fut_num in the main thread, which is then destroyed without any synchronization, causing undefined behavior as it is also accessed in the factorial function. It either case it doesn't matter whether factorial takes the argument by-reference or by-value. Nothing about the above reasoning changes.
72,545,760
72,546,047
How to solve the DLL cannot be found issue
In my C# Wpf project, I need some funtion from C++. So I make my own C++ DLL project named LibC. And the Wpf app can run normally in my computer. But on the tester's computer, the log says: Unable to load DLL 'LibC.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) And I checked that the DLL file LibC.dll is there. By checking this post: Unable to load DLL (Module could not be found HRESULT: 0x8007007E) Anthony Hayward's answer inspires me. So I run below dumpbin command and find that my dll rely on those 4 Window's dll. And on the tester's computer, two are missing: vcruntime140d.dll and ucrtbased.dll. While on my computer, all the four dlls can be found. So I copied the missing two dlls to the tester's computer, put them together with my LibC.dll, then the app works well now. My question is how to solve this kind of problem in a better way? As I said, I copy the missing dll files manually to the tester's computer. Another options is to put the two dlls into my project and release them together with my project files, including the exe file and LibC.dll. Is it possible to statically link the two missing dll into my LibC.dll? Or any other advise? "c:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\vc\Tools\MSVC\14.29.30133\bin\Hostx64\x64\dumpbin.exe" /DEPENDENTS libc.dll Microsoft (R) COFF/PE Dumper Version 14.29.30143.0 Copyright (C) Microsoft Corporation. All rights reserved. Dump of file libc.dll File Type: DLL Image has the following dependencies: KERNEL32.dll USER32.dll VCRUNTIME140D.dll ucrtbased.dll Summary 1000 .00cfg 1000 .data 2000 .idata 1000 .msvcjmc 3000 .pdata 4000 .rdata 1000 .reloc 1000 .rsrc A000 .text 10000 .textbss
Your users will need to install the visual c++ runtime. The typical way to do this would be with an installer that does this silently. As far as I know they cannot be compiled into your program, and that the license prohibit distribution of lose dlls outside the redistribution package. Note that you may need to update this package if you update the Visual studio version used to compile your dll. Also note that you need to deploy the release build of your application, since the debug version of the dlls is only distributed as part of visual studio. At last, that pure .Net code does not have these kinds of problems, so if you have c++ code it might be better to just rewrite it in c#. If you want to access some third party dll it might be better to use P/Invoke directly to that dll.
72,545,923
72,546,120
error: explicit specialization of undeclared template class
I have this interface: template <class T> class Builder { public: // Virtual destructor virtual ~Builder(){} // Builds a concrete instance of the implementor virtual T build() const =0; }; and the following concrete implementation: template <class T> class ConcreteBuilder<T> : Builder<T> { public: // Virtual destructor virtual ~ConcreteBuilder(){} // override the build() base method from Builder<T> virtual T build() override { return 0; } }; Suppose the next mock: class MockedClass { public: std::string return_hi() const { return std::string {"Hi!"}; } int return_num() const { return 10; } }; And the following: MockedClass mc; std::cout << mc.return_hi() << std::endl; std::cout << mc.return_num() << std::endl; ConcreteBuilder<MockedClass>; And the error: error: explicit specialization of undeclared template class 'ConcreteBuilder' If I remove the class parameter from the declaration of ConcreteBuilder: class ConcreteBuilder : Builder<T> everything works, but I have the doubt about what I am allowed to do this: ConcreteBuilder; (no type parameters) 1 - Why this error happens? 2 - How can I constraint my ConcreteBuilder in order to make mandatory to specify the type parameter for ConcreteBuilder? Thanks.
The correct syntax to inherit from Builder<T> while defining the ConcreteBuilder template would be as shown below: template <class T> //-------------------v------------------->removed <T> from here class ConcreteBuilder : Builder<T> { public: // Virtual destructor virtual ~ConcreteBuilder(){} // override the build() base method from Builder<T> virtual T build() override { return 0; } };
72,546,623
72,547,243
C++: Values of both objects changes after a Copy Constructor
I have written a simple c++ code to understand the concepts of Copy Constructor/Operator Overloading. A snippet of the code is shown below. In the code I am creating an object vec v2 and then creating a new object v4 and assign vec v2. Next I called the overloaded operator[] to change the values of v4[0] and v4[1]. My issue is that after assigning these values, the values of vec v2 has also changed. I am not quite sure how this could have happened. Hope anyone can help me with this. class vec { private: // Variable to store the number of elements contained in this vec. size_t elements; // Pointer to store the address of the dynamically allocated memory. double* data; public: vec(size_t size) : elements{ size }, data{ new double[size] } {std::cout << "First constructor" << "\n"; }; vec(size_t size, double ival) : elements{ size }, data{ new double[size] } { std::cout << "Second constructor" << std::endl; for (int i = 0; i < elements; i++) { data[i] = ival; } } vec(std::initializer_list<double> iList): vec(static_cast<size_t>(iList.size())) { std::cout << "Third constructor" << std::endl; auto count{ 0 }; for (auto element: iList) { data[count] = element; count++; } } /// Copy constructor that creates a copy of the vec variable 'v'. vec(const vec& v) : elements{ v.elements }, data{ new double[v.elements] }{ std::cout << "Copy constructor " << "\n"; std::memcpy(&data, &(v.data), v.elements); } /// Copy assignment operator. Creates a copy of vec variable 'v'. vec& operator=(const vec& v) { std::cout << "Copy assignment " << "\n"; if (this != &v) { const auto new_data{ new double[v.elements] }; delete[] data; data = new_data; elements = v.elements; std::memcpy(&data, &(v.data), v.elements); } return *this; } double& operator[](size_t idx){ return this->data[idx]; } friend std::ostream& operator<<(std::ostream& os, const vec& v) { for (int i = 0; i < v.elements; i++) { os << v.data[i] << "\n"; } return os; } }; int main(void) { vec v2 = {4, 5, 6}; vec v4 = v2 v4[0] = 11; // call to operator[] v4[1] = 12; // call to operator[] return 0; }
The issue is the misuse of the std::memcpy function: std::memcpy(&data, &(v.data), v.elements); Since data and v.data are already pointers to the data, getting the address of those pointers results in the incorrect pointer values being used for those arguments. The other issue is that the third argument v.elements should denote the number of bytes, not the number of elements, to copy. The correct call to std::memcpy should have been: std::memcpy(data, v.data, v.elements * sizeof(double)); But having said all this, do not use std::memcpy, and instead use std::copy. That will work with the number of elements, plus can work with types that are not trivially-copyable (such as std::string): #include <algorithm> //... std::copy(v.data, v.data + v.elements, data);
72,546,683
72,547,352
Plus sign at the beginning of a new line and the code compiles
The code below is compilable (VS2019 and cpp.sh) whereas the last line begins with a "+". I noticed this bug when I saw that the header of my CSV file was missing a column. In C++, I just checked that this line of code is also correct : + 3 + 5 so it works with integers too (the + at the beginning of 3 might siganl that 3 is positive isn't it ? but how can it work with strings ? before the '+' there's no string at all) ! Any explanation ? #include <iostream> #include <string> int main() { static constexpr char s_fieldDelimiter = ';'; static const std::string s_crlf = "\n"; static const std::string s_regsFileHeader = std::string("Date") + s_fieldDelimiter + "Current Pressure (bar)" + s_fieldDelimiter + "Analog Flow Meter (dL/min)"; + s_fieldDelimiter + "Analog Volume (L)"; }
The field delimiter type is char (integral type), so + s_fieldDelimiter is an int (the + sign is to signal that the number is positive just like in maths) and this last can be used to do pointer arithmetic since the string literal type is a "const char*".
72,546,764
72,546,908
Is C++ implementation of executor finalized? How to compile it?
I'm trying to use C++ executor. This is the code I found in https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0443r14.html. It should be supported by gcc 11. I compiled this code with command g++-11 main.cpp -ltbb #include <iostream> #include <execution> using namespace std::execution; int main() { std::static_thread_pool pool(16); executor auto ex = pool.executor(); perform_business_logic(ex); execute(ex, []{ std::cout << "Hello world from the thread pool!"; }); } It gives a lot of errors. error: ‘thread_pool’ is not a member of ‘std’ error: ‘executor’ was not declared in this scope error: ‘ex’ was not declared in this scope
This is just a proposal for addition to the C++ standard. It was never adopted. See https://github.com/cplusplus/papers/issues/102 regarding the progress of this proposal which was closed and https://github.com/cplusplus/papers/issues/1054 for the executor proposal which is currently still under consideration for C++26. Currently there is no equivalent in any C++ revision (published or drafting). It is unlikely that you will find a compiler/standard library supporting any of the proposals except maybe as experimental implementations for demonstration. In particular I am not sure what you base "It should be supported by gcc 11." on. (The original C++17 tag on the question also doesn't make sense, since the linked proposal is from 2020.)
72,546,934
72,560,526
QImage loadFromData doesn't load the data of my images
I'm new to Qt and I have been trying to develop a simple video streaming application. While developing my app, I've been facing a problem I thought could be ignored at first, but that's not the case. In fact, this problem is slowing down my whole application and is making it not working. Here's my problem: When I'm trying to display many images I have 2 choices: Using the QImage constructor QImage(uchar *data, int width, int height, QImage::Format format) to construct the image and display it. It's working as intended but is VERY, VERY slow Or load the data of the images with QImage::loadFromData(uchar *, int len), which is simply not working. Here's my working code: void MainWindow::startCapturing() { timer->start(); // on press of a button, the timer will call repeatedly the generateImage() function } void MainWindow::generateImage() { det->GetImage(&image); // fulfill my image with data myImage=QImage((uchar*)image.GetValuePointer(),image.GetSize().height,image.GetSize().width, QImage::Format_Grayscale16); // here GetValuePointer returns a void *, that's why we had to cast it. ui->img_label->setPixmap(QPixmap::fromImage(myImage)); } Here's my not working code void MainWindow::startCapturing2() { myImage=QImage((uchar*)image.GetValuePointer(),image.GetSize().height,image.GetSize().width, QImage::Format_Grayscale16); ui->img_label->setPixmap(QPixmap::fromImage(myImage)); timer->start(); // on press of a button, the timer will call repeatedly the generateImage() function } void MainWindow::generateImage2() { det->GetImage(&image); myImage.loadFromData((uchar *)image.GetValuePointer(), image.GetSizeInBytes()); // same cast of GetValuePointer as above ui->img_label->setPixmap(QPixmap::fromImage(myImage)); } INFORMATIONS ABOUT THE CODE: det->GetImage(&image) fulfill my Image object named image here. Image is my own type because I'm working with specific cameras and had to do so, it's more on the hardware side, don't bother with that. image.GetValuePointer() returns the data of the image as a void * to be cast in anything you want. don't bother with timer() and startCapturing() as well, it's working, that's not the point of the topic. in StartCapturing2, I'm trying to create the QImage, and set the pixmap so that if I update myImage with loadFromData, it will change the image displayed. I've been trying many things, like a lot of them, using a QByteArray for example but it's either not working or simply not what I want. If you have any question, please ask them I will try to answer as fast and best as I can! Thanks!
You haven't provided any value for the format parameter for loadFromData() (default value is nullptr) so most likely QImage tries to find a image header, doesn't find any and gives up, not being able to handle the following data. The loader attempts to read the image using the specified format, e.g., PNG or JPG. If format is not specified (which is the default), the loader probes the file for a header to guess the file format. On a side note, your second option might be even slower than the first because it copies the data while the first one uses the existing data from image. See constructor documentation (emphasis mine): QImage::QImage(const uchar *data, int width, int height, QImage::Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr) Constructs an image [...] that uses an existing read-only memory buffer, data.
72,547,193
72,567,289
Optimal place to call __syncthreads()
Given that the code is correct, is there some potential performance benefit in calling __syncthreads as late as possible, as early as possible, or does it not matter? Here's an example with comments that demonstrate the question: __global__ void kernel(const float* data) { __shared__ float shared_data[64]; if (threadIdx.x < 64) { shared_data[threadIdx.x] = data[threadIdx.x]; } // Option #1: Place the call to `__syncthreads()` here? // Here is a lot of code that doesn't use `shared_data`. // Option #2: Place the call to `__syncthreads()` here? // Here is some code that uses `shared_data`. }
What you are facing is a split between where the writes are made and where they should be visible to the entire block. NVIDIA has recently introduced a mechanism for just that: arrive + wait. You start with initializing a barrier: void __mbarrier_init(__mbarrier_t* bar, uint32_t expected_count); Then you arrive at your "option 1" position, with the bar token you initialized: __mbarrier_token_t __mbarrier_arrive(__mbarrier_t* bar); then you have your unrelated code, and then finally, wait for everyone to arrive at your "option 2" position: bool __mbarrier_test_wait(__mbarrier_t* bar, __mbarrier_token_t token); ... but note that this call doesn't block, i.e you'll have to actively "wait". Alternatively, you can use NVIDIA's C++ wrappers for this mechanism, presented here. Note that this functionality is relatively new, with Compute Capability at least 7.0 required, and 8.0 or later recommended.
72,547,211
72,547,259
How to print out all the strings within an array within an ncurses window?
I'm trying to display an array of multiple random generated strings within a ncurses window. At first, I thought this was going to be simple and I can print the array as I would with any other array: putting it through a loop and displaying each string that it comes across within the array. When I tried this, all the words were printing, just that they were coming out of the borders of the ncurses window. Then I tried to figure out a way I can set the location of the cursor for each word, but I can't figure out how I would do that. Does anybody know a solution I can keep the strings within the borders of the window? Any help would be appreciated. initscr(); string wordList[19] = {"icecream", "computer", "dictionary", "algorithm", "the", "be", "to", "of", "and", "a", "your", "you", "year", "would", "work", "with", "will", "who", "which",}; string word[19]; // parameters for window int height, width, start_y, start_x; height = 9; width = 75; start_y = 10; start_x = 10; //creating the window WINDOW *win = newwin(height, width, start_y, start_x); refresh(); box(win, 0, 0); wrefresh(win); // displaying random strings from the wordList array. srand(time(0)); for(int i=0; i<19 ; i++){ word[i] = wordList[rand() % 19]; printf("%s", word[i].c_str()); printf(" "); } wrefresh(win); getch(); endwin();
Don't use printf, use ncurses' functions like waddstr() instead.
72,547,643
72,548,391
Using the same vertex array object for different shader programs
my goal is to pack all mesh data into a C++ class, with the possibility of using an object of such a class with more than one GLSL shader program. I've stuck with this problem: if I understand it well the way of how in GLSL vertex data are passed from CPU to GPU is based on using Vertex Array Objects which: are made of Vertex Buffer Objects which store raw vertex data, and Vertex Attribute Pointers which tells what shader variable location to assign and the format of the data passed to VBO above additionally one can make an Element Buffer Object to store indices another extra elements necessary to draw an object are textures which are made separately I's able to make all that data and store only a VAO in my mesh class and only pass the VAO handler to my shader program to draw it. It works, but, for my goal of using multiple shader programs, the VAP stands in my way. It is the only element in my class that rely on a specific shader program's property (namely the location of input variables). I wonder if I'm forced to remake all VAOs every time I'm using my shaders when I want to draw something. I'm afraid that the efficiency of my drawing code will suffer drastically. So, I'm asking if I should forget of making my universal mesh class and instead make a separate objects for each shader program I'm using in my application. I would rather not, as I want to avoid unnecessary copying of my mesh data. On the other hand if this means my drawing routine will slow down because of all that remaking VAOs every milisecond during drawing then I have to rethink the design of my code :( EDIT: OK I've misunderstood that VAOs store bindings to other objects, not the data itself. But there is one thing still left: to make an VAP I have to provide information about the location of an input variable from a shader and also the layout of data in VBO from a mesh. What I'm trying to avoid is to make an separate object that stores that VAP which relies both on a mesh object and a shader object. I might solve my problem if all shader programs use the same location for the same thing, but at this moment I'm not sure if this is the case.
additionally one can make an Element Buffer Object to store indices another extra elements necessary to draw an object are textures which are made separately Just to be clear, that's you being lazy and/or uninformed. OpenGL strongly encourages you to use a single buffer for both vertex and index data. Vulkan goes a step further by limiting the number of object names (vao, vbo, textures, shaders, everything) you can create and actively punishes you for not doing that. As to the problem you're facing.. It would help if you used correct nomenclature, or at least full names. "VAP" is yet another sign of laziness that hides what your actual issue is. I will mention that VAOs are separate from VBOs, and you can have multiple VAOs linked to the same VBO (VBOs are just buffers of raw data -- again, Vulkan goes a step further here and its buffers store literally everything from vertex data, element indices, textures, shader constants etc). You can also have multiple programs use the same VAOs, you just bind whatever VAO you want active (glBindVertexArray) once, then use your programs and call your render functions as needed. Here's an example from one of my projects that uses the same terrain data to render both the shaded terrain and a grid on top of them: chunk.VertexIndexBuffer.Bind(); // pass 1, render the terrain terrainShader.ProgramUniform("selectedPrimitiveID", selectedPrimitiveId); terrainShader.Use(); roadsTexture.Bind(); GL.DrawArrays(PrimitiveType.Triangles, 0, chunk.VertexIndexBuffer.VertexCount); // pass 2, render the grid gridShader.Use(); GL.DrawElements(BeginMode.Lines, chunk.VertexIndexBuffer.IndexCount, DrawElementsType.UnsignedShort, 0);
72,547,644
72,554,541
Pybind11 compiles with c++98 despite specification
I am trying to expose some c++ code to Python with pybind11. I specifically would like to enforce a certain c++ standard (say c++11), as the same .cpp file would need to be compiled on different systems. Following the official example to compile with setuptools in this repository, I modified part of the code as follows: ext_modules = [ Pybind11Extension( modulename, sources=[filename], language='c++', cxx_std=11 ), ] I ran python setup.py install on my windows machine and a Linux machine (it's actually Google Colab, which uses Linux backend). I checked the standard used by adding py::print(__cplusplus); in code. On the Linux machine, the standard changed from c++14 to c++ 11 after adding cxx_std=11. However, on my own windows machine, the standard remained as c++98. In both cases, the exposed code can be sucefully imported as a module (a .pyd file on windows and a .so file on linux) and works as intended. This is very strange because: (1) According to the documentation for Pybind11Extension, it "Build a C++11+ Extension module with pybind11.". It does not make sence for my code to be compiled with c++98 successfully when the minimum requirement is c++11. (2) I have gcc version 8.1.0 (by checking g++ -v), which should support the latest standard of c++. Additionally, if I use g++ command to compile a normal cpp file, it says c++14, which means c++14 is the default. This difference of standard is causing a lot of trouble because sometimes code works on my windows machine but fails when compiled on Linux. Now, I am relatively new to stuff about c++ compilers, so I might be missing something obvious. Any idea how to solve this? Update: After some discussion it seems that setup.py uses MSVC on windows. This question then becomes a duplicate of this, which remains unsolved (the setup.cfg method mentioned does not work. I could specify --compiler msvc but if I write --compiler mingw32 it raise several errors: gcc: error: /EHsc: No such file or directory, gcc: error: /bigobj: No such file or directory, gcc: error: /std:c++14: No such file or directory). Update 2: With the method by spectras it is confirmed that setup.py uses MSVC, which also has c++14 as earlist possible standard. However, I still want to enforce GCC so I could have the same compiler on windows and linux. To enforce GCC, I tried the following command (env_csmar is an anaconda virtual environment under my disk F): D:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\gcc.exe -static -shared -std=c++11 -DMS_WIN64 -fPIC "-IF:\...\env_csmar\lib\site-packages\pybind11\include" "-IF:\...\env_csmar\include" "-L F:\...\env_csmar\libs" -c example_cpp.cpp -o example_cpp.o This works, and the .o file can be imported as a module on my windows. However, it still says it is compiled with MSVC and under c++14 (from #ifdef _MSVC_LANG). Why is this?
You did not build using C++98 on Windows. You got confused because by default MSVC always reports __cplusplus as 199711, no matter what standard it is using, for compatibility reasons. This behavior can be disabled with the /Zc:__cplusplus switch. Alternatively, you can use _MSVC_LANG predefined macro. If it is defined, then you are building with MSVC (or a compiler emulating it) and then _MSVC_LANG will accurately reflect the language standard being enforced. Something like… #ifdef _MSVC_LANG py::print(_MSVC_LANG) #else py::print(__cplusplus) #endif …should do the trick.
72,547,656
72,548,627
TSAN thread race error detected with Boost intrusive_ptr use
Below code generates a TSAN error(race condition). Is this a valid error ? or a false positive ? Object is destroyed only after ref count becomes zero(after all other thread memory operations are visible - with atomic_thread_fence) If I use a std::shared_ptr instead of boost::intrusive_ptr, then TSAN error disappears. Since both threads use the object as read-only, I presume this should be safe. If this is a valid error how do I fix it ? gcc version - 7.3.1 boost version - 1.72.0 compile command : "g++ -ggdb -I /usr/local/boost_1_72_0 -O3 -fsanitize=thread TSan_Intr_Ptr.cpp -lpthread " #include <boost/smart_ptr/intrusive_ptr.hpp> #include <boost/smart_ptr/detail/spinlock.hpp> #include <boost/atomic.hpp> #include <thread> #include <iostream> #include <vector> #include <atomic> #include <unistd.h> using namespace std; struct Shared { mutable boost::atomic<int> refcount_; //From https://www.boost.org/doc/libs/1_72_0/doc/html/atomic/usage_examples.html friend void intrusive_ptr_add_ref(const Shared * x) { x->refcount_.fetch_add(1, boost::memory_order_relaxed); } friend void intrusive_ptr_release(const Shared* x) { if (x->refcount_.fetch_sub(1, boost::memory_order_release) == 1) { boost::atomic_thread_fence(boost::memory_order_acquire); delete x; } } }; vector<boost::intrusive_ptr<Shared const>> g_vec; boost::detail::spinlock g_lock = BOOST_DETAIL_SPINLOCK_INIT; void consumer() { while(true) { g_lock.lock(); g_vec.clear(); g_lock.unlock(); usleep(10); } } int main() { thread thd(consumer); while(true) { boost::intrusive_ptr<Shared const> p(new Shared); g_lock.lock(); g_vec.push_back(p); g_lock.unlock(); usleep(1); } return 0; } TSAN Error WARNING: ThreadSanitizer: data race (pid=14513) Write of size 8 at 0x7b0400000010 by main thread: #0 operator delete(void*) <null> (libtsan.so.0+0x00000006fae4) #1 intrusive_ptr_release(Shared const*) /Test/TSan_Intr_Ptr_Min.cpp:25 (a.out+0x000000401195) #2 boost::intrusive_ptr<Shared const>::~intrusive_ptr() /boost_1_72_0/boost/smart_ptr/intrusive_ptr.hpp:98 (a.out+0x000000401195) #3 main /x01/exch/Test/TSan_Intr_Ptr_Min.cpp:51 (a.out+0x000000401195) Previous atomic write of size 4 at 0x7b0400000010 by thread T1: #0 __tsan_atomic32_fetch_sub <null> (libtsan.so.0+0x00000006576f) #1 boost::atomics::detail::gcc_atomic_operations<4ul, true>::fetch_sub(unsigned int volatile&, unsigned int, boost::memory_order) /boost_1_72_0/boost/atomic/detail/ops_gcc_atomic.hpp:116 (a.out+0x000000401481) #2 boost::atomics::detail::base_atomic<int, int>::fetch_sub(int, boost::memory_order) volatile /usr/local/boost_1_72_0/boost/atomic/detail/atomic_template.hpp:348 (a.out+0x000000401481) #3 intrusive_ptr_release(Shared const*) /Test/TSan_Intr_Ptr_Min.cpp:22 (a.out+0x000000401481) ...
it seems using memory_order_acq_rel resolves the issue. (May be https://www.boost.org/doc/libs/1_72_0/doc/html/atomic/usage_examples.html example is in-correct) friend void intrusive_ptr_add_ref(const Shared * x) { x->refcount_.fetch_add(1, boost::memory_order_acq_rel); } friend void intrusive_ptr_release(const Shared* x) { if (x->refcount_.fetch_sub(1, boost::memory_order_acq_rel) == 1) { delete x; } }
72,548,027
72,548,303
Compile same source with diffrent aliases
TLDR: Can you compile the same source code with different headers defining diffrent aliases? I have created a library, with a set of functions coded using a couple of aliased type in the header. algorithm_2d.h using Point = Eigen::Vector2d; using Vector = Eigen::Vector2d; algorithm.cpp Vector& scale_vector( Vector &v, double s) { double len = v.norm(); if (len != 0.0) { v *= s/len;} return v; } double distance_between_points( Point const &p1, Point const &p2) { return (p2 - p1).norm(); } Now I would like to compile the same algorithm.cpp but with different aliases: algorithm_3d.h using Point = Eigen::Vector3d; using Vector = Eigen::Vector3d; I am building using CMake with pybind11 as this is mainly a python library. I would prefer not having to use templates, as that would cause me to have to define every single type in every function. And as you can see in the snippet, it would make it a lot less readable, and this is already a mathematically complicated algorithm (rest of the code not shown). EDIT: Another example to make it clear what I mean by using the aliases. If I were using templates, each time this function is called .h using PointSet = std::vector<Point, Eigen::aligned_allocator<Point> >; .cpp Vector compute_left_tangent( PointSet const &pts, int end, { Vector tHat1 = PointSet[end+1] - PointSet[end]; tHat1 = tHat / distance_between_points(PoinSet[end],PointSet[end+1]) } I don't want to have to add the <Eigen::Vector2d,..., etc> every time I call one of these functions. Maybe there is a way of doing this with templates that I am missing?
Given the following template file: (call it algorithm.cpp.tmpl) using Point = @_flavor@; using Vector = @_flavor@; #include "algorithm.cpp" You can have CMake generate flavors automatically and build them as part of some_target: set(FLAVORS Eigen::Vector2d Eigen::Vector3d) foreach(_flavor ${FLAVORS}) string(MAKE_C_IDENTIFIER ${_flavor} _flavor_slug) set(_flavor_out algorithm_${_flavor_slug}.cpp) configure_file(algorithm.cpp.tmpl ${_flavor_out} @ONLY) target_sources(some_target PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/${_flavor_out}) endforeach()
72,548,170
72,548,424
Why using erase and unique function to remove duplicate vectors from a 2d vector is adding an extra empty vector in 2d vector?
I am using the below code to remove duplicate vectors from a 2d vector sort(final_vec.begin(), final_vec.end()); final_vec.erase(unique(final_vec.begin(), final_vec.end())); Can someone explain me why this is happening and what change should I make.
To make it clearer what exactly is going wrong, I'm going to introduce an intermediate variable to store the iterator returned by std::unique. Your code is equivalent to: sort(final_vec.begin(), final_vec.end()); auto new_ending_iterator = unique(final_vec.begin(), final_vec.end()) final_vec.erase(new_ending_iterator); When we check the overloads of std::vector::erase, we see that this is actually the one-argument erase call: iterator erase( const_iterator pos ) Removes the element at pos. So this is erasing a single element from final_vec. However, our goal is to erase every element from new_ending_iterator all the way until final_vec.end(). To do so, we use the second overload of erase: iterator erase( const_iterator first, const_iterator last ); Removes the elements in the range [first, last). The correct code would therefore look like sort(final_vec.begin(), final_vec.end()); auto new_ending_iterator = unique(final_vec.begin(), final_vec.end()) final_vec.erase(new_ending_iterator, final_vec.end()); Or, if you really want to keep it all in one line: sort(final_vec.begin(), final_vec.end()); final_vec.erase(unique(final_vec.begin(), final_vec.end()), final_vec.end());
72,548,689
72,549,678
Why do `std::ranges::size` require a non-const method when using ADL?
Otherwise, size(t) converted to its decayed type, if ranges::disable_sized_range<std::remove_cv_t<T>> is false, and the converted expression is valid and has an integer-like type, where the overload resolution is performed with the following candidates: void size(auto&) = delete; void size(const auto&) = delete; 1 class Test { friend size_t size(/*const*/ Test&) { return 0; } }; int main() { std::ranges::size(Test{}); // no matching function error when adding the `const` qualifier } https://godbolt.org/z/79e5vrKrT Generally, size method doesn't require to modify the range, like what std::size does. Why is there such a constraint of std::ranges::size? (Seems it's only performed for non-member version.)
Why is there such a constraint of std::ranges::size? (Seems it's only performed for non-member version.) Although the size method does not modify the range, some ranges do not have a const-qualified member begin(), which allows only non-const-qualified objects to model a range. This also makes some range adaptors in the standard may only have a non-const-qualified size. For your example, considering that Test only has non-const begin/end or size, then friend size_t size(Test&) can really only be the option.
72,548,768
72,548,833
How can I assign element-wise to a tuple using fold expressions?
I have a type effectively wrapping a variadic std::tuple like this: #include <iostream> #include <tuple> template <typename ...Args> struct Foo { std::tuple<Args...> t; Foo(Args&&... a) : t{ std::forward<Args>(a)... } { } Foo& operator +=(const Foo& f) { std::apply([&](auto&&... ts) { std::apply([...ts = std::forward<decltype(ts)>(ts)](auto&&... fts) { ((ts += fts), ...); }, f.t); }, t); return *this; } friend std::ostream& operator <<(std::ostream& os, const Foo& f) { std::apply([&](auto&&... ts) { ((os << ts << ' '), ...); }, f.t); return os; } }; int main() { Foo goy{ 1, 2, 3 }; Foo bar{ 4, 5, 6 }; goy += bar; std::cout << goy << std::endl; // expect 5 7 9 as output } Now I want to be able to add-assign instances of this type by adding the tuple entries element-wise, as indicated in the code snippet and preferably with the use of fold-expressions instead of rather clumsy constructions using std::index_sequence<> and alike. However, my attempt fails at the compiler level, with clang facing and internal compiler crash and GCC diagnosing: error: assignment of read-only variable 'ts#0' 15 | ((ts += fts), ...); | ~~~~^~~~~~~ Cf. Godbolt I fail to see why ts is immutable here. So what's wrong? Is the program ill-formed and/or are the compilers buggy? Is there an elegant fix?
lambda capture are const by default, you need to add mutable to mutate it. std::apply([...ts = std::forward<decltype(ts)>(ts)](auto&&... fts) mutable { ... } although I don't see why you capture it by value here, to me it seems like you actually want to capture them by reference. std::apply([&](auto&&... fts){ ... }
72,548,868
72,549,373
Remove duplicates from array C++
Input: int arr[] = {10, 20, 20, 30, 40, 40, 40, 50, 50} Output: 10, 30 My code: int removeDup(int arr[], int n) { int temp; bool dupFound = false; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(arr[i] == arr[j]){ if(!dupFound){ temp = arr[i]; dupFound = true; } else{ arr[i] = temp; } } } } //shift here } First of all, I don't know if this is the most efficient way of doing this. I'm trying to find the first duplicate element, assign it to every duplicate element and shift them to the end of the array, which doesn't work because the last duplicate element cannot be compared. I need some help with finding the last duplicate element, so I can assign temp to it.
Instead of trying to do everything at once, let us focus on correctness first: int removeDup(int* arr, int n) { // Note: No i++! This depends on whether we find a duplicate. for (int i = 0; i < n;) { int v = arr[i]; bool dupFound = false; for (int j = i+1; j < n; j++) { if (v == arr[j]) { dupFound = true; break; } } if (!dupFound) { i++; continue; } // Copy values to the sub-array starting at position i, // skipping all values equal to v. int write = i, skipped = 0; for (int j = i; j < n; j++) { if (arr[j] != v) { arr[write] = arr[j]; write++; } else { skipped++; } } // The previous loop duplicated some non-v elements. // We decrease n to make sure these duplicates are not // considered in the output n -= skipped; } return n; }
72,549,449
72,549,538
undeclared indentifier on the same scope C++
Playing with C++ 20 modules, I have the following snippet: export { template<class T> class Suite { private: std::vector<ConcreteBuilder<T>> things {}; }; template <class T> class ConcreteBuilder : Builder<T> { private: // A collection of things of function pointers or functors std::vector<std::function<void()>> things; public: // Virtual destructor virtual ~TestBuilder() override {}; // Add a new thing to the collection of things template<typename Function> void add(Function&& fn) { tests.push_back(std::forward<Function>(fn)); } // override the build() base method from Builder<T> virtual T build() const override { return this->things; } }; } And I am getting this Clang error: error: use of undeclared identifier 'ConcreteBuilder' std::vector<ConcreteBuilder> things {}; Why I can't access to a type that are in the same module at the same level?
The compiler compiles the file from the top down, not all at once. It is hitting the definition of std::vector<ConcreteBuilder<T>> before it gets to the definition of class ConcreteBuilder. So, you need to move your definition of Suite after the definition of ConcreteBuilder, so the compiler knows what it is when you use it in the vector definition.
72,549,463
72,549,714
Compiling with PGI PGCC with LAPACK and LBLAS libraries?
I'm trying to compile my OpenACC parallel C++ program that makes use of dgemm (BLAS) and dgesvd (LAPACK) functions. I'm trying to compile the program with PGI PGCC compiler, linking it with the libraries like this (the program is called "VD"): # Target rules LIBRARIES := -lblas -llapack -lm CC = gcc CFLAGS = -O3 PGCC = pgcc -Minfo=accel -fast -acc -ta=multicore -tp=nehalem -DDEBUG ################################################################################ # Target rules all: build build: vd VD.o: VD.cpp $(PGCC) -o $@ -c $< -w vd: VD.o $(PGCC) $(CFLAGS) -o $@ $+ $(LIBRARIES) clean: rm -f VD.o vd But I get the following error: https://i.stack.imgur.com/giIlr.jpg It looks like the file is compiling (by this I mean that there are no errors in the code), but when its going to link it to LAPACK (BLAS works) it just doesn't seem to find some references. My $(LD_LIBRARY_PATH) variable contains the exact path of LAPACK: /opt/nvidia/hpc_sdk/Linux_x86_64/21.9/compilers/lib/ Here is the first part of my code: #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <time.h> #include <string.h> // NUEVOS INCLUDES #include <openacc.h> // FIN DE NUEVOS INCLUDES #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define MAXLINE 200 #define MAXCAD 200 #define FPS 5 extern int dgemm_(char *transa, char *transb, int *m, int * n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc); extern int dgesvd_(char *jobu, char *jobvt, int *m, int *n, double *a, int *lda, double *s, double *u, int * ldu, double *vt, int *ldvt, double *work, int *lwork, int *info); Note: I've tried to put these latest functions starting with "extern "C" int..." but it doesn't compile. What am I missing? Thank you!
The BLAS and LAPACK are written in Fortran, hence the error you’re seeing is due to missing the Fortran runtime libraries on the link line. To fix, add “-fortranlibs” on your link line so these libraries are added.
72,549,590
72,549,749
Constructer Calling order
I know when a constructer is being called, then it gets created in the memory, and when it gets out of the block it gets destroyed unless it's static. Know I have this code: #include <iostream> #include <string> using namespace std; class CreateSample { private: int id; public: CreateSample(int i) { id = i; cout << "Object " << id << " is created" << endl; } ~CreateSample() { cout << "Object " << id << " is destroyed" << endl; } }; void fuct() { CreateSample o1(1); static CreateSample o2(2); } CreateSample o3(3); void fuct2(CreateSample o); int main() { fuct(); static CreateSample o4(4); CreateSample o5(5); fuct2(o5); return 0; } void fuct2(CreateSample o) { CreateSample o6 = o; } and my concern is in object o5, why it's getting called once and gets destroyed 3 times?
CreateSample o5(5); calls the constructor CreateSample(int). fuct2(o5); and CreateSample o6 = o; call the implicitly-defined default copy constructor CreateSample(CreateSample const&). All three of these variables (o6, o, and o5) call the destructor ~CreateSample() when their scope is exited. The fix is to follow the rule of three and also define a copy constructor and copy-assignment operator: class CreateSample { // ... CreateSample(CreateSample const& o) { id = o.id; cout << "Object " << id << " is copy-constructed" << endl; } CreateSample& operator=(CreateSample const& o) { cout << "Object " << id << " is copy-assigned from " << o.id << endl; id = o.id; return *this; } } Demo on Compiler Explorer
72,549,715
72,550,021
Which undefined behavior allows this optimization?
I'm working on a virtual machine which uses a typical Smi (small integer) encoding where integers are represented as tagged pointers. More precisely, pointers are tagged and integers are just shifted. This is the same approach as taken by V8 and Dart: https://github.com/v8/v8/blob/main/src/objects/smi.h#L17 In our implementation we have the following code for the Smi: // In smi.h #include <stdint.h> class Object { public: bool is_smi() const { return (reinterpret_cast<uintptr_t>(this) & 0x1) == 0; } }; class Smi : public Object { public: intptr_t value() const { return reinterpret_cast<intptr_t>(this) >> 1; } static Smi* from(intptr_t value) { return reinterpret_cast<Smi*>(value << 1); } static Smi* cast(Object* obj) { return static_cast<Smi*>(obj); } }; With this setup, the following function is optimized by gcc 12.1.0 and -O3 so that the 'if' is never taken when o has the Smi value 0. // bad_optim.cc #include "smi.h" void bad_optim(Object* o) { if (!o->is_smi() || o == Smi::from(0)) { printf("in if\n"); } } If I replace the 'if' line with the following code, the check works: if (!o->is_smi() || Smi::cast(o)->value() == 0) { I'm guessing we are hitting an undefined behavior, but it's not clear to me which one. Furthermore, it would be good to know whether there is a flag that warns about this behavior. Alternatively, maybe there is a flag to disable this optimization. For completeness sake, here is a main that triggers the behavior. (Note that the bad_optim and main function must be compiled separately). // main.cc #include "smi.h" void bad_optim(Object* o); int main() { Smi* o = Smi::from(0); bad_optim(o); return 0; }
It's simple: dereferencing invalid or null o would cause UB, so after the dereference, o supposedly can't be null. Calling is_smi() counts as dereferencing, even if it actually doesn't access the memory. Make is_smi() a free function (since this only applies to this, not pointer parameters). I'd also make Object an opaque struct (declared but not defined).
72,549,927
72,550,033
Casting operator ignored?
Having such simple code: DWORD i = 0xFFFFFFF5; // == 4294967285(signed) == -11(unsigned) if((unsigned)i == -11) OutputDebugString(L"equal"); else OutputDebugString(L"not equal"); The condition is meet - i'm getting "equal" output. My question is WHY is that happen since in the condition we have f(4294967285 == -11) considering the explicit unsigned cast on the left side of the operator? Why is the cast ignored?
DWORD is unsigned or equivalent, a 32-bit unsigned integer in your C++ implementation. DWORD i = 0xFFFFFFF5; initializes i to FFFFFFF516 = 4,294,967,285. In (unsigned)i == -11, i is converted to unsigned, which yields the same value, 4,294,967,285. The other operand, -11, has type int and value −11. When two numbers are compared with ==, they are converted to be some common type. The rules for operating on an unsigned and an int result in the int being converted to unsigned. When −11 is converted to unsigned in a C++ implementation in which unsigned is 32 bits, the result of the conversion is 232−11 = 4,294,967,296 − 11 = 4,294,967,285. Then the two unsigned values are compared. Since they are both 4,294,967,285, the comparison indicates they are equal.
72,549,975
72,549,989
c++ code will not return my trigonometry table (beginner)
I am currently in an introduction to programming class, and still don't know much. My current assignment is to write a program that returns a table that gives the cosine, sine, and tangent for every 15 angles from 0 to 90. I don't believe my code has any bugs, but the code won't run. I'm not sure if my computer is just too trash or what. Here's the code: #define _USE_MATH_DEFINES #include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { double ang_deg = 0; double ang_rad = 0; while (ang_deg < 91); { ang_rad = (ang_deg * M_PI) / 180.0; cout << setw(7) << "ANGLE" << setw(7) << "SIN" << setw(7) << "COS" << setw(7) << "TAN" << endl; cout << fixed << setprecision(3); cout << setw(7) << ang_deg << setw(7) << sin(ang_rad) << setw(7) << cos(ang_rad) << setw(7) << tan(ang_rad) << endl; ang_deg += 15; } return 0; } I have had a diagnostics running for about 10 minutes. My other programs have took about 30 seconds. My IDE and console which should have my table
Here's a bug while (ang_deg < 91); should be while (ang_deg < 91) Your version is an empty while loop, because the loop is empty ang_deg never changes and so the loop never terminates. That's why your program seemed not to run (in fact it did run, but it never finished). Sometimes the smallest things can be errors.