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,920,015
72,920,050
"static const" function and variable
I read so many answers saying static const functions can't exist. Eg. this Q&A. and this Q&A What if this is the use case: #include<iostream> using namespace std; class Sample{ static const int privx; static int privy; public: static int getPrivx(){ return privx; } static int getPrivy(){ // privy += 100;// I want to avoid changes in static variables through a static function => I need const static function return privy; } }; const int Sample::privx = 90; int Sample::privy = 100; int main(){ cout<<Sample::getPrivx()<<endl; cout<<Sample::getPrivy()<<endl; } So, use case: There are a lot of static variables declared in class. During development phase, I want to prevent developer from manipulating values of these static variables via operations inside a (static) function. Basically, compiler must shoot error saying changing value in static variable not allowed. The exact reason why const methods are used for i.e. no manipulations inside it (to calling object members of course). What are your solutions? I think a static & const function must be allowed as: static int getPrivy() const{} P.S. I asked this question before without considering const functions syntax => hence readers may find unrelated answers. Apologies.
This code is illegal, it's const qualified static method class Sample{ public: static int fun() const { return 0; } }; This code is OK, it's a const qualified non-static method class Sample{ public: int fun() const { return 0; } }; This code is OK, it's a static method with a const return type class Sample{ public: static const int fun() { return 0; } }; I guess the problem is that you don't realise what it means that a method is const. It has nothing to do with the return type, it's about the type of the this pointer within the method (as the quote says).
72,920,343
72,920,565
How to ensure a weak_ptr is not created from a temporary shared_ptr?
Let's have class Foo and method void use_weak_ptr(std::weak_ptr<Foo>). Is there a way to ensure - preferably at compile time - that the method is not called with temporary? Allow this: auto shared = std::make_shared<Foo>(); use_weak_ptr(shared); Do not allow this: use_weak_ptr(std::make_shared<Foo>()); Edit: Godbolt with suggestions.
You "poison" overload resolution on rvalues void use_weak_ptr(const std::shared_ptr<Foo>&&) = delete; void use_weak_ptr(std::weak_ptr<Foo>);
72,920,442
72,920,486
CMake add list of subdirectories
In my CMake project I need to add a list of subdirectories. The correct way is not nice because I can not pass a list: add_subdirectory(Helpers) add_subdirectory(Lib1) add_subdirectory(Lib2) subdirs can pass a list, but is deprecated: subdirs(Helpers Lib1 Lib2) Is there a way to add subdirectories as a list? It seems like a common usecase. If not: Why was it discontinued?
You could use foreach(): foreach(SUBDIR IN ITEMS Helpers Lib1 Lib2 ) add_subdirectory(${SUBDIR}) endforeach() You could even wrap this in a custom function function(my_subdirs SUB1) foreach(SUBDIR IN ITEMS ${SUB1} ${ARGN}) add_subdirectory(${SUBDIR}) endforeach() endfunction() ... my_subdirs( Helpers Lib1 Lib2 )
72,920,641
72,920,677
How to simulate EAGAIN or EWOULDBLOCK when send data to socket
I have a non-blocking socket to send data to. When sending data to a socket in non-blocking mode, we can get EAGAIN or EWOULDBLOCK if there is not enough space in the socket buffer. If the send call returns EAGAIN or EWOULDBLOCK, I subscribe to the EPOLLOUT event in epoll to know when the socket is ready to resend data in future. However, in practice, I have never been in a situation where send would return EAGAIN or EWOULDBLOCK and i am not get EPOLLOUT event from epoll. For this reason, I can't test code that resend data when the EPOLLOUT event is received. How i can test my code in this case?
How i can test my code in this case? This depends a lot on your kind of application and protocol. In general to trigger the condition the socket write buffer needs to fill up. This can be done by sending lots of data and making sure that the receiver application does not read from the socket. But this will not work if your specific application protocol does not allow for this, like application protocol has small message size and expects every message to be acknowledged by recipient before transmitting next. This can also be done by decreasing the size of the socket buffer (using setsockopt with SO_SNDBUFSIZ) - but it is not clear if the minimal buffer size is sufficient to trigger the condition in your specific use case.
72,920,805
72,920,848
How versatile are c++'s templates?
I want to write a highly optimized code in C++ and there is a templated structure which takes a type variable T. There is one function wow() in that structure that can be optimized to run twice faster if and only if the size of T is a power of 2. Can I use the better version of wow() without doing branching (use if or something) at the beginning of every call to wow()? I understand (I hope I do) that C++ creates a copy (or better say instantiation) of my structure for every type T I use it with, so can I tell that "struct builder" which version of wow() to use depending on the size of T?
I would use constexpr if and std::has_single_bit: #include <bit> template<class T> struct foo { void wow() { if constexpr (std::has_single_bit(sizeof(T))) { // sizeof(T) is a power of two } else { // not a power of two } } };
72,920,862
72,920,923
Why does template ordering matter when defining a method?
I have the following code: template<int n> struct array_container{double arr[n];}; template<int n> struct avg{ double first[n], second[n]; template <int q> array_container<q> get_avg(double p) const; }; I can add a definition for get_avg like this: template<int n> template<int q> array_container<q> avg<n>::get_avg(double p) const{ array_container<q> result; const int m = min(n,q); for(int k=0;k<m;k++){result.arr[k] = p*first[k] + (1-p) * second[k];} return result; } If I were to replace the first two lines of the definition, namely: template<int n> template<int q> with any one of these: template<int q> template<int n> template<int n, int q> template<int q, int n> compilation would fail . Why is this so? I see no significance in the order of the templates when defining for array_container<q> avg<n>::get_avg(double p) const . Edit: I understand that in the current standard the ordering of the template parameter clauses in the definition must correspond exactly to that of the declaration. My question is relating to the design of the language. Is there any reason, relating to logic or consistency, why my alternative examples could not be considered equally as valid? Especially since the compiler can already deduce the correct candidate if I provide it with an "incorrect" ordering.
Why is this so? Because when providing an out-of-class definition the first parameter clause template<int n> corresponds to the outermost enclosing class template while the second parameter clause template<int q> corresponds to the member template get_avg itself. More importanty when providing an out-of-class definition for the member template, the outermost parameter clause(for the class template(if any)) must come first, then the clause for the member templates(if any) . template<int n> //parameter clause corresponding to the outermost class template template<int q> //parameter claluse corresponding to the the member template itself array_container<q> avg<n>::get_avg(double p) const{ array_container<q> result; const int m = min(n,q); for(int k=0;k<m;k++){result.arr[k] = p*first[k] + (1-p) * second[k];} return result; }
72,920,894
72,921,342
Reference to a vector element become invalid after n iterations
Program stop occur in this line guess = secret; From that, I guess that reference is broken, because if I change reference to simple value const string secret = word_list[idx_word]; the program finishes correctly. So, my question is why this happen. The word_list is not changed/resided in loop. Erorr occur on 392 iteration. #include <QCoreApplication> #include <QFile> #include <QDir> #include <QVector> #include <cmath> #include <algorithm> #include <iostream> #include <map> #include <set> #include <thread> #include <mutex> #include <iomanip> #include <string> using namespace std; bool debug = true; const int COUNT = 5; string MASK_FULL_MATCH(COUNT, 'o'); const string getMask(const string& word, const string& answer) { if (word.size() != COUNT || answer.size() != COUNT) { cout << word.size() << " " << answer.size() << endl; } char mask[5]; bool visited[5]; for (int i = 0; i < COUNT; i++) { mask[i] = 'x'; visited[i] = false; } // find correct letters for(int i = 0; i < COUNT; i++){ if (word[i] == answer[i]){ mask[i] = 'o'; visited[i] = true; } } // find present letters for (int i = 0; i < COUNT; i++){ if (mask[i] != 'o'){ for (int j = 0; j < COUNT; j++) { if (answer[j] == word[i] && !visited[j]) { mask[i] = '-'; visited[j] = true; break; } } } } return string(mask, COUNT); } int main(int argc, char *argv[]) { QString pathToFile = QString("C:/Users/Ivan/Desktop/w_assets/w") + QString::number(COUNT) + QString("_entropy.txt"); QFile file(pathToFile); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return -2; QTextStream in(&file); QVector<string> word_list; while (!in.atEnd()) { QString line = in.readLine(); word_list.append(line.split(QChar(' '))[0].toStdString()); } file.close(); for (int idx_word = 0; idx_word < word_list.size(); idx_word++) { const string &secret = word_list[idx_word]; cout << secret << '\t'; } int total = 0; for (int idx_word = 0; idx_word < word_list.size(); idx_word++) { const string &secret = word_list[idx_word]; cout << "NEW SECRET " << secret << endl; QVector<string> possible_answers = word_list; for (int row = 0; row < 6; row++) { string guess; if (row == 0) { guess = word_list[0]; } else { cout << "before broken secret\n"; guess = secret; cout << "after broken secret\n"; cout << "row " << row << "; GUESS " << guess << endl; } debug = true; string mask = getMask(guess, secret); debug = false; cout << "MASK: " << mask << endl; if (mask == MASK_FULL_MATCH) { break; } QVector<string> new_possible_answers; for (const auto& pa : possible_answers) { if (getMask(guess, pa) == mask) { new_possible_answers.append(pa); } } possible_answers = new_possible_answers; cout << "NEW POSSIBLE WORDS SIZE " << possible_answers.size() << endl; } } return 0; }
word_list[0]; - this is a non-const operation in a QVector (see documentation, there is even a note about the possible detach) and since the reference count of your word_list is two due to the copy to possible_answers some lines above, the container has to do a detach and therefore your reference goes out of scope. If you work with references on Qt containers you have to make sure to either have a reference count of 1 or only use const-access to the container (e.g. by creating a const ref to the container -> const auto &const_word_list = word_list; guess = const_word_list [0])
72,920,937
72,924,499
How to get the number of fields in a boost-hana adapted struct?
Say I have the following struct: struct MyStruct { int field1; float field2; }; I would like to obtain the number of fields in the struct using boost-hana. #include <boost/hana/adapt_struct.hpp> BOOST_HANA_ADAPT_STRUCT(MyStruct, position, field1, field2); // this code does not work: constexpr std::size_t NUMBER_OF_FIELDS = boost::hana::length<MyStruct>(); static_assert(NUMBER_OF_FIELDS == 2); How to get the number of fields in a boost-hana adapted struct?
Hana specifically aims to simplify meta-programming by lifting type functions to the constexpr domain. In plain English: you shouldn't be using length<> as a "type function template" but as a normal function: Live On Coliru struct MyStruct { int position; int field1; float field2; }; #include <boost/hana.hpp> BOOST_HANA_ADAPT_STRUCT(MyStruct, position, field1, field2); constexpr std::size_t NUMBER_OF_FIELDS = boost::hana::size(MyStruct{}); static_assert(NUMBER_OF_FIELDS == 3); int main(){}
72,920,979
72,924,031
Win32 Handle WM_NOTIFY message from Rich Edit Control
How can I retrieve information about what change is being made in a rich edit control when handling WM_NOTIFY? More specifically, I am confused because in the documentation for WM_NOTIFY it says that lParam points to an NMHDR structure but in the page for EN_CHANGE they say that lParam points to a CHANGENOTIFY structure. What does lParam point to exactly?
If you read the EN_CHANGE documentation you linked to more carefully, you will notice this caveat: https://learn.microsoft.com/en-us/windows/win32/controls/en-change--rich-edit-control- Notifies a windowless rich edit control's host window that a change has occurred. A rich edit control sends this notification code in the form of a WM_NOTIFY message. See Windowless Rich Edit Controls for more details. And, as you noted, this message's CHANGENOTIFY struct does not conform to the standard use of WM_NOTIFY. The message carries only the RichEdit's control ID in the wParam, there is no NMHDR* in the lParam. If you are using a windowed Rich Edit control instead (which I assume you are), then it uses the same EN_CHANGE message that standard Edit controls use: https://learn.microsoft.com/en-us/windows/win32/controls/en-change Sent when the user has taken an action that may have altered text in an edit control. Unlike the EN_UPDATE notification code, this notification code is sent after the system updates the screen. The parent window of the edit control receives this notification code through a WM_COMMAND message. ... Rich Edit: Supported in Microsoft Rich Edit 1.0 and later. To receive EN_CHANGE notification codes, specify ENM_CHANGE in the mask sent with the EM_SETEVENTMASK message. For information about the compatibility of rich edit versions with the various system versions, see About Rich Edit Controls.
72,921,003
72,923,894
Why does RegOpenKeyExA fail to open a key path with a space in the name?
Why does RegOpenKeyExA throw a path not found error according to the error codes from Microsoft docs other paths (no spaces) do open flawlessly int res; HKEY hKey; res = RegOpenKeyExA(HKEY_CURRENT_USER, "SOFTWARE\\Policies\\Microsoft\\Windows Defender", 0, KEY_QUERY_VALUE|KEY_WRITE|KEY_READ|KEY_SET_VALUE, &hKey); std::cout << " Error code ["+res+"]"<<std::endl; the error code I am getting is 2 I am running the compiled executable as admin
RegOpenKeyEx() allows spaces just fine. MANY Registry keys have spaces in their names. Error 2 is ERROR_FILE_NOT_FOUND, which means the key you are trying to open does not exist. And indeed, the Windows Defender key does not exist in HKEY_CURRENT_USER, it exists in HKEY_LOCAL_MACHINE instead. BTW, KEY_WRITE includes KEY_SET_VALUE (among others), and KEY_READ includes KEY_QUERY_VALUE (among others), so technically you are opening the key with just KEY_WRITE|KEY_READ. Which is likely to fail unless your program is running with elevated permissions, since most of HKEY_LOCAL_MACHINE is read-only to non-admin users. It is rarely of good idea to open a key under HKEY_LOCAL_MACHINE for both read and write permissions at the same time. If you need to read something, open the key for read-only access, which is likely to succeed. If you need to write something, open the key for write-only access, which will succeed only if you have permission to write.
72,921,071
72,921,365
binary '<': no operator found which takes a left-hand operand of type 'const _Ty' glm::vec3 in map
I've been dabbling with discregrids LRUCache, but I'm having trouble getting it working with glm's vec3's. I keep getting a binary '<': no operator found which takes a left-hand operand of type 'const _Ty' error, even though I've implemented an operator overload for the underlying std:map [file.hpp]: bool operator<(const glm::vec3& lhs, const glm::vec3& rhs) { return lhs.x < rhs.x || lhs.x == rhs.x && (lhs.y < rhs.y || lhs.y == rhs.y && lhs.z < rhs.z); } template <typename K, typename V> class LRUCache { using key_type = K; using value_type = V; using key_tracker_type = std::list<key_type>; using key_to_value_type = std::map<key_type, std::pair<value_type, typename key_tracker_type::iterator>>; ... } LRUCache<glm::vec3, double>
The short form is your operator< is not being found due to how ADL works. In particular, C++ searches the namespaces of the arguments (and their base classes, and other related classes). You've placed operator< in the global namespace, which is not the glm namespace. So, you could either put the comparison in the glm namespace (Which I don't really recommend), or create a comparison function object, and use that. struct MyCompare{ bool operator()(const glm::vec3& lhs, const glm::vec3& rhs) const { return lhs.x < rhs.x || lhs.x == rhs.x && (lhs.y < rhs.y || lhs.y == rhs.y && lhs.z < rhs.z); } }; And then use it with std::map<key_type, std::pair<value_type, typename key_tracker_type::iterator>, MyCompare> If you don't want ordering, you can also look at unordered_map, if you can develop a reasonable hashing function (or if it comes with one).
72,921,127
72,922,577
Why is my thread execution jumping between CPU cores?
I recently started experimenting with std::thread and I tried running a small program that displays the webcam feed in a separate thread and I am using OpenCV. I am just doing this for "educational" purposes. What I noticed was that the thread seemed to keep jumping between cores which striked me as odd since I thought that the overhead of this change would not be worth it from an efficiency/performance side of view. Does anybody know the root/reason for such behavior? Short disclaimer --> I am new to StackOverflow so if I missed something, please let me know. A snapshot of my system monitor - Ubuntu #include <stdio.h> #include <opencv2/opencv.hpp> //openCV functionality #include <time.h> //timing functionality #include <thread> using namespace cv; using namespace std; void webcam_func(){ Mat image; namedWindow("Display window"); VideoCapture cap(0); if (!cap.set(CAP_PROP_AUTO_EXPOSURE , 10)){ std::cout <<"Exposure could not be set!" <<std::endl; //return -1 ; } if (!cap.isOpened()) { cout << "cannot open camera"; } int i = 0; while (i < 1000000) { cap >> image; Size s = image.size(); int rows = s.height; int cols = s.width; imshow("Display window", image); double fps = cap.get(CAP_PROP_FPS); //cout << "Frames per second using video.get(CAP_PROP_FPS) : " << fps << endl; //cout <<"The height of the video is " <<rows <<endl; //cout <<"The width of the video is " <<cols <<endl; std::thread::id this_id = std::this_thread::get_id(); std::cout << "thread id --> " << this_id <<std::endl; waitKey(25); i++ ; std::cout <<"Counter value " <<i <<std::endl; } } int main() { std::thread t1(webcam_func); while(true){ } return 0; }
The default Linux scheduler schedule tasks (eg. threads) for a given quantum (time slice) on available processing units (eg. cores or hardware threads). This quantum can be interrupted if a task enters in sleeping mode or wait for something (inputs, locks, etc.). waitKey(25) exactly does that: it causes your thread to wait for a short period of time. The thread execution is interrupted and a context-switch is done. The OS can execute other tasks during this time. When the computing thread is ready again (because >25 ms has elapsed), the scheduler can schedule it again. It tries to execute the task on the same processing unit so to reduce overheads (eg. cache misses) but the previous processing unit can be still used by another thread when the computing task is being scheduled back. This is unlikely to be the case when there is not many ready tasks or just greedy ones though. Additionally, some processors supports SMT (aka. hyper-threading). For example, many x86-64 Intel processors supports 2 hardware threads per core sharing the same caches. Context-switches between 2 hardware threads lying on the same core are significantly cheaper (eg. far less cache-misses). Also note that the Linux scheduler is not perfect like most other schedulers. In fact, it was bogus few years ago and not even able to fill all available cores when it was possible (see: The Linux Scheduler: a Decade of Wasted Cores). Finally, note that the (direct) overhead of a context-switch is no more than few dozens of micro-seconds on a mainstream Linux PC so having them every few dozens of milliseconds is fine (<1% overhead).
72,921,359
72,921,562
Dereferencing a string pointer from a FreeRTOS queue
I'm trying to use the queue API that FreeRTOS provides to read a string data from an Interrupt Service Routine (ISR) on an ESP32 device. As strings are quite large data, I actually send the address of the string using a pointer. This seems to work as I can read the correct pointer adress (see example below). However, I'm stuck to understand why I'm unable to get the string value when dereferencing this pointer. I'm not used to deal with pointers but reading various examples on the web, I don't see what I'm doing wrong. QueueHandle_t qGsmEventData; void IRAM_ATTR ISR_GSM_RI(){ BaseType_t xHigherPriorityTaskWoken = pdFALSE; String sGsmEventData = "String sent from ISR"; String * pGsmEventData = &sGsmEventData; Serial.print("Pointer address added to queue: "); Serial.println((unsigned int)pGsmEventData); Serial.print("String length: "); Serial.println(sGsmEventData.length()); xQueueSendToBackFromISR(qGsmEventData, &pGsmEventData, &xHigherPriorityTaskWoken); } void setup() { [...] qGsmEventData = xQueueCreate(10, sizeof(String *)); attachInterrupt(digitalPinToInterrupt(GSM_INT_PIN), ISR_GSM_RI, RISING); } void loop() { String *pGsmEventData; xQueueReceive(qGsmEventData, &(pGsmEventData), portMAX_DELAY); Serial.print("Pointer address get from queue: "); Serial.println((unsigned int)pGsmEventData); String sGsmEventData = *pGsmEventData; Serial.print("String length: "); Serial.println(sGsmEventData.length()); delay(500); } and i'm getting on the serial console output : Pointer address added to queue: 1073475016 String length: 20 Pointer address get from queue: 1073475016 String length: 0 So the queue seems to work as I get the correct pointer address but why I get a 0 length string when dereferencing this pointer ? How to get the string value ?
Basically the pointers outlive the objects they point to. Let's break the ISR down as an example: void IRAM_ATTR ISR_GSM_RI(){ BaseType_t xHigherPriorityTaskWoken = pdFALSE; String sGsmEventData = "String sent from ISR"; //string is created on the stack String * pGsmEventData = &sGsmEventData; //its address is taken Serial.print("Pointer address added to queue: "); Serial.println((unsigned int)pGsmEventData); Serial.print("String length: "); Serial.println(sGsmEventData.length()); //String object is valid thus so are the logs xQueueSendToBackFromISR(qGsmEventData, &pGsmEventData, &xHigherPriorityTaskWoken); //its address is sent } //string's destructor is called, it no longer exists //pointer points to now empty place in memory After reception, you're dereferencing the no longer valid pointer, so anything can happen really, the behaviour is undefined. And this is generally true for objects of any type, save string literals.
72,921,565
72,921,747
How to get two threads to work on the shared resource
I have a С++ class that has a databases_list_ vector defined. This vector contains database objects. I need to make two functions that will run on separate threads. And each function will use the databases_list_ vector. That is, this vector is a shared resource for my functions. In this case, I don't know the correct approach to secure the share so that every thread can use it. // This is class Worker class Worker { private: std::thread check_oo_thread_{}; // thread #1 std::thread check_db_thread_{}; // thread #2 void check_oo(); // func #1 void check_db(); // func #2 std::vector<std::unique_ptr<database>> databases_list_; // This is a shared resource bool is_work_{ false }; } // Here I am running two threads void Worker::start() { is_work_ = true; check_oo_thread_ = std::thread(&Worker::check_oo, this); check_db_thread_ = std::thread(&Worker::check_db, this); } And here are two functions that use the databases_list_ vector in different threads. The difference is that these functions get different data from the database - it depends on the command_type parameter // In this function, each database object is called in turn void Worker::check_oo() { while (is_work_) { for (auto& db : databases_list_) { auto db_cfg = db->get_cfg(); data_handler_.set_database(db_cfg.db_server); auto db_respond = db->send_command(receive_cmd, command_type::get_data); } std::this_thread::sleep_for(std::chrono::seconds(processing_period_1)); } } // In this function, each database object is called in turn void Worker::check_db() { while (is_work_) { for (auto& db : databases_list_) { auto db_cfg = db->get_cfg(); data_handler_.set_database(db_cfg.db_server); auto db_respond = db->send_command(receive_cmd, command_type::get_stat); } std::this_thread::sleep_for(std::chrono::seconds(processing_period_2)); } } This is a tricky case for me and I can't figure out how to get two threads to work on the shared resource databases_list_.
You can lock a std::mutex every time you want to access the shared resource. You also access is_work_ from multiple threads and I therefore suggest making that std::atomic<bool> is_work_ instead. #include <atomic> #include <mutex> class Worker { private: std::thread check_oo_thread_{}; // thread #1 std::thread check_db_thread_{}; // thread #2 mutable std::mutex m_mtx; // use this to sync actions on your resource std::atomic<bool> is_work_{}; // now atomic void check_oo() { while(is_work_) { { std::lock_guard<std::mutex> lock{m_mtx}; // locks the mutex // use databases_list_ here } // mutex is unlocked here std::this_thread::sleep_for(...); } } void check_db() { while(is_work_) { { std::lock_guard<std::mutex> lock{m_mtx}; // use databases_list_ here } std::this_thread::sleep_for(...); } } std::vector<std::unique_ptr<database>> databases_list_; };
72,921,596
72,948,819
How to automatically append gtkwidget in new line when no horizontal space is available in gtkbox?
Let's say I have the following code m_box=gtk_box_new(GTK_ORIENTATION_HORIZONTAL,4); gtk_widget_set_halign (m_box, GTK_ALIGN_START); gtk_widget_set_valign (m_box, GTK_ALIGN_START); Now I am adding multiple widgets and running out of horizontal space. How can I make it responsive? NOTE:- I am using gtk4
This is not something a GtkBox can do. It's quite "dumb" in that it doesn't care about reflowing or anything like that. It does one thing and one thing only: putting child widgets next to each other in a specific orientation. For your use case, you might be more interested in Gtk.FlowBox, which rearranges its children when it can't allocate enough space
72,921,983
72,922,085
C++ spaceship-operator and user-defined types: comparing a subset of attributes only
I have two classes. The first one composing the second one. Both classes have its own synthetized attribute that doesn't collaborate to either ordering or comparision. In addition, I want to usestd::ranges::sort over a container of the second one, so I need to implement a strong-ordering. That's what I have: struct basic { std::string synthetized; // string representation of the next field. unsigned value; unsigned property; friend bool operator<(basic const& a, basic const& b) { return a.value < b.value or (a.value == b.value and a.property < b.property); } }; struct composed { basic value; custom_type meta; friend bool operator<(composed const& a, composed const& b) { return a.value < b.value; } }; int main() { std::vector<composed> container; // populating container // Compilation error here. std::ranges::sort(container); } How should I appropiately efficiently overload operator<=>? Although what I need is to sort the vector and that's it (I could just go to traditional std::sort), I want to know how to give to both classes full relational capabilities (<, <=, ==, !=, etc) to both classes, but ignoring synthetized and meta, and without doing anything stupid performance-wise.
How should I appropiately efficiently overload operator<=>? The simplest way to do both would probably be to use std::tie and use the existing function template for operator<=> for tuple types: template< class... TTypes, class... UTypes > constexpr /* see link */ operator<=>( const std::tuple<TTypes...>& lhs, const std::tuple<UTypes...>& rhs ); Example: #include <tuple> struct basic { std::string synthetized; // excluded from comparisons unsigned value; unsigned property; friend auto operator<=>(basic const& a, basic const& b) { return std::tie(a.value, a.property) <=> std::tie(b.value, b.property); } }; struct composed { basic value; custom_type meta; // excluded from comparisons friend auto operator<=>(composed const& a, composed const& b) { return a.value <=> b.value; } }; You should also add operator== which will also be used for != so you don't have to overload operator!=.
72,922,675
72,946,528
Google S2 Geometry: polygon contains check does not work as expected
I'm using the Google S2 Geometry library to check whether a given geo point is within a polygon. The following assertion should pass, but is failing and I'm unable to explain what's going wrong: std::vector<S2Point> vertices = { S2LatLng::FromDegrees(60, -118).ToPoint(), S2LatLng::FromDegrees(23, -118).ToPoint(), S2LatLng::FromDegrees(23, 34).ToPoint(), S2LatLng::FromDegrees(60, 34).ToPoint(), }; auto loop = new S2Loop(vertices, S2Debug::DISABLE); S2Point p = S2LatLng::FromDegrees(42.716450, -67.079284).ToPoint(); ASSERT_TRUE(loop->Contains(p)); The point is certainly within the polygon indicated by the vertices but S2 says that the point is not inside.
S2 uses geodesic edges, so the loop is not just a rectangle on a flat map, but the "horizontal" edges are curved towards the poles following the shortest path on spherical Earth. For small distances, the difference from planar maps are negligible, but for huge distances like here the shortest path is quite different. The loop and the point can be seen on the picture below, and the loop does not contain the point: BTW, to visualize the loop and the point on this picture, I used Google's BigQuery GeoViz tool (you need to setup BigQuery account, free tier should be enough). It might be a good debugging tool for S2. You can read more about it here: https://cloud.google.com/bigquery/docs/geospatial-visualize#geo_viz. I used the following query (in SQL the order of coordinates is longitute-latitude): select st_geogfromtext('polygon((-118 60, -118 23, 34 23, 34 60, -118 60))') p union all select st_geogpoint(-67.079284, 42.716450);
72,923,419
72,923,454
Compile C++ Code Using The Terminal Directly Without Save File.cpp
I need to compile C++ code directly in the terminal or CLI without saving the file When is use the below way, It shows me an error. gcc -x c - <<eof #include <iostream> using namespace std; int main() { cout << "Hello world"; } eof
You are trying to compile a C++ program using a C compiler. This works: g++ '-xc++' - <<eof #include <iostream> using namespace std; int main() { cout << "Hello world"; } eof
72,924,024
72,926,021
Slicing and Indexing Eigen matrix Error: how to index matrix correctly?
I have matrix u with size 11 by 15 where 11 is number of rows and 15 number of columns. I am trying to index my matrix so that the first five columns and the last five columns are equal to some expression. I am able to index the first 5 columns but not last 5 as the following: static const int nx = 10; static const int ny = 10; static const int mm = nx* 3/2; Eigen::Matrix<std::complex<double>, (ny+1), mm> u; u.setZero(); u(all,seqN(0,nx/2)) u(all,seqN(last-nx/2,last)) //ERROR The second indexing is incorrect, and it resturns the error: Eigen::Block<XprType, BlockRows, BlockCols, InnerPanel>::Block(XprType&, Eigen::Index, Eigen::Index, Eigen::Index, Eigen::Index) [with XprType = Eigen::Matrix<std::complex<double>, 11, 15>; int BlockRows = 11; int BlockCols = -1; bool InnerPanel = true; Eigen::Index = long int]: Assertion `startRow >= 0 && blockRows >= 0 && startRow <= xpr.rows() - blockRows && startCol >= 0 && blockCols >= 0 && startCol <= xpr.cols() - blockCols' failed. How can I index this properly.
Thanks to @chtz from the comments, this fixed the issue: seq(last+1-nx/2, last)
72,924,527
72,924,578
retrive username and domain with GetUserNameExA
I am trying to get username and domain with GetUserNameExA function this is my code #include <windows.h> #include <Lmcons.h> #include <iostream> using namespace std; #include <windows.h> #include <Lmcons.h> #include <Security.h> #include <secext.h> DWORD main() { CHAR *username = [200]; DWORD dwSize = 199; memset(username, 0x00, 200); GetUserNameExA(NameSamCompatible, username, &dwSize); wcout << L"Hello, " << NameSamCompatible << L"!\n"; } but keep getting an error that you need to declare an identifer can you plz help me to figure it out?
CHAR *username = [200]; should be this char username[200]; And this wcout << L"Hello, " << NameSamCompatible << L"!\n"; should be this cout << "Hello, " << username << "!\n";
72,925,058
72,925,102
Creating variadic template with template object containing string
I want to create a template that will take variadic number of a specific class that contains a string. When i try to make such a template class, it throws no instance of constructor "A" matches the argument list class A: template<template_string s> class A {}; class B: template<A... As> class B {}; template_string.h: template<size_t _N> struct template_string { char c_str[_N]; constexpr template_string(const char(&text)[_N]) { std::copy(text, text+_N, c_str); } constexpr std::string std_str() const noexcept { return std::string(c_str); } constexpr std::string_view str_view() const noexcept { return std::string_view(c_str); } constexpr size_t length() const noexcept { return _N-1; } }; I want to make it explicitly through templates and classes. What would i need to do so that I can construct class B like this: B<A<"text">(), A<"other text">(),....> b;
This is an instance of the "most vexing parse" problem, where it looks like you are declaring a function type instead of creating on object. Here's a complete working example, where I've replaced the function call () with the uniform initialization syntax {}: #include <cstddef> #include <string> using std::size_t; template<size_t _N> requires (_N >= 1) struct template_string { char c_str[_N]; constexpr template_string(const char(&text)[_N]) { std::copy(text, text+_N, c_str); } constexpr std::string std_str() const noexcept { return std::string(c_str); } constexpr std::string_view str_view() const noexcept { return std::string_view(c_str, length()); } constexpr size_t length() const noexcept { return _N-1; } }; template<template_string s> class A {}; template<A... As> class B {}; int main() { [[maybe_unused]] B<A<"text">{}, A<"other text">{}> b; } The other thing I did was create the string_view with the length of the string, just in case the string contains NUL bytes, as in "hello\0there".
72,926,596
72,926,617
Type deduction for a member function pointer
I know there are similar questions on SO, but the usages there seem different to what I have. Here is my MRE: #include <iostream> #include <functional> using namespace std; void freeFunction() {} struct Foo { void memberFunction() {} }; template<typename FunctionPtrT> void foo(FunctionPtrT* f) { f(); } template<typename InstanceT, typename FunctionPtrT> void bar(InstanceT&& i, FunctionPtrT f) { std::mem_fn(f)(i); } template<typename InstanceT, typename FunctionPtrT> void baz(InstanceT&& i, FunctionPtrT* f) {} int main() { foo(&freeFunction); //Ok, obviously bar(Foo(), &Foo::memberFunction); //Ok, how?! // Error: candidate template ignored: could not match 'FunctionPtrT *' against 'void (Foo::*)()' baz(Foo(), &Foo::memberFunction); //why?! return 0; } Why is &Foo::memberFunction not resolving to a pointer? What is the type of f in bar? If it's not a pointer how am I able to pass it to std::mem_fun that is defined as template< class M, class T > /*unspecified*/ mem_fn(M T::* pm) noexcept;?
General suggestion for type investigations I think the easiest way to answer questions like "what is the type of x in this context" is to put a static_assert(std::is_same_v<void, delctype(x)>); in that same context. The compiler will then tell you the static_assertion failed because void is not equal to the type of x, revealing what that type is. is &Foo::memberFunction a pointer? And there are variations of that. For instance, if you truly want to know wheter &Foo::memberFunction is a pointer, then ask it this way: static_assert(std::is_pointer_v<decltype(&Foo::memberFunction)>); and the compiler will tell you something along the lines of Static_assert failed due to requirement 'std::is_pointer_v<void (Foo::*)()>' [static_assert_requirement_failed] so it just can't match against FunctionPtrT*. As regards What is the type of f in bar? if you put static_assert(std::is_same_v<void, decltype(f)>); inside of bar, the compiler will tell you Static_assert failed due to requirement 'std::is_same_v<void, void (Foo::*)()>' meaning that the type of f is void(Foo::*)(). How does &Foo::memberFunction's type from a free function pointer? Compare this with the error you get if you define void f(); and assert static_assert(std::is_same_v<void, decltype(f)>); The compiiler will tell you Static_assert failed due to requirement 'std::is_same_v<void, void (*)()>' So the point is that void(*)(), a pointer to a free function from void to void, is different from void (Foo::*)(), a pointer member of Foo function from void to void. How can I restrict a template to be instatiated only for member functions? If you want your template to match only member functions, can go for template<typename InstanceT, typename R, typename C> void baz(InstanceT&& i, R C::* f) { } or, if you want it to match any member function of Foo, you can clearly either change the order of the template parameters such that you can provide C manually template<typename C, typename R, typename InstanceT> void baz(InstanceT&& i, R C::* f) { } which allows you to call baz<Foo>(/* args */);, or you can simply hardcode Foo in place of C: template<typename R, typename InstanceT> void baz(InstanceT&& i, R Foo::* f) { } And what if I want to restrict the match to member function with a specific signature? As you see, we already have a placeholder R, for the return type. If we also wanted to have a placeholder for the arguments, we could go for this: template<typename R, typename C, typename ...Args> void baz(R (C::*f)(Args...)); Which will just match the same function as the previous example. I showed this just to make you see that, if you want to type the arguments out, you must put parenthesis around C::*f, or just C::*, if you want to omit the name (the lack of parenthesis is the typo in the comment under your question). Therefore, if you want to restrict the match to a specific signature, let's say void(), this is how you do it: template<typename C> void baz(void (C::*f)());
72,926,648
72,926,709
how to map a class object and instantiate it
I'm trying to mimic this Python functionality: class Bla: def __init__(self, arg): self.arg = arg {"bla": Bla}["bla"](None) # create a Bla class dynamically I looked at this but it didn't help me... My C++ module looks something like this: // MyObj is an abstract class with all its subclasses using same signature constructor class Factory{ MyObj create_obj(int n); } std::map<std::string, MyObj> my_map = {"example1", MyObj1}; my_map["example1"](0); How can I make this work?
C++, in contrast to Python, is statically typed. Classes are not first-class objects and you can't store them. In the following I assume that MyObj is the abstract base that all "stored" types are meant to inherit from and that MyObj1/MyObj2 are some of these types. Instead of the classes themselves, you can store function pointers or std::functions which return a std::unique_ptr<MyObj> pointing to a newly-created object of the corresponding type, so that my_map["example1"](0); has a well-defined static type. For example: #include<functional> // for std::function #include<memory> // for std::unique_ptr and std::make_unique #include<type_traits> // for std::has_virtual_destructor_v //... template<typename T> std::unique_ptr<MyObj> MakeMyObj(int n) { static_assert(std::has_virtual_destructor_v<MyObj>); return std::make_unique<T>(n); } // or std::map<std::string, std::unique_ptr<MyObj>(*)(int)> std::map<std::string, std::function<std::unique_ptr<MyObj>(int)>> my_map = { { "example1", MakeMyObj<MyObj1> }, { "example2", MakeMyObj<MyObj2> } }; //... auto x = my_map["example1"](0); // x has type std::unique_ptr<MyObj> auto y = my_map["example2"](123); // y also has type std::unique_ptr<MyObj> std::function supports more types of callables than a function pointer approach would, but has significantly more runtime overhead. With the function pointer approach, trying to use an unassigned string argument will also result in undefined behavior, while the std::function approach will throw an exception. As mentioned in the other answer, a more straight-forward approach if you don't need to modify the map at runtime is to write a single factory function or class which directly switches on string arguments and throws an appropriate exception directly. In any case it is important that this requires that MyObj has a virtual destructor. Otherwise the program will have undefined behavior. That is what the static_assert is meant to protect against, since std::unique_ptr itself currently unfortunately doesn't verify that.
72,926,766
72,926,818
Recursive print within std::cout
The input is N spaced integers. You have to read the input and print the input backwards. Source:(https://www.hackerrank.com/challenges/arrays-introduction/problem?isFullScreen=false) One of the solutions is: #include <iostream> int main() { int N,i=0; std::cin>>N; int *A = new int[N]; while(std::cin>>A[i++]); // We have now iterated through the input and stored the // integers in a dynamically allocated array. // This line apparently prints out the Array (size N) backwards. while(std::cout<<A[--N]<<' ' && N); delete[] A; return 0; } How does while(std::cout<<A[--N]<<' ' && N); print out the array A backwards? How does it know to stop running the while loop? What does the expression ' ' && N do? My intuition of && tells me that it should equate to TRUE or FALSE, but what does ' ' have to do with Boolean?
The << operator (even though it's overloaded for output streams and is no longer a bitwise shift) has higher precedence than the && operator. Thus, we can add parentheses to your while statement to make it clearer: while ( (std::cout << A[--N] << ' ') && N ) ; The expression within the added parentheses will, on each loop, decrement the value of N (so, on the first loop, that will be reduced to the original value minus 1 – which is the index to the last element of the allocated array), output the integer element at that index, then output a space. The result of that 'chained' operation will be a reference to std::cout; that has an operator bool(), which returns true if the output succeeded and false in the event (unlikely, in the given code) of failure. That (probably) true value is then combined with the result of converting N to a Boolean value – and that conversion will yield true1 for an non-zero value and false` for zero … so the loop will stop when the index has been decrement to zero (referencing the first element of the array). When that N has reached zero, we no longer need to run the (empty) loop, because the output will already have been performed by the expression on the left of the && operator.
72,926,985
72,927,090
Pass array from C++ to C#
I need to pass an array from C++ to C# The C++ header is the following extern "C" GMSH_API void GMSH_Model_OCC_Fragments(int* arrayPtr); The C++ cpp is the following void GMSH_Model_OCC_Fragments(int* arrayPtr) { int array[] = {1,2}; arrayPtr = array; } The C# code is the following [DllImport("GMSHCSHARP.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void GMSH_Model_OCC_Fragments(out IntPtr arrayPtr); public void Create() { GMSH_Model_OCC_Fragments(out IntPtr arrayPtr); int[] ReturnArray = new int[2]; int size = Marshal.SizeOf(ReturnArray[0]) * ReturnArray.Length; Marshal.Copy(arrayPtr, ReturnArray, 0, size); } Seems that arrayPtr is transmitted as null and this causes the Marshal.Copy to return an error. I'd appreciate any help.
When you call C++ from C# you have to play by the rules of C++, so you cannot assign an array by arrayPtr = array; You can however fill an array given by C# C++ Function void someFunction(char* dest, size_t length){ char* someData = "helloWorld"; size_t copyLen = std::min(length, strlen(someData)); memcpy(dest, someData, copyLen); //If it was a string you'd also want to make sure it's null terminated } C# Function call (Something like this sorry if it's not 100%) [DllImport("MyDll.dll", CallingConvention = CallingConvention.CDecl)] private static extern void someFunction(Byte[] dest, uint Length); Byte[] array = new byte[10]; someFunction(array, 10); I'm not sure if you can pass heap memory out of C++, but if you can you would do this: void GMSH_Model_OCC_Fragments(int** dest){ *dest = new int[2]; *dest[0] = 1; *dest[1] = 2; } Note you need to use a double pointer to pass back memory in this fashion. As you need the first pointer to reference the object or array, and the second pointer to keep track of that.
72,927,080
72,927,806
How Could I Register Types With A Deleted Copy Constructor To QMetaType?
The Problem: I want to create an object instance at runtime using QMetaType by the type name. But I couldn't register the type because it's a QObject and I don't have access to the implementation to change it. Duplicate Question(s): How to properly use qRegisterMetaType on a class derived from QObject? I couldn't understand from the answer to where I have to define the specialization of qMetaTypeConstructHelper. Reproducible Example Of The Problem: The CMake: CMakeLists.txt #include <QMetaType> #include <QObject> class MyObject : public QObject { Q_OBJECT }; #include "main.moc" int main() { qRegisterMetaType<MyObject>("MyObject"); int const type_id = QMetaType::type("MyObject"); } It will fail: /tmp/untitled1/main.cc:12:3: note: in instantiation of function template specialization 'qRegisterMetaType<MyObject>' requested here qRegisterMetaType<MyObject>("MyObject"); ^ /tmp/untitled1/main.cc:4:18: note: copy constructor of 'MyObject' is implicitly deleted because base class 'QObject' has a deleted copy constructor class MyObject : public QObject { ^ /opt/Qt/5.15.2/gcc_64/include/QtCore/qobject.h:467:20: note: 'QObject' has been explicitly marked deleted here Q_DISABLE_COPY(QObject) ^
A Non-portable And Non-documented Solution: Specialize the QtMetaTypePrivate::QMetaTypeFunctionHelper for your type: namespace QtMetaTypePrivate { template <> struct QMetaTypeFunctionHelper<MyObject, true> { static void Destruct(void *address) { static_cast<MyObject *>(address)->~MyObject(); } static void *Construct(void *where, void const *address) { if (address != nullptr) { delete static_cast<MyObject const *>(address); } return where != nullptr ? new (where) MyObject : new MyObject; } }; } // namespace QtMetaTypePrivate Using QMetaObject, But Requires A Q_INVOKABLE Constructor: By not providing a Public Copy Constructor one solution is to register a pointer type: qRegisterMetaType<MyObject*>(); And then retrieve the type ID using "MyObject*" string and the QMetaObject using QMetaType::metaObjectForType: int const type_id = QMetaType::type("MyObject*"); QMetaObject const* metaObject = QMetaType::metaObjectForType(type_id); And now we could create an instance of the class: QObject* instance = metaObject->newInstance(); But still, we need to have an invokable public constructor: class MyObject : public QObject { Q_OBJECT public: Q_INVOKABLE MyObject() {} }; https://interest.qt-project.narkive.com/zP6wxOZf/how-to-create-qobject-derived-class-instance-from-class-name#post7
72,927,098
72,927,147
Recursive Type Dependencies in C++
#include <iostream> #include <cstdlib> class Egg; class Chicken; class Egg { public: Chicken *creator; Chicken getCreator() { if (!creator) return Chicken{}; return *creator; } }; class Chicken { public: Egg creator; Egg getCreator() { if (&creator == 0) return Egg{}; return creator; } }; void chicken_and_egg() { Chicken chicken; Egg egg; chicken.creator = egg; egg.creator = &chicken; Egg e = chicken.getCreator(); Chicken c = egg.getCreator(); if (&(chicken.creator) == &(c.creator) && &(egg.creator) == &(e.creator)) { using namespace std; cout << "the `Chicken and Egg' dilemma is solved!" << endl; } } int main() { chicken_and_egg(); return 0; } Does anybody know how to resolve the circular type dependencies in these two classes? The creator in Egg class is reported to have incomplete type Chicken. I have tried to mess around with pointers but so far have found no clue.
You need to define the member functions after the full definitions of the necessary classes have been seen. Example: class Egg; class Chicken; class Egg { public: Chicken* creator; Chicken getCreator(); // declaration only }; class Chicken { public: Egg creator; Egg getCreator(); // declaration only }; // definitions: Chicken Egg::getCreator() { if (!creator) return Chicken{}; return *creator; } Egg Chicken::getCreator() { // strange comparison removed return creator; }
72,927,480
72,927,732
Reading integers and strings from a text file and storing in parallel arrays
I have a text file that stores the index, student name and student ID and I am trying to read them into an array of integers index, arrays of strings studentName and studentID. I'm having problems storing the student's names because they could be more than a single word. I could separate the items in the text file by commas and use getline but that would mean the index array will have to be a string type. Is there a workaround for this without changing the original text file? Original file: 1 James Smith E2831 2 Mohammad bin Rahman M3814 3 MJ J4790 const int SIZE = 3; int index[SIZE]; string studentName[SIZE], studentID[SIZE]; fstream infile("students.txt"); if(infile.is_open()){ int i = 0; while(i < 3){ infile >> index[i] >> studentName[i] >> studentID[i]; i++; } } Changed file: 1,James Smith,E2831 2,Mohammad bin Rahman,M3814 3,MJ,J4790 const int SIZE = 3; string index[SIZE]; string studentName[SIZE], studentID[SIZE]; fstream infile("students.txt"); if(infile.is_open()){ int i = 0; while(i < 3){ getline(infile, index[i],','); //index array is string getline(infile, studentName[i],','); getline(infile, studentID[i],'\n'); i++; } }
It's an error to read one line into one student property with the given input format. You need to read one line and then split the information in this line into the 3 properties. std::stoi can be used to convert to convert the first part of the line read to an int. Futhermore it's simpler to handle the data, if you create a custom type storing all 3 properties of a student instead of storing the information in 3 arrays. Note that the following code requires the addition of logic to skip whitespace directly after (or perhaps even before) the ',' chars. Currently it simply includes the whitespace in the name/id. I'll leave that task to you. struct Student { int m_index; std::string m_name; std::string m_id; }; std::vector<Student> readStudents(std::istream& input) { std::vector<Student> result; std::string line; while (std::getline(input, line)) { size_t endIndex = 0; auto index = std::stoi(line, &endIndex); if (line[endIndex] != ',') { throw std::runtime_error("invalid input formatting"); } ++endIndex; auto endName = line.find(',', endIndex); if (endName == std::string::npos) { throw std::runtime_error("invalid input formatting"); } result.push_back(Student{ index, line.substr(endIndex, endName - endIndex), line.substr(endName + 1) }); } return result; } int main() { std::istringstream ss( "1,James Smith,E2831\n" "2, Mohammad bin Rahman, M3814\n" "3, MJ, J4790\n"); auto students = readStudents(ss); for (auto& student : students) { std::cout << "Index=" << student.m_index << "; Name=" << student.m_name << ";Id=" << student.m_id << '\n'; } }
72,927,672
72,927,734
CMake creating libraries that depend each other
my goal is to create libraries like client and generator and use them in src/main.cpp, but sometimes these libraries depend each other. In this case: client/User.hpp uses generator/IdGenerator.hpp Project │ ├── CMakeLists.txt ├── libs │   ├── CMakeLists.txt │   ├── client │   │   ├── CMakeLists.txt │   │   ├── User.cpp │   │   └── User.hpp │   └── generator │   ├── CMakeLists.txt │   ├── IdGenerator.cpp │   ├── IdGenerator.hpp │   └── Types.hpp └── src └── main.cpp Project/CMakeLists.txt: cmake_minimum_required (VERSION 3.8) project(game-project VERSION 0.1.0) set (CMAKE_CXX_STANDARD 20) set (CMAKE_CXX_FLAGS "-Wall -Wextra -O0 -std=c++20") add_executable (game src/main.cpp) add_subdirectory(libs) target_link_libraries(game libclient libgenerator) libs/CMakeLists.txt: add_subdirectory(generator) add_subdirectory(client) libs/client/CMakeLists.txt: add_library(libclient STATIC User.cpp User.hpp ) include_directories(generator/) target_link_libraries(libclient libgenerator) libs/generator/CMakeLists.txt: add_library(libgenerator STATIC IdGenerator.cpp IdGenerator.hpp Types.hpp ) C++ files: main.cpp: #include <client/User.hpp> int main(int argc, const char* argv[]) { User user; return 0; } client/User.hpp: #pragma once #include <generator/IdGenerator.hpp> class User { Identifier id = IdGenerator::generateId(); }; When I run make after cmake, I get this error: In file included from Project/libs/client/User.cpp:1: Project/libs/client/User.hpp:3:10: fatal error: generator/IdGenerator.hpp: No such file or directory 3 | #include <generator/IdGenerator.hpp> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. Sorry for the verbose summary, I was able to shorten the example this much. What do you think the problem is? This question might seem like a duplicate of CMake libraries that depend on each other but as you can see I'm already applying the include_directories(generator/).
I misunderstood what the problem was initially, but now I think this might help. Try adding to the CMakeLists.txt of your client instead of include_directories(generator/) this command target_include_directories(libclient PUBLIC <Path to your generator file>) Maybe you need to experiment a little to get the path correct as you might need to either specify it from the root directory or the current one (where this CMakeLists.txt resides), but it might solve your problem.
72,928,619
72,928,763
confusions about a simple smart pointer implementaion
The following code is abstracted from the book << Hands-On Design Patterns with C++ >> by Fedor G. Pikus published by Packt. Some confusions have been bugging me for weeks. (1) How the char array mem_ is initialized? (2) Is allocate used to allocate memory? How? (3) Why does mem_ == p ? How was the memory delocated? // 02_scoped_ptr.C // Version 01 with deletion policy. #include <cstdlib> #include <cassert> #include <iostream> template <typename T, typename DeletionPolicy> class SmartPtr { public: explicit SmartPtr(T* p = nullptr, const DeletionPolicy& deletion_policy = DeletionPolicy() ) : p_(p), deletion_policy_(deletion_policy) {} SmartPtr(const SmartPtr&) = delete; SmartPtr& operator=(const SmartPtr&) = delete; ~SmartPtr() { deletion_policy_(p_); } void release() { p_ = NULL; } T* operator->() { return p_; } const T* operator->() const { return p_; } T& operator*() { return *p_; } const T& operator*() const { return *p_; } private: T* p_; DeletionPolicy deletion_policy_; }; class SmallHeap { public: SmallHeap() {} SmallHeap(const SmallHeap &) = delete; SmallHeap &operator=(const SmallHeap &) = delete; ~SmallHeap() {} void * allocate(size_t s) { assert(s <= size_); return mem_; // ------------------ is allocate used to allocate memory? how? } void deallocate(void *p) { assert(mem_ == p); // ------------------- why does mem_ == p ? How was the memory delocated? } private: static constexpr size_t size_ = 1024; char mem_[size_]; // ------------------- how mem_ is initialized? }; void * operator new(size_t s, SmallHeap *h) { return h->allocate(s); } template<typename T> struct DeleteSmallHeap { explicit DeleteSmallHeap(SmallHeap &heap) : heap_(heap) {} void operator()(T *p) const { p->~T(); heap_.deallocate(p); } private: SmallHeap &heap_; }; int main() { SmallHeap a_sh_obj; SmartPtr<int, DeleteSmallHeap<int>> sh_sp{new(&a_sh_obj) int(42), DeleteSmallHeap<int>(a_sh_obj)}; std::cout << *sh_sp << std::endl; } ------------------ Update 1 : how is char related to memory? -------------------- Thanks for the helpful explanations, and I need some time to them, especially the custom allocator. But one thing that is really strange to me is that: we are talking about memory stuff, but why do we need a char array here?
How the char array mem_ is initialized? mem_ is not initialized as in filled with values until the use of the custom new operator in new(&a_sh_obj) int(42). This only initializes a small portion of the memory though. Space is allocated on the stack however when you create the local SmallHeap a_sh_obj; variable in main. Is allocate used to allocate memory? How? Yes, it is used. The expression new(&a_sh_obj) int(42) uses void * operator new(size_t s, SmallHeap *h) { return h->allocate(s); } which gets sizeof(int) passed as first parameter and &a_sh_obj as second parameter. Why does mem_ == p? How was the memory delocated? On destruction of sh_sp the DeleteSmallHeap<int> object is used to get rid of the object. The assert is just verification that the memory "freed" is actually the one expected. This doesn't actually deallocate anything, since the memory is still owned by a_sh_obj. It's leaving the main function that in fact releases the memory during when cleaning up a_sh_obj.
72,928,680
72,928,730
Tidying function template to avoid duplication: decltype issues
I have the following class which wraps a member function: #include <cstdio> #include <type_traits> #include <utility> using namespace std; class testclass { public: double get() { return d_; } void set(double d) { d_ = d; } double d_ = 0.0; }; template<typename Retriever, Retriever retrieverFunc, typename Updater, Updater updaterFunc, typename OwningClass> struct Wrapper { Wrapper(Retriever retriever, Updater updater, OwningClass* owner) : retriever_(retriever), updater_(updater), containingClass_(owner) {} using GetterReturnType = std::invoke_result_t<decltype(retrieverFunc), OwningClass>; GetterReturnType Get() { return (containingClass_->*retriever_)(); } template<typename...Args> using SetterReturnType = std::invoke_result_t<decltype(updaterFunc), OwningClass, Args...>; template<typename...Args> SetterReturnType<Args...> Set(Args&&... args) { return (containingClass_->*updater_)((forward<Args>(args))...); } Retriever retriever_; Updater updater_; OwningClass* containingClass_; }; int main() { testclass tc; Wrapper<decltype(&testclass::get), &testclass::get, decltype(&testclass::set), &testclass::set, testclass> pp(&testclass::get, &testclass::set, &tc); pp.Get(); pp.Set(1.0); } Clearly, the syntax for declaring a wrapper is a bit tedious, so I wanted to clean it up a bit. I tried this: template<typename Retriever, Wrapper Updater, typename OwningClass> using WrapperSimplified = Wrapper<decltype(Retriever), Retriever, decltype(Updater), Updater, OwningClass>; with the intention of being able to say this: WrapperSimplified<&testclass::get, &testclass::set, testclass> pp(&testclass::get, &testclass::set, &tc); But it does not compile, VS2022 complains 'Retriever': is not a valid type for non-type template parameter 'retrieverFunc' How can I achieve this please?
Retriever is supposed to be the value, not the type, of the non-type template argument. So it should be declared as non-type template parameter. Since you want the type to be deduced, the type of the non-type template parameter should be auto. Equivalently for Updater: template<auto Retriever, auto Updater, typename OwningClass> using WrapperSimplified = Wrapper<decltype(Retriever), Retriever, decltype(Updater), Updater, OwningClass>; But from what I can tell the class doesn't actually use the non-type template parameters retrieverFunc and updaterFunc. You can remove them (replacing the decltype(retrieverFunc) with Retriever and decltype(updaterFunc) with Updater). Then the class object can be created simply using CTAD: Wrapper pp(&testclass::get, &testclass::set, &tc);
72,929,159
72,929,258
How to use concepts to pass an argument to a class method?
I have an optional_monadic class that I inherit from the std::optional class template <class T> class monadic_optional : public std::optional<T> { public: using std::optional<T>::optional; monadic_optional(T value) : std::optional<T>(value) {} } In this class I describe the method template <class Return> nonstd::monadic_optional<Return> and_then(std::function<nonstd::monadic_optional<Return>(T)> func) { if (this->has_value()) return func(this->value()); else return std::nullopt; } I want to use concepts to pass a template to a method that checks to see if it's a function. How can I implement this using concepts? template <class T> concept convertible_to_func = std::convertible_to <T, std::function<nonstd::monadic_optional<Return>(T)>> requires { }; nonstd::monadic_optional<T> and_then(T func) { if (this->has_value()) return func(this->value()); else return std::nullopt; } It should look something like this, but it doesn't compile.
This is pretty trivial with invokable. And you don't have to require it to become a std::function: auto and_then(std::invocable<T> auto func) -> monadic_optional<std::invoke_result_t<decltype(func), T>> { if(this->has_value()) return std::invoke(func, *this); return std::nullopt; }
72,929,177
72,929,506
Correct way to check bool flag in thread
How can I check bool variable in class considering thread safe? For example in my code: // test.h class Test { void threadFunc_run(); void change(bool _set) { m_flag = _set; } ... bool m_flag; }; // test.cpp void Test::threadFunc_run() { // called "Playing" while(m_flag == true) { for(int i = 0; i < 99999999 && m_flag; i++) { // do something .. 1 } for(int i = 0; i < 111111111 && m_flag; i++) { // do something .. 2 } } } I wan to stop "Playing" as soon as change(..) function is executed in the external code. It also wants to be valid in process of operating the for statement. According to the search, there are variables for recognizing immediate changes, such as atomic or volatile. If not immediately, is there a better way to use a normal bool?
Actually synchronizing threads safely requires more then a bool. You will need a state, a mutex and a condition variable like this. The approach also allows for quick reaction to stop from within the loop. #include <chrono> #include <condition_variable> #include <iostream> #include <future> #include <mutex> class Test { private: // having just a bool to check the state of your thread is NOT enough. // your thread will have some intermediate states as well enum play_state_t { idle, // initial state, not started yet (not scheduled by OS threadscheduler yet) playing, // running and doing work stopping, // request for stop is issued stopped // thread has stopped (could also be checked by std::future synchronization). }; public: void play() { // start the play loop, the lambda is not guaranteed to have started // after the call returns (depends on threadscheduling of the underlying OS) // I use std::async since that has far superior synchronization with the calling thead // the returned future can be used to pass both values & exceptions back to it. m_play_future = std::async(std::launch::async, [this] { // give a signal the asynchronous function has really started set_state(play_state_t::playing); std::cout << "play started\n"; // as long as state is playing keep doing the work while (get_state() == play_state_t::playing) { // loop to show we can break fast out of it when stop is called for (std::size_t i = 0; (i < 100l) && (get_state() == play_state_t::playing); ++i) { std::cout << "."; std::this_thread::sleep_for(std::chrono::milliseconds(200)); } } set_state(play_state_t::stopped); std::cout << "play stopped.\n"; }); // avoid race conditions really wait for // trhead handling async to have started playing wait_for_state(play_state_t::playing); } void stop() { std::unique_lock<std::mutex> lock{ m_mtx }; // only wait on condition variable in lock if (m_state == play_state_t::playing) { std::cout << "\nrequest stop.\n"; m_state = play_state_t::stopping; m_cv.wait(lock, [&] { return m_state == play_state_t::stopped; }); } }; ~Test() { stop(); } private: void set_state(const play_state_t state) { std::unique_lock<std::mutex> lock{ m_mtx }; // only wait on condition variable in lock m_state = state; m_cv.notify_all(); // let other threads that are wating on condition variable wakeup to check new state } play_state_t get_state() const { std::unique_lock<std::mutex> lock{ m_mtx }; // only wait on condition variable in lock return m_state; } void wait_for_state(const play_state_t state) { std::unique_lock<std::mutex> lock{ m_mtx }; m_cv.wait(lock, [&] { return m_state == state; }); } // for more info on condition variables // see : https://www.modernescpp.com/index.php/c-core-guidelines-be-aware-of-the-traps-of-condition-variables mutable std::mutex m_mtx; std::condition_variable m_cv; // a condition variable is not really a variable more a signal to threads to wakeup play_state_t m_state{ play_state_t::idle }; std::future<void> m_play_future; }; int main() { Test test; test.play(); std::this_thread::sleep_for(std::chrono::seconds(1)); test.stop(); return 0; }
72,929,287
72,929,458
What part of overload resolution (or more generally of the function call processing) does the value category of the argument play a role in?
C++ Templates - The Complete Guide, in §C.1, reads Overload resolution is performed to find the best candidate. If there is one, it is selected; otherwise, the call is ambiguous. Then, in §C.2, ranks the possible matches (of a given argument with the corresponding parameter of a viable candidate) like this (my emphasis): Perfect match. The parametere has the type of the expression, or it has a type that is a reference to the type of the expression (possible with added const and/or volatile qualifiers). Match with minor adjustments. This includes, for example, the decay of an array variable to a pointer to its first element or the addition of const to match an argument of type int** to a parameter of type int const* const*. Match with promotion. … Match with standard conversions only. … Match with user-defined conversion. … Match with ellipsis (...). … Now, since top level const of by-value parameters are not part of the signature of a function, I think that the part in parenthesis in the first point refers to the case that the parameter is a reference to the type of the expression. If my interpretation is correct, that means that a T const& parameter is a perfect match for an argument of type T. After all, in §C.2.2, I see that confirmed: For an argument of type X, there are four common parameter types that constitute a perfect match: X, X&, X const&, and X&& (X const&& is also an exact match, …) And then the book goes on with some example that show how the category value of the argument determines what overload is selected. But if all of X, X&, X const&, X&&, and X const&& are perfect matches, then when is one of them preferred based on the value category of the argument? Isn't that part of overload resolution? If so, why the value category is not mentioned at all in the points above?
why the value category is not mentioned at all in the points above? It is mentioned in the book as can be seen as quoted below. In particular, if you continue reading further then you'll see that the section C.2.2 titled Refining the Perfect Match does mention the part about distinguishing between different perfect matches: With the addition of rvalue references in C++11, another common case of two perfect matches needing to be distinguished is illustrated by the following example: struct Value { ... }; void pass(Value const&); // #1 void pass(Value&&);// #2 void g(X&& x) { pass(x); // calls #1 , because x is an lvalue pass(X()); // calls #2 , because X() is an rvalue (in fact, prvalue) pass(std::move(x)); // calls #2 , because std::move(x) is an rvalue (in fact, xvalue) } This time, the version taking an rvalue reference is considered a better match for RVALUES, but it cannot match lvalues. Note the bold part in the above quoted example. Similarly, it even has the following example: void report(int&); // #1 void report(int const&); // #2 int main() { for (int k = 0; k<10; ++k) { report(k); // calls #1 } report(42); // calls #2 } Here, the version without the extra const is preferred for LVALUES, whereas only the version with const can match RVALUES.
72,929,601
72,930,824
Templated Proxy in wrapper class issues
I asked previously about the following class, which is a wrapper around a member function. I now want to add "plugin" functionality to it via a proxy class. My wrapper class's operator* returns a proxy object on which I can then assign and retrieve as shown below: #include <cstdio> #include <type_traits> #include <utility> using namespace std; class testclass { public: double get() { return d_; } void set(double d) { d_ = d; } double d_ = 0.0; }; template <typename PropertyType> struct DEFAULT_WRAPPER_PROXY { DEFAULT_WRAPPER_PROXY(PropertyType* p) : property_(p) {} operator typename PropertyType::GetterReturnType() { return property_->Get(); } DEFAULT_WRAPPER_PROXY& operator=(typename PropertyType::GetterReturnType val) { property_->Set(val); return *this; } PropertyType* property_; }; template <typename PropertyType> struct LOGGING_WRAPPER_PROXY { LOGGING_WRAPPER_PROXY(PropertyType* p) : property_(p) {} operator typename PropertyType::GetterReturnType() { // Log some interesting stuff return property_->Get(); } LOGGING_WRAPPER_PROXY& operator=(typename PropertyType::GetterReturnType val) { // Log some interesting stuff property_->Set(val); return *this; } PropertyType* property_; }; template<typename Retriever, typename Updater, typename OwningClass, template<typename PropertyType> class WRAPPER_PROXY = DEFAULT_WRAPPER_PROXY> struct Wrapper { Wrapper(Retriever retriever, Updater updater, OwningClass* owner) : retriever_(retriever), updater_(updater), containingClass_(owner) {} using GetterReturnType = std::invoke_result_t<Retriever, OwningClass>; GetterReturnType Get() { return (containingClass_->*retriever_)(); } template<typename...Args> using SetterReturnType = std::invoke_result_t<Updater, OwningClass, Args...>; template<typename...Args> SetterReturnType<Args...> Set(Args&&... args) { return (containingClass_->*updater_)((forward<Args>(args))...); } WRAPPER_PROXY<Wrapper<Retriever, Updater, OwningClass>> operator*() { return WRAPPER_PROXY(this); } Retriever retriever_; Updater updater_; OwningClass* containingClass_; }; int main() { testclass tc; { // Can use template arg deduction in construction Wrapper pp(&testclass::get, &testclass::set, &tc); // use default proxy double y = *pp; *pp = 102; } { // Try and use the logging proxy // Does not work: LWT is not a template //using LWT = LOGGING_WRAPPER_PROXY<Wrapper<decltype(testclass::get), decltype(testclass::set), testclass>>; //Wrapper<decltype(testclass::get), decltype(testclass::set), testclass, LWT> pp2(&testclass::get, &testclass::set, &tc); // Does not work;see errors below Wrapper<decltype(testclass::get), decltype(testclass::set), testclass, LOGGING_WRAPPER_PROXY> pp2(&testclass::get, &testclass::set, &tc); } } The errors I get are as follows: 'std::invoke_result_t' : Failed to specialize alias template 'type': is not a member of any direct or indirect base class of 'std::_Invoke_traits_nonzero<void,Retriever,OwningClass>' Can anyone suggest a nice way I can achieve this plugin functionality please?
You were missing a & from the decltype expressions when trying to instantiate the Wrapper template: Wrapper< decltype(&testclass::get), ^ decltype(&testclass::set), ^ testclass, LOGGING_WRAPPER_PROXY > pp2(&testclass::get, &testclass::set, &tc); Generally, when working with the MSVC compiler (Visual Studio C++), I would recommend utilizing godbolt with hard-to-understand compiler error messages. Microsoft's compiler has a tendency to give the worst error messages among the three well-known compilers (clang, gcc, and msvc), especially with templates. For example, your code in godbolt produces rather clear error messages with the three compilers. Unfortunately, I was not able to reproduce the exact error message you were having, although it seemed that the missing & were the only problem. P.S. Regarding your duplication problem again (having to decltype each of the constructor params), I would define a factory function to help with this: template< template<typename PropertyType> class WRAPPER_PROXY = DEFAULT_WRAPPER_PROXY, typename Retriever, typename Updater, typename OwningClass> auto MakeWrapper(Retriever&& retriever, Updater&& updater, OwningClass* const owner) { return Wrapper<Retriever, Updater, OwningClass, WRAPPER_PROXY>( std::forward<Retriever>(retriever), std::forward<Updater>(updater), owner ); } Function templates allow us to partially deduce the template arguments, which is not possible with class templates. This makes it easy to only modify the WRAPPER_PROXY template argument, as everything else would be deduced from the Wrapper's constructor call anyways (or in this case the MakeWrapper's function arguments): // Error-prone, lengthy and repetitive Wrapper< decltype(&testclass::get), decltype(&testclass::set), testclass, LOGGING_WRAPPER_PROXY > pp2(&testclass::get, &testclass::set, &tc); // Cleaner (using CTAD here, could also use auto) Wrapper pp3 = MakeWrapper<LOGGING_WRAPPER_PROXY>( &testclass::get, &testclass::set, &tc ); // The types are the same static_assert(std::is_same_v<decltype(pp2), decltype(pp3)>);
72,929,739
72,930,096
Why does the compiler create a variable that's only used once?
Consider the following two examples, both compiled with g++ (GCC) 12.1.0 targetting x86_64-pc-linux-gnu: g++ -O3 -std=gnu++20 main.cpp. Example 1: #include <iostream> class Foo { public: Foo(){ std::cout << "Foo constructor" << std::endl;} Foo(Foo&& f) { std::cout << "Foo move constructor" << std::endl;} Foo(const Foo& f) {std::cout << "Foo copy constructor" << std::endl;} ~Foo() { std::cout << "Foo destructor" << std::endl;} }; class Baz { private: Foo foo; public: Baz(Foo foo) : foo(std::move(foo)) {} ~Baz() { std::cout << "Baz destructor" << std::endl;} }; Foo bar() { return Foo(); } int main() { Baz baz(bar()); return 0; } Output: Foo constructor Foo move constructor Foo destructor Baz destructor Foo destructor Example 2: #include <iostream> class Foo { public: Foo(){ std::cout << "Foo constructor" << std::endl;} Foo(Foo&& f) { std::cout << "Foo move constructor" << std::endl;} Foo(const Foo& f) {std::cout << "Foo copy constructor" << std::endl;} ~Foo() { std::cout << "Foo destructor" << std::endl;} }; class Baz { private: Foo foo; public: Baz(Foo foo) : foo(std::move(foo)) {} ~Baz() { std::cout << "Baz destructor" << std::endl;} }; Foo bar() { return Foo(); } int main() { // DIFFERENCE IS RIGHT HERE Foo f = bar(); Baz baz(f); return 0; } Output: Foo constructor Foo copy constructor Foo move constructor Foo destructor Baz destructor Foo destructor Foo destructor So the difference here is that there is an additional instance of Foo, which needs to be handled. I find this difference quite shocking, as my (apparently untrained) eyes would not even consider these pieces of code effectively different. Moreover, a collegue might ask me to turn example 1 into example 2 for readability and suddenly I will be incurring a performance penalty! So why are example 1 and 2 so different according to the compiler/C++ spec that the resulting code suddenly needs to copy? Why can the compiler not generate the same code for both cases?
In Foo f = bar(); Baz baz(f); return 0 It is indeed obvious that f will never be used again and the compiler probably even works this out. However the compiler isn't allowed to move f into baz, all optimisations done by the compiler must result in your program having the same behaviour (if the program is well defined to start with). Especially in your case where the move and copy constructors print different things, making this optimisation would change the behaviour of your program. In a more realistic program the compiler may be able to deduce that the code would have the same behaviour with a move or a copy and change a copy into a move but it's always best to give the compiler as much help as possible and not rely on it making optimisations. If you know that you don't need f any more then you can tell the compiler this by converting it to an rvalue reference using std::move, then it will use the move constructor (if available): Foo f = bar(); Baz baz(std::move(f)); return 0
72,930,427
72,939,308
How to load data into a vector from a text file that has been created inside the same program. in C++
I want to load data from a Text file that has been created in the same program into a vector of strings. But no line of text is getting pushed into the vector here. Here First I am reading data from some input file and then doing some operations (Removing extra spaces) on it then I save this file as "intermediate.txt". This intermediate.txt is being created and all the operations that I want to do happen successfully. Finally, I want to read this file into a vector<string> code but it doesn't work. I can't store anything in the vector<string> code. Its size is Zero. #include <bits/stdc++.h> using namespace std; int main() { string inputFileName; cout << "Enter the Input File Name: "; cin >> inputFileName; ifstream f1(inputFileName); ofstream f0("intermediate.txt"); string text_line; while (getline(f1, text_line)) { string word; istringstream text_stream(text_line); while (text_stream >> word) { f0 << word << " "; } f0 << "\n"; } f0.close() ifstream file("intermediate.txt"); vector<string> code; string line; while (getline(file, line, '\n')) { code.push_back(line); } for (auto it : code) { cout << it << "\n"; } }
Here's a mini-code review: #include <bits/stdc++.h> // Don't do this; doesn't even compile for me using namespace std; // Don't do this either int main() { string inputFileName; cout << "Enter the Input File Name: "; cin >> inputFileName; ifstream f1(inputFileName); // Bad name ofstream f0("intermediate.txt"); // Bad name // You never check that you successfully opened *any* files. string text_line; /* * You don't describe why this is necessary, can a line not be read and * written as-is? Is it already a line of space-separated variables? * * In any case, this is where you already have the words; so store them in * the vector here as well. */ while (getline(f1, text_line)) { string word; istringstream text_stream(text_line); while (text_stream >> word) { f0 << word << " "; } f0 << "\n"; } f0.close() // Forgot your semi-colon // Left f1 open, that's bad practice ifstream file("intermediate.txt"); vector<string> code; string line; /* * I would hope you felt that reading from a file, writing to a new file, * closing both files, opening the new file, and reading from the new file * into the vector was wasteful. */ while (getline(file, line, '\n')) { code.push_back(line); } for (auto it : code) { cout << it << "\n"; } } The most immediate issue with your original question was that you tried to open the same file in two different streams. The second time, the file failed to open, but because you never check if you actually opened the file, you assumed everything worked fine, but it didn't, which brought you here. However, there is a better way. #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> int main() { std::string inputFileName; std::cout << "Enter the Input File Name: "; std::cin >> inputFileName; // Always check that you successuflly opened the file. std::ifstream fin(inputFileName); if (!fin) { std::cerr << "Error opening: " << inputFileName << ". Exiting...\n"; return 1; } std::ofstream fout("intermediate.txt"); if (!fout) { std::cerr << "Error opening: intermediate.txt. Exiting...\n"; return 2; } std::vector<std::string> code; std::string text_line; while (std::getline(fin, text_line)) // You've read the line { std::string word; std::istringstream text_stream(text_line); while (text_stream >> word) { fout << word << " "; } fout << "\n"; code.push_back(text_line); // Just store it while you have it } fin.close(); // Best practice is to close a file as soon as you're done fout.close(); // with it. Don't hog resources. for (const auto& it : code) // Avoid making copies { std::cout << it << "\n"; } } The while loop, where you read the lines that you want to store in the vector, now writes to your file and stores the lines into the vector. We also now check whether we successfully opened files, and we close the file streams as soon as we're done with the file so as to not keep it locked for no good reason. A good next step for improving this program a bit more would be to avoid asking the user for a file name. Instead, take it as an argument to main(). That way, someone only has to type ./a.out input.txt on the command line and the program will do the job automatically.
72,930,594
72,930,640
Does constructor in cpp doesnot return anything?
It is said that constructor doesnot return anything.But if constructor doesnot return anything, then how do this code segment works: *this=classname{args};. I hope someone could shed me some light on whats actually going under the hood. A complete code: #include <iostream> using namespace std; class hell { private: int a{}, b{}; public: hell(int _a = 7, int _b = 8) : a{ _a }, b{ _b } {} void print() { cout << a << endl << b << endl; } void change() { *this = hell(4, 5); } }; int main() { hell h; h.print(); h.change(); h.print(); return 0; }
The statement *this = hell(4, 6); does two things: First it create a temporary and unnamed object of the class hell, initialized using the values you use to pass to a suitable constructor. Then that temporary and unnamed object is copy-assigned to the object pointed to by this. It's somewhat similar to this: { hell temporary_object(4, 5); // Create a temporary object *this = temporary_object; // Copy the temporary object to *this }
72,931,024
72,931,130
Why += works when inserting string in vector<string> and then pushing in 2d string vector, but doesn't work when inserting char by char?
I was creating a vector of strings of size 4x4 with all characters as dots i.e. I was creating: .... .... .... .... And then I had to push this vector of strings in a vector of vector of strings like in the code below: int main() { vector<vector<string>> ans; int n=4; vector<string> matrix(n); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { matrix[i][j]='.'; //inserting '.' as characters } } ans.push_back(matrix); for(int i=0;i<n;i++) //printing the just inserted matrix { for(int j=0;j<n;j++) { cout<<ans[0][i][j]<<" "; } cout<<endl; } } This was when I am printing it back, it gives garbage/nothing. But, I change the insertion matrix[i][j]='.'; to matrix[i]+='.';, it is working fine. int main() { vector<vector<string>> ans; int n=4; vector<string> matrix(n); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { matrix[i]+='.'; //inserting '.' by += } } ans.push_back(matrix); for(int i=0;i<n;i++) //printing the just inserted matrix { for(int j=0;j<n;j++) { cout<<ans[0][i][j]<<" "; //works fine } cout<<endl; } } What is the cause of this behaviour?
This code: int n=4; vector<string> matrix(n); Will create a vector filled with n default-constructed strings; i.e. a vector with 4 empty strings. So, in the following loop, you're accessing each string with an out-of-bound index (which is undefined behavior): for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = '.'; // ^ Out of bounds: matrix[i].size() == 0 } } In your second case: for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i] += '.'; // ^ You're appending '.' to the string. // That's fine } } you're appending to the strings, which is fine. If you want to have a vector of n strings, each containing n times character '.', you may just skip the loop and do: int n = 4; std::vector<std::string> matrix(n, std::string(n, '.')); As a side note, you're not showing it but most probably you are: using namespace std; You shouldn't do it.
72,931,173
72,932,107
Why std::shared_ptr control block need to hold a pointer to managed object with its correct type
I am looking at the shared_ptr implementation in the following post. One question that is not entirely clear to me is, why in addition to the pointer stored with T* type in shared_ptr class itself, author also needs to store the second copy of the managed object's pointer with its concrete type in the control block (i.e. U* p; in auximpl). I understand why we need this for custom deleter, but not for actual pointer. It looks like this complies with the requirements of the standard, when I read control block description in cppreference page. Author made the following comment about this "this is needed to properly manage all the cases of T being a base for whatever U having multiple T in the derivation hierarchy" but I still can't come up with an example of when this will really be required. Can someone please demonstrate it with an example? Thank you, -Grigor
One case is when using shared_ptr's alias capability. Create a shared_ptr using an object's member but the control block is the same and thus the reference count. class holder : public std::enable_shared_from_this<holder> { int member; public: std::shared_ptr<int> get_member() { return std::shared_ptr<int>(shared_from_this(), &member); } }; std::shared_ptr<int> foo() { auto ptr = std::make_shared<holder>(); return ptr->get_member(); } the object created in the make_shared call won't be freed until the object returned from foo's reference count goes to 0.
72,931,394
72,931,439
AzerothCore Unable to connect to server, probably WorldSocket Malformed request sent by client
I am using AzerothCore locally and when I try to log in - I am stuck at "Authenticating". Previously on login attempt - a error occured, WorldSocket Malformed request sent by client, But after opening the ports for both inbound and outbound connections - it dissapeared. Therefore, no error message, just stuck at "Authenticating". Client version: 3.3.5 (13240) (Release) Jan 24 2010 The realmList is changed to 127.0.0.1:8085 But I am not sure if it is correct, since once I had issues accessing localhost on another application and had to use the router's IP (192.168.0.3)
WorldSocket Malformed request sent by client WorldSocket::ReadHeaderHandler(): client 111.222.11.22 sent malformed packet (size: 1234, cmd: 3333333) means some machine anywhere on the planet sent a random portscan to your IP. Not related to your actual problem. You should try and set the realmlist to the LAN IP of the machine running the server and do the same in the realmlist table. Also make sure all ports are properly forwarded to your server. (8085 und 3724 by default). If both, client and server are running on the same machine, you can use 127.0.0.1. Not otherwise.
72,931,994
72,932,771
C++ Template Argument Deduction with Additional Specified Template Arguments
I have encountered an issue with template argument deduction. The following complies without issues, the compiler can deduce the template argument: template<size_t a_size> class DummyBase { public: DummyBase() = delete; constexpr DummyBase(const char (& i)[a_size]) { } }; constexpr const auto dummy = DummyBase{"f"}; However, the following does not compile and the compile gives me an error that I have not provided enough arguments: template<int useless, size_t a_size> class DummyBase { public: DummyBase() = delete; constexpr DummyBase(const char (& i)[a_size]) { } }; constexpr const auto dummy = DummyBase<1>{"f"}; The only change is that I have provided an additional (useless) template argument. The compile cannot deduce it and for this reason I am providing an explicit value. If I understood the theory correctly, the compiler should then try to deduce additional template arguments which were not explicitly provided. However, it either doesn't try to deduce the argument or it is suddenly unable to deduce it despite no change in the information provided for it to be deduced. (Btw, I am pretty sure taht this is the correct order for the template parameters but just for safety I tried it with reversed order and it didn't work either) Could someone tell me what is going on and if/how I can fix it?
Unfortunately, "Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place." - https://en.cppreference.com/w/cpp/language/class_template_argument_deduction You could use a wrapper function to do what you want, but it won't work with the constructor itself.
72,932,091
72,932,139
Is std::equal guaranteed to short circuit?
I would like to compare a nul-terminated string against a string literal. I hope to use std::equal and am curious if this code is well-defined according to the C++ standard: #include <algorithm> bool is_foo(const char *str) { const char *lit = "foo"; return std::equal(lit, lit + 4, str); } If std::equal is guaranteed to stop at the first mismatch, then this code seems defined to me even if str has length < 3. If there is no such guarantee then I think this may dereference past the end of str resulting in UB. What if anything does the C++ spec say about this? Thanks for any help!
My reading of the C++ standard indicates that this is pedantically undefined behavior based on the following remark: Remarks: If last2 was not given in the argument list, it denotes first2 + (last1 - first1) below. This is referring to overloads of std::equal that do not supply the second sequence's ending iterator. In this case this would not be a valid pointer, hence this is pedantically undefined behavior, given the following part of the specification: E be: pred(*i, *(first2 + (i - first1))) for the overloads with no parameter proj1; ... Returns: If last1 - first1 != last2 - first2, return false. Otherwise return true if E holds for every iterator i in the range [first1, last1) Otherwise, returns false. I see nothing here that guarantees short circuit evaluation. The complexity does not seem to imply guaranteed short-circuit evaluation, either: Complexity: [ ... ] ... at most min(last1 - first1, last2 - first2) applications of ... The "at most" part is not qualified in any way. Strictly interpreted this allows, but not requires, short-circuit evaluation.
72,932,948
72,932,995
C-plus-plus coding errors
I am learning C++ and I have to complete an Object Oriented Program. I am struggling to understand why I am getting an error. Please give as much as detail as possible when explaining because it would be helpful in the journey of teaching myself C++. Below is my initial code and the error: #include<iostream> using namespace std; class RectangularCube { //Defined the class Rectangular Cube private: //Access specifier - Declare two sides as private data field string color; //Private data field color that is string type double width; double height; public: double length; //Declare one side as a public data field //Contructor with parameteres RectangularCube(string newColor, double newWidth, double newHeight, double newLength) { color = newColor; width = newWidth; height = newHeight; length = newLength; } RectangularCube() { //No-arguments contructor with all three sides and color set to different values color = black; width = 5.145; height = 4.894; length = 10.123; } // Return Volume of this Rectangular Cube double getVolume() { return length * width * height; }; //Return Surface Area of this Rectangular Cube double getSurfaceArea() { return 2(length * width) + 2(length * height) + 2(width * height) }; //get and set functions for the two private sides and color data field double getColor(); double getWidth(); double getHeight(); void setColor(); void setWidth(); void setHeight(); }; int main() { RectangularCube rectangularcube1(); cout << "The Volume of the Rectangular Cube is: " << rectangularcube1.getVolume() << endl; return 0; } The Error color = black; ^ RectangularCube.cpp:35:21: error: called object type 'int' is not a function or function pointer return 2(length * width) + 2(length * height) + 2(width * height) ~^ RectangularCube.cpp:35:41: error: called object type 'int' is not a function or function pointer return 2(length * width) + 2(length * height) + 2(width * height) ~^ RectangularCube.cpp:35:62: error: called object type 'int' is not a function or function pointer return 2(length * width) + 2(length * height) + 2(width * height) ~^ 4 errors generated.
By 2(length * width) I assume you really mean 2*(length * width) and this color = black; should probably be color = "black";
72,933,156
72,933,186
Is there any risk if I call clear when loop a vector?
I want to call clear when loop to visit the vector. I think this will be dangerous, but in my experiment code below, it seems ok to run, it just stop the loop when i called clear. #include <bits/stdc++.h> using namespace std; int main() { std::vector<int> a = {1,2,3,4,5}; for (size_t i = 0; i < a.size(); ++i) { a.clear(); // just run once, then loop exited cout << "i = " << i << endl; } } Is there anything I don't know about the risk? could you help on this?
There is a very, very major temptation that when you have a loop that looks like this: for (size_t i = 0; i < a.size(); ++i) { then you will be under the impression that looking at a[i] and/or modifying it, freely, inside the loop, whenever you have an urge to do so, is perfectly acceptable. And it is. Unless you already did a a.clear(); Alone, by itself, there's nothing wrong with just the code you showed. It's defined behavior. But as soon as a is clear()ed, doing something with a[i] becomes a no-no, inside the loop. But resistance is futile. At some point it's a near certainty that you'll forget that you clear()ed the vector, decide to take a peek at a[i], and have to deal with demons flying out of your nose. If your goal is to stop the loop, a simple break will do. If there is a separate reason to clear() the vector, do so, but immediately break from the loop as well, to avoid giving in to the temptations of creating nasal demons.
72,933,324
72,946,116
how could I create a file in this path : "~/testUsr" by using boost
I want to create a file in the path "~/testUsr" while I don't know which "testUsr" exactly is. if I just use path "~/testUsr", it will generate a directory "~" in current path instead of "home/testUsr"; // create directories std::string directoryPath = "~/testUsr"; if(!boost::filesystem::exists(directoryPath)){ boost::filesystem::create_directories(boost::filesystem::path(directoryPath)); } std::string filePath = directoryPath + "/" + filename +".ini"; if(!boost::filesystem::exists(filePath)){ boost::filesystem::ofstream File(filePath) ; config.WriteConfigFile(filePath); File.close(); }
Using a helper function from Getting absolute path in boost Live On Coliru #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <iostream> using boost::filesystem::path; struct { void WriteConfigFile(std::ostream& os) const { os << "[section]\nkey=value\n"; } } static config; path expand(path p) { char const* const home = getenv("HOME"); if (home == nullptr) return p; // TODO handle as error? auto s = p.generic_string<std::string>(); if (!s.empty() && s.find("~/") == 0u) { return home + s.substr(1); } return p; } int main() { path filename = "abc"; // create directories path directoryPath = expand("~/testUsr"); if (!exists(directoryPath)) { create_directories(directoryPath); } path filePath = directoryPath / filename.replace_extension(".ini"); if (!exists(filePath)) { boost::filesystem::ofstream os(filePath); config.WriteConfigFile(os); } // os.close(); implied by destructor } Note the use of path instead of string to make the code more reliable.
72,933,479
72,934,922
The Procedure entry point pointstd::from_chars could not be located in the dynamic link library libpqxx-7-7.dll
I am compiling a C++ program on windows under MSYS2 MinGW and I am using the libpqxx library, the program compiles fine but when I go to run it from file explorer I get the following error The Procedure entry pointstd::from_chars(char const*, char const*, double&, std::chars_format) could not be located in the dynamic link library libpqxx-7-7.dll this program runs without any errors if I run it from the MSYS2 MinGW terminal (By executing ./main.exe) but I would like the program to work without having to install MSYS2. I have the libpqxx library installed. I am using the following commands to compile the program g++ main.cpp -o main libpq.lib -lpqxx pkg-config --cflags --libs gtk+-3.0 (this program was developed on linux and I am using the gtk library) (edit) Here is the folder structure that I have, the required dll is contained in the folder already, if I remove the dll then I get a file not found error any help would be greatly appreciated
I have fixed the problem, I just needed to add a few more dll files to the directory in which my program resides and now it starts! the dll files required are: libintl-8.dll libstdc++-6.dll these dll files can be found in the bin folder under the mingw64 folder Thanks to @HolyBlackCat for pointing me in the right direction (telling me that I need more dlls)
72,933,995
72,934,095
How to not allow conversion from temporary shared_ptr to weak_ptr for derived types
I have asked this question for concrete types. The provided solution is sufficient for those, but when it comes to inheritance, it fails. Would there be a solution to that as well? Lets have a inheritance of classes Foo and IFoo such that class Foo: public IFoo and a function void use_weak_ptr(std::weak_ptr<IFoo>). Is it possible to ensure that this compiles: auto shared = std::make_shared<Foo>(); use_weak_ptr(shared); And this does not: use_weak_ptr(std::make_shared<Foo>()); Godbolt
One of the possible solutions - overload use_weak_ptr for all std::shared_ptr. template <typename T> void use_weak_ptr(std::shared_ptr<T>&&) = delete; https://godbolt.org/z/Tj1a134bd The linked answer is not a good answer. const std::shared_ptr<IFoo>&& - const is redundant.
72,934,107
72,959,805
How to use Additional Module Dependencies in C++20
I created a TestModule.ixx in one folder and I want to use import TestModule in my cpp project(in different folder). I tried TestModule=E:\XXX\TestModule.ixx.ifc; in properties-> Additional Module Dependencies, but got error lnk2019. Q: How to import module in other files? Is there a way like adding header file directory. Module export module TestModule; #define ANSWER 42 namespace Example_NS { int f_internal() { return ANSWER; } export int f() { return f_internal(); } } Main: import TestModule; import std.core; using namespace std; int main() { cout << "The result of f() is " << Example_NS::f() << endl; // 42 system("pause"); } Thanks in advance.
In the build parameters we need to add it as an option. When it comes to visual studio below is the way worked. Similarly there will a build option for other compilers. In Visual studio (for MSVC) - Project properties--"C/C++"--Command Line--Additional options https://learn.microsoft.com/en-us/cpp/build/reference/module-reference?view=msvc-170 /reference filename /reference "C:\\Users\\Module.ixx.ifc"
72,934,138
72,934,173
how can I deal with this error: `cannot convert argument 1 from 'Node *' to 'Move'`
I am new to C++ and I am trying to build a Monte Carlo Tree Search from scratch. This structure allows me to traverse from root node to leaf node and also from leaf node to root node. So the node that has a NULL parent is the root. Each node can have multiple children. This structure has to be capable of creating and deleting nodes dynamically. For example, I may want to replace the tree root with one of its children. so I have to dynamically delete the old root and its subtree that does not belong to the new root. I am trying to apply what I learned about dynamic memory allocation in C++ to this project. This is the code that I implemented so far: #include <math.h> #include <vector> #include <unordered_map> struct Move { int x; int y; }; class Node { private: Move move; int Q = 0; int N = 0; int N_RAVE = 0; int Q_RAVE = 0; int OUTCOME = GameMeta().GAME_ON; Node* parent; std::vector <Node> children; public: Node(Move move, Node* parent = NULL); double value(const float EXPLORE_CONST); void add_children(vector<Node>); void add_win() { N++; Q++; } void add_loss() { N++; } void add_rave_win() { N_RAVE++; Q_RAVE++; } void add_rave_loss() { N_RAVE++; Q_RAVE--; } Move get_move() { return move; } }; Node::Node(Move move, Node* parent_inp){ // Constructor this->move = move; this->parent = parent_inp; this->Q = 0; this->N = 0; this->N_RAVE = 0; this->Q_RAVE = 0; } And this is the main function that throws error: int main() { Move move = { 2, 4 }; Node *root = new Node(move, nullptr); vector<Node> children; // Moves from (0, 2) to (20, 2); for (int i = 0; i <= 20; i++) { Move move1 = { i,2 }; //Node item = Node(move1, &root); Node *item = new Node(move1, root); item->add_win(); children.emplace_back(item); } } This is the error that it throws: `Error C2664 'Node::Node(Move,Node *)': cannot convert argument 1 from 'Node *' to 'Move' ConsoleApplication1 C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\xmemory 680` How can I deal with this problem? Thanks
The problem is that children is a vector with elements of type Node(and not Node*) and you're trying to add item which is of type Node* into. To solve(get rid of) the error you can either make children to be a vector of Node* or you can dereference the pointer item before adding it into children.
72,934,202
72,936,546
sh: 1: Syntax error: Unterminated quoted string\n
I am making an online judge in django frame work I am trying to run a c++ program inside a docker container through subprocess. This is the line where I am getting error x=subprocess.run('docker exec oj-cpp sh -c \'echo "{}" | ./a.out \''.format(problem_testcase.input),capture_output=True,shell=True) here oj-cpp is my docker container name and problem_testcase.input is input for the c++ file C++ code: #include <bits/stdc++.h> using namespace std; int main() { int t; while (t--) { int a, b; cin >> a >> b; cout << a + b << endl; } return 0; } problem_testcase.input: 2 4 5 3 5 error: CompletedProcess(args='docker exec oj-cpp sh -c \'echo "2\n4\n5\n3\n5" | ./output\'', returncode=2, stdout=b'', stderr=b'2: 1: Syntax error: Unterminated quoted string\n') I am not getting what's wrong is in my code
subprocess.call(shell=True) has some significant security problems and I'd avoid it whenever possible. It opens your application to a shell injection attack. You're actually seeing this in your code: if the string in problem_testcase.input contains any characters that are meaningful to a shell, the shell will interpret them, which can cause it to do unexpected things. In your input, Python expands the \n newlines and then hands them off to the host shell it launches. So the shell command that's being run is docker exec oj-cpp sh -c 'echo "2 4 5 3 5" | ./a.out ' and the shell stops at the first newline and tries to run the command up to there, which produces your error. If the input string can be controlled, and you know docker commands work, it's actually straightforward to use this to take over the whole host. The important thing to know here is that docker exec will pass its own stdin to the program it's running. So you don't need the echo input | program syntax; since you don't need that, you don't need the sh -c invocation; and since you're only running a fixed command with no substitutions, you don't need shell=True. x = subprocess.run(['docker', 'exec', 'oj-cpp', './a.out'], input=problem_testcase.input, capture_output=True) I might make two other changes to this program. The Docker SDK for Python provides a more direct access to Docker functionality, without using subprocess. It doesn't require a docker binary, though it still requires the Docker daemon to be running and for you to have permission to access it. I'd also avoid scripting docker exec. If you think of a container as a wrapper around a single process, docker exec starts a second process within that process, which is a little odd. If you docker run a new (temporary) container, it starts up in a known state, and there's reduced risk of different program invocations interfering with each other. import docker client = docker.from_env() # Start the container (`docker run -d -i some_image`) container = client.containers.run(some_image, detach=True, stdin_open=True) # Send the input string into the container socket = container.attach_socket() socket.send(problem_testcase.input.encode('utf-8')) socket.close() # Let the program run, collect its output, clean up container.wait() output = container.logs() container.remove()
72,934,250
72,934,294
I am stuck in this binary search problem in geeks for geeks (time limit exceeded)
C++ I don't know what went wrong or am I missing something ? always getting a time limit exceeded. class Solution { public: int binarysearch(int arr[],int n,int k){ int low = 0; int high = n-1; while(low < high){ int mid = (low + high)/2; if(arr[mid] == k){ return mid; } else if(arr[mid] < k){ high = mid + 1; } else{ low = mid-1; } } return -1; } };
Here's a hint. Take a closer look at this: else if(arr[mid] < k){ high = mid + 1; } else{ low = mid-1; } Now ask yourself. If arr[mid] is less than the value to be searched for, what range of indices should be searched for on the next iteration? Then compare that to what the code is actually doing.
72,934,253
72,939,243
How to use multi-threading in C++ binomial pricing?
I'm new to multithreading in C++, and I am not sure how to apply it. Can anyone help? I'm trying to make the BinomialTree function multithreaded, This is what I have tried so far: thread th1(BinomialTree,S0, r, q, sigma, T, N); th1.join(); But it doesn't work int main() { double K = 100; double S0 = 100; double r = 0.03; double q = 0; double sigma = 0.3; double T = 1; const int N = 1000; shared_ptr<Payoff> callPayOff = make_shared<PayoffCall>(K, r, T); EuropeanOption europeanCall(T, callPayOff); BinomialTree tree(S0, r, q, sigma, T, N); double callPrice1 = tree.Price(europeanCall); } double BinomialTree::Price(const Option &theOption) { if (!treeInitialized_) initializeTree(); for (long j = 0; j <= N; ++j) { // threads[j]=thread([&counter](){ tree_[N][j].second = theOption.ExpirationPayoff(tree_[N][j].first); } double disc = exp(-r*dt); for (long ir = N - 1; ir >= 0; --ir) { #pragma omp parallel for for (long j = 0; j <= ir; ++j) { double discountedExpectation = disc*0.5*(tree_[ir + 1][j].second + tree_[ir + 1][j + 1].second); //find the payoff at the node: tree_[ir][j].second = theOption.IntermediatePayoff(tree_[ir][j].first, discountedExpectation); } #pragma omp barrier } return tree_[0][0].second; }
From BinomialTree tree(S0, r, q, sigma, T, N); double callPrice1 = tree.Price(europeanCall); it looks like BinomialTree tree(...) is the definition of an object, and tree.Price is the actual function call. Your thread probably should be running the &BinomialTree::Price function. That said, thread th1(&BinomialTree::Price, tree, 0, r, q, sigma, T, N); th1.join(); will just cause the main thread to wait while th1 is running. For multi-threading, you want to do something useful with multiple threads at the same time. And in this simple example, there's of course nothing obvious that you can do. But in your real program, you might want to have a look. Note: since you've left out the code of &BinomialTree::Price, we can't tell if you could use multiple threads inside that function.
72,934,313
72,934,331
Function not updating internal state of mt19937
I have a function that generates and writes random integers: void randint(int min, int max, int times,std::mt19937 rng){ std::uniform_int_distribution<int> dist(min, max); for (int i=0;i<times;i++){ std::cout<<dist(rng)<<' '; } } When this function is called, generates numbers from the mt19937 object. However, when returning from the function, the mt19937 object's internal state is not updated. This can be seen by running this code below. int main(){ std::mt19937 gen(2845); std::uniform_int_distribution<int> spread(1,100); randint(1,100,5,gen); std::cout<<"| "; for (int i=0;i<5;i++){ std::cout<<spread(gen)<<' '; } Actual Output: 88 93 79 43 92 | 88 93 79 43 92 Expected output: 88 93 79 43 92 | 97 71 34 32 70 Is there any way for the internal state to be continuously updated even when passed through the function?
You are passing the object by value (i.e. you are copying the object when you call the function). Use a reference void randint(int min, int max, int times,std::mt19937& rng){
72,934,473
72,936,522
Retrieve Path by Wildcard in custom taget CmakeLists.txt
I'm trying to create a custom target in a CmakeList.txt which I'm planning to execute during the build process with Conan. When executing the build with conan build the sources are compiled and built, creating an output file with a dynmic name and a .a file extensions. Now my question is how is it possible to retrieve the path to this .a file? I've tried things like this: set(A_FILE ${CMAKE_BINARY_DIR}/*.a) or file(GLOB A_FILE ${CMAKE_BINARY_DIR}/*.a) But unfortunately both variants do not resolve the wildcard character and I end up with a path that is not usable. Is there any way to retrieve a path with the file extensions and some wildcards in a custom target? This target would be executed after the build process has finished and produced the *.a file.
If you want to manipulate created library after it is built, you can use add_custom_command with generator expressions: #create library add_library(my_lib STATIC my_lib.cpp) # list the contents of a newly created library add_custom_command( TARGET my_lib POST_BUILD COMMAND ar -t $<TARGET_FILE:my_lib> ) Note the $<TARGET_FILE:my_lib>; it is a generator expression that will retrieve the full path to the target my_lib. BTW, trying to guess/figure-out library path in a configure phase (i.e. during cmake run) is wrong, and will almost never work correctly. Instead, use "generator expressions" to retrieve the required data. At the end, here is the documentation about add_custom_command(build_events), and generator expressions (target queries).
72,934,598
72,934,755
Specialization of variadic template function over the non-variadic arguments
I have a template for a function that accepts at least one parameter and performs some formatting on the rest: template <typename T, typename... ARGS> void foo(T first, ARGS&&... args) { // ... } I want it to do a different thing when the first parameter is of a specific type. I like the compiler to choose this particular version, where the rest of the variadic arguments are just ignored. So I tried template specialization: template <> void foo(const ICON* p) { // ... } or: template <typename T, typename... ARGS> void foo(const ICON* p, ARGS&&... args) { // ... } I also tried a non-templated overload, though it always picks the first version. The caller code is supposed not to know about templates at all (legacy code, backwards-compatibility nonsense, etc.) So it relies on type deduction and calls like this: MyClass fooMaker; fooMaker.set("A", "B", 3.14, 42); // v1 fooMaker.set(pIcon); // v2 (special)
If you have access to c++17 or later, using if constexpr you can retain the true statement in the foo, at compile time, as follows: #include <type_traits> // std::is_pointer_v, std::is_same_v template <typename T, typename... ARGS> void foo(T first, ARGS&&... args) { if constexpr (std::is_pointer_v<T> // is pointer check && std::is_same_v<T, ICON*>) // is the type is of "ICON*" { // ICON impli... } else { // other impli... } } See online demo
72,934,901
72,935,772
inline constexpr have external linkage?
I know global constexpr variables have internal linkage. so how is it that inline constexpr are introduced with having external linkage? does adding inline just converts internal linakges to external linkages in all cases?
There seems to be a little bit of confusion about what "linkage" and "inline" actually means. They are independent (orthogonal) properties of a variable, but nevertheless coupled together. To inline a variable one declares it inline. Declaring a constexpr variable at namescope does not imply inline [1]. To declare a variable to have internal linkage one declares it static or more preferrable puts it into an anonymous namespace [2],[3]. For const and constexpr (which implies const) variables there is a special rule, which gives them internal linkage as long as they are non-inline [4]. Because constexpr variables require an immediate definition [5], you typically want them to be be inline which allows multiple (equivalent) definitions in multiple translation units: \\ c.hpp inline constexpr int c = 0; // define it in header \\ a.cpp #include "c.hpp" // c is defined in a.cpp int a = c; // use it \\ b.cpp #include "c.hpp" // c is re-defined in b.cpp int b = c; // use it The linkage of c in that example above is external, because the special rule for const variables only applies to non-inline variables. Note that when ommiting the inline specifier in the example makes each source file get an independent non-inline definition of c with internal linkage. It will still compile but you have to be careful to not use c in any inline functions [6]. You can put inline constexpr variables into an anonymous namespace or declare it static to make its linkage internal. If we changed the example above into \\ c.hpp namespace { inline constexpr int c = 0; }; \\ a.cpp ... the effects would be almost the same as if ommitin the inline in the original example. Each translation unit gets its own version of the (now inlined) variable and you have to make sure that you don't use c in an inline function.
72,934,928
72,935,043
SEGMENTATION FAULT for my code , need guidance with debugging
I am using the below code to solve the rat maze problem from geeksforgeeks.However I am getting the segmentation error and I am unable to debug it.Can someone guide me with the debugging? Here's the code: class Solution{ public: string x=""; void rat(vector<vector<int>>&m,int n,vector<string>&ans,int i,int j) { cout<<"cool"; if(i==n-1&&j==n-1) {ans.push_back(x); return;} if(m[i][j]==0) return; if(i<0||j<0||i==n||j==n) return ; if(i<n-1) { x+="D"; rat(m,n,ans,i+1,j); } x.pop_back(); if(j!=n-1) { x+="R"; rat(m,n,ans,i,j+1); } x.pop_back(); if(i>0) { x+="U"; rat(m,n,ans,i-1,j); } x.pop_back(); if(j>0) { x+="L"; rat(m,n,ans,i,j-1); } x.pop_back(); */ } vector<string> findPath(vector<vector<int>> &m, int n) { vector<string>ans; rat(m,n,ans,0,0); if(ans.size()==0) return {"-1"}; return ans; } };
Seem very likely to me that this code if(i>0) { x+="U"; rat(m,n,ans,i-1,j); } x.pop_back(); should be if(i>0) { x+="U"; rat(m,n,ans,i-1,j); x.pop_back(); } Same error several times. The way you have written it, you will remove characters from x that were never put there in the first place.
72,935,628
72,965,664
FLTK - Why fl_width function returns -1 for the length of a char array on a Linux machine?
I am using the fl_width function to create widgets whose size depends on their label (e.g., some Fl_Box). In the documentation for this function one reads FL_EXPORT double fl_width (const char *txt) Returns the typographical width of a nul-terminated string using the current font face and size. I encountered anyway some strange behaviors on my Linux machine when I run even a simple program as the following one. #include <FL/Fl.H> #include <FL/fl_draw.H> #include <FL/Fl_Double_Window.H> #include <FL/Fl_Box.H> #include <iostream> int main(){ Fl_Double_Window* W = new Fl_Double_Window(200,100,"Test"); W->begin(); // Creation of the char array const char* s1 = "text"; // Usage of the fl_width double I1 = fl_width(s1); // Print the result std::cout << I1 << std::endl; // A Fl_Box for comparinson Fl_Box* B1 = new Fl_Box(50,10,100,30,"New Box"); B1 -> box(FL_UP_BOX); // Another box whose width depends on the length of its label: Fl_Box* B2 = new Fl_Box(50,50,(int)I1,30,s1); B2 -> box(FL_UP_BOX); W->end(); W->show(); return Fl::run(); } In this case I get -1 as a result for the length of s1, as it is evident also from the second Fl_Box that actually does not appear. Same result when I use a std::string with its c_str() method. Where did I get wrong? Have I have to include some other header files? My setup is the following: Ubuntu 20.04.04, FLTK 1.3.8, gcc version 9.4.0. On other projects on my MacBook Pro (MacOS 11) I did not have any problems.
One should invoke fl_font(Fl_Font face, Fl_Fontsize fsize) first. As user7860670 suggested in the comments to the question, one have to invoke fl_font(Fl_Font face, Fl_Fontsize fsize) for having a proper behaviour for the fl_width() function. This is also explained in the documentation of fl_font and in the (local) header file fl_draw.H. The example code below shows how to call this function and how setting different sizes impacts on the further computations. #include <FL/Fl.H> #include <FL/fl_draw.H> #include <FL/Fl_Double_Window.H> #include <FL/Fl_Box.H> #include <iostream> int main(){ Fl_Double_Window* W = new Fl_Double_Window(200,150,"Test"); W->begin(); // Creation of the char array const char* s1 = "text"; fl_font(0,20); std::cout << "The initial size is set to " << fl_size() << std::endl; // Usage of the fl_width double I1 = fl_width(s1); // Print the result std::cout << "The length hence is " << I1 << std::endl; // A Fl_Box for comparinson Fl_Box* B1 = new Fl_Box(50,10,100,30,"New Box"); B1 -> box(FL_UP_BOX); // Another box whose width depends on the length of its label: Fl_Box* B2 = new Fl_Box(50,50,(int)I1,30,s1); B2 -> box(FL_UP_BOX); // Another Box which shows that actually fl_width() returns a number depending on the size of the font fl_font(0,40); std::cout << "The new size is set to " << fl_size() << std::endl; double I2 = fl_width(s1); std::cout << "The new length hence is " << I2 << std::endl; Fl_Box* B3 = new Fl_Box(50,90,(int)I2,30,s1); B3 -> box(FL_UP_BOX); W->end(); W->show(); return Fl::run(); }
72,935,819
72,935,985
When to use reinterpret_cast without disobeying the strict aliasing rule?
For a long time I've used reinterpret_cast like this: static_assert(sizeof(int) == sizeof(float)); int a = 1; float b = *reinterpret_cast<float*>(&a); // viewed as float in binary. However, when I reviewed type conversion in C++ recently, I found that it's UB when the strict aliasing rule is considered! Dereferencing a different type(or to be exact, non-similar type) of pointer to the initial data may be optimized. (I've known that std::bit_cast in C++20 is an alternative way.) From my perspective, reinterpret_cast is mainly used for pointer type conversion. Nevertheless, how can I use another type of pointer considering dereferencing is prohibited? I've browsed when to use reinterpret_cast, and an answer is quoted below : One case when reinterpret_cast is necessary is when interfacing with opaque data types. This occurs frequently in vendor APIs over which the programmer has no control. Here's a contrived example where a vendor provides an API for storing and retrieving arbitrary global data. But when it comes to the implementation of these APIs, if the data should be used there, it's hard to avoid dereferencing the pointer. It seems that only converting to another pointer type and back to the initial pointer type is reasonable (But what's the point? Why don't you use the initial type or define a template directly?). So my question is: When to use reinterpret_cast without disobeying that rule? Is there any general usage? I'm really a novice in C++, so any advice would be appreciated.
When you use a reinterpret_cast in your code, your are telling the compiler: "I know what I'm doing – just implement the cast and trust me that the result will be OK to use." The compiler will then use the result of that cast as it would any other object of the specified destination type. So, if you know that a particular value is the address of an actual float data type, then you can safely cast (say) an intptr_t value to a float* and dereference the resulting pointer. A common case for such use of the reinterprt_cast occurs in Windows (WinAPI) programming: the LPARAM of a Windows message is often used to point to a particular type of data structure. Here is a 'pseudo-example' of a handler for the WM_NOTIFY message: BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT *pResult) { NMHDR *pHdr = reinterpret_cast<NMHDR *>(lParam); switch (pHdr->code) { // ... do some stuff with the data in the referenced NMHDR structure } //... *pResult = 0; return TRUE; } In this case, the Windows framework has 'promised' that the lParam argument received will be the address of a NMHDR structure, so the cast is safe. (Note that other C++ casts won't work for such a conversion: only reinterpret_cast or a "C-Style" cast can convert the integer type to a pointer.) However, using any sort of cast (reinterpret_cast or C-style, especially) for so-called type punning is never a good idea, because of the strict aliasing rules you have mentioned in your question. To copy the bits ("as-is") from an int to a float (assuming those types are the same size, and that you don't have access to the C++20 std::bit_cast), you should use std::memcpy, instead of dereferencing aliased pointers.
72,935,947
72,937,802
CMake imported targets in add_subdirectory not available in main CMakeLists.txt
I want to build an application that depends on the OpenCV (version 3.4.6) viz module. This module has the VTK library (version 7.1.1) as dependency. I want to use ExternalProject to build both, the vtk library and the opencv viz module and subsequently want to build the main application, all in one cmake run. . ├── CMakeLists.txt ├── deps │   └── CMakeLists.txt └── main.cpp I am using the cmake ExternalProject module to build both opencv and vtk inside a subdirectory like this: deps/CMakeLists.txt cmake_minimum_required(VERSION 3.14) project(dependencies) include(ExternalProject) ExternalProject_add( vtklib GIT_REPOSITORY https://github.com/Kitware/vtk GIT_TAG v7.1.1 GIT_PROGRESS TRUE UPDATE_COMMAND "" CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX} -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF -DVTK_DATA_EXCLUDE_FROM_ALL=ON -DVTK_USE_CXX11_FEATURES=ON -Wno-dev ) add_library(vtk INTERFACE IMPORTED GLOBAL) add_dependencies(vtk vtklib) ExternalProject_add( ocv GIT_REPOSITORY https://github.com/opencv/opencv GIT_TAG 3.4.6 GIT_PROGRESS TRUE UPDATE_COMMAND "" CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX} -DWITH_VTK=ON -Wno-dev ) # ExternalProject_Get_Property(ocv install_dir) # include_directories(${install_dir}/src/ocv/include) include_directories(${CMAKE_INSTALL_PREFIX}/include) set(ocv_libdir ${CMAKE_INSTALL_PREFIX}/${CMAKE_VS_PLATFORM_NAME}/vc15) set(OCV_VERSION 346) add_dependencies(ocv vtklib) add_library(opencv_core SHARED IMPORTED) set_target_properties(opencv_core PROPERTIES IMPORTED_IMPLIB "${ocv_libdir}/lib/opencv_core${OCV_VERSION}.lib" IMPORTED_LOCATION "${ocv_libdir}/bin/opencv_core${OCV_VERSION}.dll" ) add_library(opencv_viz SHARED IMPORTED) set_target_properties(opencv_viz PROPERTIES IMPORTED_IMPLIB "${ocv_libdir}/lib/opencv_viz${OCV_VERSION}.lib" IMPORTED_LOCATION "${ocv_libdir}/bin/opencv_viz${OCV_VERSION}.dll" ) the main CMakeLists.txt looks like this: cmake_minimum_required(VERSION 3.14) project(cmaketest VERSION 0.1 DESCRIPTION "" LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_Flags "${CMAKE_CXX_FLAGS} -std=c++17") # include_directories(${CMAKE_INSTALL_PREFIX}/include) add_subdirectory(deps) add_executable(${PROJECT_NAME} main.cpp) target_link_libraries(${PROJECT_NAME} opencv_core opencv_viz) install( TARGETS ${PROJECT_NAME} EXPORT "${PROJECT_NAME}-targets" LIBRARY DESTINATION lib/ ARCHIVE DESTINATION lib/${CMAKE_PROJECT_NAME} RUNTIME DESTINATION bin PUBLIC_HEADER DESTINATION include/${CMAKE_PROJECT_NAME}/${PROJECT_NAME} ) the main.cpp for completeness: #include <opencv2/viz.hpp> int main(){} but it seems that the include_directories and add_library calls inside deps/CMakeLists.txt do not work on the correct scope as i am getting the following error messages: error C1083: File (Include) can not be opened: "opencv2/viz.hpp" if i uncomment the include_directories inside the main CMakeLists.txt then i get a linker error (this is not what i want, included directories should be specified inside deps/CMakeLists.txt): LNK1181: opencv_core.lib can not be opened If i just copy the contents of deps/CMakeLists.txt in the main CMakeLists.txt in place of the add_subdirectory call everything works fine. So, how do i get the include directories and the created targets from the subdirectory in my main CMakeLists? edit: call to cmake configure: cmake.exe -B build -S . -G "Visual Studio 17 2022" -A x64 -T v141 -DCMAKE_INSTALL_PREFIX=D:/test call to cmake build: cmake.exe --build build --config Release --target install
Unlike to normal targets, which are global, an IMPORTED target by default is local to the directory where it is created. For extend visibility of the IMPORTED target, use GLOBAL keyword: add_library(opencv_core SHARED IMPORTED GLOBAL) This is written in the documentation for add_library(IMPORTED): The target name has scope in the directory in which it is created and below, but the GLOBAL option extends visibility.
72,936,121
72,957,664
what is the optimize argument in pcap_compile( , , , int optimize, ) in npcap library?
pcap_compile(pcap, &fcode, "tcp", 0, PCAP_NETMASK_UNKNOWN) Here I have set to 0 and it is working, but I want to know what it does. I am trying to filter tcp packets in a pcap file. And does pcap_setfilter() reconstructs pcap file into a given fcode?
Well, as stated in the pcap_compile man page, optimize controls whether optimization on the resulting code is performed. OK, but of course you might be wondering, "What does that really mean?" To answer that question, I think it's best to provide an example. Consider the following capture filter: icmp or udp port 53 or bootpc. If you run tcpdump, passing it that filter expression, along with the -d and -O options, it will generate a non-optimized BPF program containing 46 instructions that looks like this: tcpdump -d -O "icmp or udp port 53 or bootpc" (000) ldh [12] (001) jeq #0x800 jt 2 jf 4 (002) ldb [23] (003) jeq #0x1 jt 44 jf 4 (004) ldh [12] (005) jeq #0x86dd jt 6 jf 12 (006) ldb [20] (007) jeq #0x11 jt 8 jf 12 (008) ldh [54] (009) jeq #0x35 jt 44 jf 10 (010) ldh [56] (011) jeq #0x35 jt 44 jf 12 (012) ldh [12] (013) jeq #0x800 jt 14 jf 24 (014) ldb [23] (015) jeq #0x11 jt 16 jf 24 (016) ldh [20] (017) jset #0x1fff jt 24 jf 18 (018) ldxb 4*([14]&0xf) (019) ldh [x + 14] (020) jeq #0x35 jt 44 jf 21 (021) ldxb 4*([14]&0xf) (022) ldh [x + 16] (023) jeq #0x35 jt 44 jf 24 (024) ldh [12] (025) jeq #0x86dd jt 26 jf 32 (026) ldb [20] (027) jeq #0x11 jt 28 jf 32 (028) ldh [54] (029) jeq #0x44 jt 44 jf 30 (030) ldh [56] (031) jeq #0x44 jt 44 jf 32 (032) ldh [12] (033) jeq #0x800 jt 34 jf 45 (034) ldb [23] (035) jeq #0x11 jt 36 jf 45 (036) ldh [20] (037) jset #0x1fff jt 45 jf 38 (038) ldxb 4*([14]&0xf) (039) ldh [x + 14] (040) jeq #0x44 jt 44 jf 41 (041) ldxb 4*([14]&0xf) (042) ldh [x + 16] (043) jeq #0x44 jt 44 jf 45 (044) ret #262144 (045) ret #0 And if you run that same tcpdump command, but without the -O option, thus enabling optimization (the default), then the resulting BPF program contains only 24 instructions that looks like this: tcpdump -d "icmp or udp port 53 or bootpc" (000) ldh [12] (001) jeq #0x800 jt 2 jf 13 (002) ldb [23] (003) jeq #0x1 jt 22 jf 4 (004) jeq #0x11 jt 5 jf 23 (005) ldh [20] (006) jset #0x1fff jt 23 jf 7 (007) ldxb 4*([14]&0xf) (008) ldh [x + 14] (009) jeq #0x35 jt 22 jf 10 (010) jeq #0x44 jt 22 jf 11 (011) ldh [x + 16] (012) jeq #0x35 jt 22 jf 21 (013) jeq #0x86dd jt 14 jf 23 (014) ldb [20] (015) jeq #0x11 jt 16 jf 23 (016) ldh [54] (017) jeq #0x35 jt 22 jf 18 (018) jeq #0x44 jt 22 jf 19 (019) ldh [56] (020) jeq #0x35 jt 22 jf 21 (021) jeq #0x44 jt 22 jf 23 (022) ret #262144 (023) ret #0 Both programs are functionally equivalent but the latter is going to be much more efficient, so in general enabling optimization should be preferred. If you'd like even more information about optimization, then I would recommend visiting the bpfexam man page where you can even enter an arbitrary capture filter and examine the results. Regarding pcap_setfilter, as the man page indicates, it is used to specify the filter program (such as those you can see above), which ultimately determines which packets are captured and which ones are discarded.
72,937,106
72,982,039
How can I interact with html elements use QT
For example, I have a simple HTML page with button and label (or something else). How can I change the text in label (or something else) and catch the button click use QT. I try to use QWebEngineView to show html, but I don`t know how to interact with elements from QT modul, just change the url, but I dont think its a better way
To be able to interact with HTML rendered with QWebEngine you need to use QWebChannel. You can find the basic guidelines at Qt WebChannel JavaScript API page. To implement intercommunication with JavaScript in your HTML page you need: Add Qt += webchannel in your project file Implement a QObject derived class that should be a proxy between C++ and JavaScript. The simpliest way to make it usable in JavaScript is to create getters, setters and signals for the values you intend to use in JavaScript, and expose them as Q_PROPERTY. Example: class ProxyClass: public QObject { Q_OBJECT Q_PROPERTY(QString value READ value WRITE setValue NOTIFY valueChanged) public: explicit ProxyClass(QObject *parent = nullptr); QString value() const; void setValue(const QString &aValue); signals: void valueChanged(const QString &aValue); }; Set HTML to QWebEngineView with QWebEngineView::setHtml, instantiate your "proxy" class and create QWebChannel for the page (note that you can register multiple objects in QWebChannel). Example: //create QWebEngineView and set HTML from resources auto webView = new QWebEngineView; QFile htmlFile(":/page.html"); htmlFile.open(QIODevice::ReadOnly); QString html = htmlFile.readAll(); webView->setHtml(html); //create and set up the instance of your "proxy" class auto proxy = new ProxyClass; //create QWebChannel and set it for the page QWebChannel *webChannel = new QWebChannel(webView->page()); webChannel->registerObject(QStringLiteral("proxy"), proxy); webView->page()->setWebChannel(webChannel); Embed qwebchannel.js file in HTML. File is located at <Qt installation directory>/Examples/Qt-<version>/webchannel/shared directory. You can include it in application resources and embed in HTML with <script type="text/javascript" src="qrc:/qwebchannel.js"></script> Create onload event handler in HTML and initialize QWebChannel in it. Example: function loaded() { new QWebChannel(qt.webChannelTransport, function (channel) { <!--get and assign "proxy"--> window.proxy = channel.objects.proxy; <!--now you can--> <!--get values--> let proxyValue = proxy.value; <!--connect signals--> proxy.valueChanged.connect(() => { ... }); }); } function someFunction(newValue) { <!--set values--> proxy.value = newValue; } ... <body onload="loaded()">...</body> Once you initialized a web channel and assigned "proxy" object to the window object, you are free to use it everywhere in JavaScript.
72,937,139
72,937,419
Invalid conversion on template argument type?
With help from this question, I have gradually built up this code, a wrapper around a class member function. The idea is that I can use operator* on my property to write to the class object: #include <cstdio> #include <type_traits> #include <utility> using namespace std; class testclass { public: double get() { return d_; } bool set(double d) { d_ = d; return true; } double d_ = 0.0; }; template <typename PropertyType> struct DEFAULT_WRAPPER_PROXY { DEFAULT_WRAPPER_PROXY(PropertyType* p) : property_(p) {} operator typename PropertyType::GetterReturnType() { return property_->Get(); } DEFAULT_WRAPPER_PROXY& operator=(typename PropertyType::GetterReturnType val) { property_->Set(val); return *this; } PropertyType* property_; }; template <typename PropertyType> struct LOGGING_WRAPPER_PROXY { LOGGING_WRAPPER_PROXY(PropertyType* p) : property_(p) {} operator typename PropertyType::GetterReturnType() { // Log some interesting stuff return property_->Get(); } LOGGING_WRAPPER_PROXY& operator=(typename PropertyType::GetterReturnType val) { // Log some interesting stuff property_->Set(val); return *this; } PropertyType* property_; }; template<typename Retriever, typename Updater, typename OwningClass, template<typename PropertyType> class WRAPPER_PROXY = DEFAULT_WRAPPER_PROXY> struct Wrapper { Wrapper(Retriever retriever, Updater updater, OwningClass* owner) : retriever_(retriever), updater_(updater), containingClass_(owner) {} using GetterReturnType = std::invoke_result_t<Retriever, OwningClass>; GetterReturnType Get() { return (containingClass_->*retriever_)(); } template<typename...Args> using SetterReturnType = std::invoke_result_t<Updater, OwningClass, Args...>; template<typename...Args> SetterReturnType<Args...> Set(Args&&... args) { return (containingClass_->*updater_)((forward<Args>(args))...); } WRAPPER_PROXY<Wrapper<Retriever, Updater, OwningClass>> operator*() { return WRAPPER_PROXY(this); } Retriever retriever_; Updater updater_; OwningClass* containingClass_; }; template< template<typename PropertyType> class WRAPPER_PROXY, typename Retriever, typename Updater, typename OwningClass> auto MakeWrapper(Retriever&& retriever, Updater&& updater, OwningClass* const owner) { return Wrapper<Retriever, Updater, OwningClass, WRAPPER_PROXY>( std::forward<Retriever>(retriever), std::forward<Updater>(updater), owner ); } int main() { testclass tc; // Cleaner (using CTAD here, could also use auto) Wrapper pp3 = MakeWrapper<LOGGING_WRAPPER_PROXY>( &testclass::get, &testclass::set, &tc ); *pp3 = 100; Wrapper pp4 = MakeWrapper<DEFAULT_WRAPPER_PROXY>( &testclass::get, &testclass::set, &tc ); *pp4 = 100; } This does not compile on *pp3 = 100, because VS2022 states cannot convert from 'LOGGING_WRAPPER_PROXY<Wrapper<double (__cdecl testclass::* )(void),bool (__cdecl testclass::* )(double),testclass,LOGGING_WRAPPER_PROXY>>' to 'LOGGING_WRAPPER_PROXY<Wrapper<Retriever,Updater,OwningClass,DEFAULT_WRAPPER_PROXY>>' with [ Retriever=double (__cdecl testclass::* )(void), Updater=bool (__cdecl testclass::* )(double), OwningClass=testclass ] I don't understand why it is trying to create a DEFAULT_WRAPPER_PROXY, what is going wrong here please?
The cause of the problem: struct Wrapper is a struct with 4 template parameters, and the last of them has a default: template<typename Retriever, typename Updater, typename OwningClass, template<typename PropertyType> class WRAPPER_PROXY = DEFAULT_WRAPPER_PROXY> struct Wrapper { /* ... */ } In this line in struct Wrapper: WRAPPER_PROXY<Wrapper<Retriever, Updater, OwningClass>> operator*() { You don't specify the last template parameter of Wrapper, and therefore the default of DEFAULT_WRAPPER_PROXY is used. This will cause a compilation error when trying to use operator* with the result of MakeWrapper<LOGGING_WRAPPER_PROXY>. The solution: You can fix it as shown below by adding the last template argument explicitly: //-----------------------------------------------------vvvvvvvvvvvvv WRAPPER_PROXY<Wrapper<Retriever, Updater, OwningClass, WRAPPER_PROXY>> operator*() {
72,937,566
72,987,189
What is the true getrusage resolution?
I'm trying to measure getrusage resolution via simple program: #include <cstdio> #include <sys/time.h> #include <sys/resource.h> #include <cassert> int main(int argc, const char *argv[]) { struct rusage u = {0}; assert(!getrusage(RUSAGE_SELF, &u)); size_t cnt = 0; while(true) { ++cnt; struct rusage uz = {0}; assert(!getrusage(RUSAGE_SELF, &uz)); if(u.ru_utime.tv_sec != uz.ru_utime.tv_sec || u.ru_utime.tv_usec != uz.ru_utime.tv_usec) { std::printf("u:%ld.%06ld\tuz:%ld.%06ld\tcnt:%ld\n", u.ru_utime.tv_sec, u.ru_utime.tv_usec, uz.ru_utime.tv_sec, uz.ru_utime.tv_usec, cnt); break; } } } And when I run it, I usually get output similar to the following: ema@scv:~/tmp/getrusage$ ./gt u:0.000562 uz:0.000563 cnt:1 ema@scv:~/tmp/getrusage$ ./gt u:0.000553 uz:0.000554 cnt:1 ema@scv:~/tmp/getrusage$ ./gt u:0.000496 uz:0.000497 cnt:1 ema@scv:~/tmp/getrusage$ ./gt u:0.000475 uz:0.000476 cnt:1 Which seems to hint that the resolution of getrusage is around 1 microsecond. I thought it should be around 1 / getconf CLK_TCK (i.e. 100hz, hence 10 millisecond). What is the true getrusage resolution? Am I doing anything wrong? Ps. Running this on Ubuntu 20.04, Linux scv 5.13.0-52-generic #59~20.04.1-Ubuntu SMP Thu Jun 16 21:21:28 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux, 5950x.
The publicly defined tick interval is nothing more than a common reference point for the default time-slice that each process gets to run. When its tick expires the process loses its assigned CPU which then begins executing some other task, which is given another tick-long timeslice to run. But that does not guarantee that a given process will run for its full tick. If a process attempts to read() an empty socket, and has nothing to do in a middle of a tick the kernel is not going to do nothing with the process's CPU, and find something better to do, instead. The kernel knows exactly how long the process ran for, and there is no reason whatsoever why the actual running time of the process cannot be recorded in its usage statistics, especially if the clock reference used for measuring process execution time can offer much more granularity than the tick interval. Finally the modern Linux kernel can be configured to not even use tick intervals, in specific situations, and its advertised tick interval is mostly academic.
72,937,810
72,938,280
Making a function in a struct template
So i made a template struct cause i want to be able to decide what type i give to my val. But when creating a function i don't know how to do it. Here's what i'm doing: In my .hpp template<typename T> struct Integer { T val; void setUint(const T &input); }; Now i can set what variable i want in the val and what i want in the function. But now in my cpp i don't know how to invoke the function. void Integer<T>::setUint(const T &input) { val = input; } Error: identifier "T" is undefined.
A template function is a way to operate with generic types (you may consider the type as an argument). Your template parameter T allows to pass different types to a function when you invoke the function (which means, simply said, you may replace T with some other types int, double, ...) Please, have a look at the following simple example. #include <iostream> #include <typeinfo> // you may put it all in a hpp and thus include the hpp file in the CPP template<typename T> struct Integer { T val; void setUint(const T &input){ val=input; std::cout <<"the type is " << typeid(T).name() << " value is "<< val << std::endl; } }; // or look at Jarod42's implementation details. /* template<typename T> void Integer<T>::setUint(const T &input){ val=input; std::cout <<"the type is " << typeid(T).name() << " value is "<< val << std::endl; }*/ // and here you have your cpp calling you template function with different types int main() { Integer<double> value; value.setUint(1500000); Integer<int> value2; value2.setUint(5); return 0; }
72,939,306
72,940,705
How to set `sf::Drawable` positions sfml
I'm trying to declare a sf::Drawable * property inside my class body. the code i already wrote: #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> class View{ protected: sf::Drawable *view; }; and inside the class constructor, I want to use the view properties: class View{ public: View(){ view->...} protected: sf::Drawable *view; } but I cannot access any of the sf::Drawable methods. I get the No member named 'setPosition' in 'sf::Drawable' warning from IDE. the only code suggestion i get from code completer is: draw(RenderTarget& target, RenderStates states)
Indeed, sf::Drawable doesn't have a setPosition method. You could instead use sf::Transformable*, which does have setPosition. If you need to have drawable properties, then... If all your items are either shapes/sprites/texts, consider walking down the inheritance chain and use sf::Shape, sf::Sprite, or sf::Text. Make a separate class for each (ShapeView, SpriteView, TextView). Use dynamic_cast, as suggested by TheMedicineSeller. But this will incur a small runtime cost.
72,939,414
72,939,894
c++ classes and vector members
I have checked Stack Overflow for a sample of these class vectors and none of the answers point out common uses of vectors in a class . My code works but I have a few questions on it . I have a struck of objects that is stored in a class member vector struct Station { std::string StationName; int StationId; int PlayerId; std::vector<float> position; }; Here is the class that declaration with the Vectors class playerData { public: std::vector <playerDataDetails> PlayerList; std::vector<Station> Stations; void addNewPlayer(std::string Name , std::string faction , int Id ); void PrintPlayer(); void AddStations(int PlayerNumber, std::string name); }; When running the member function this is how Im accessing the Vector void playerData::AddStations(int PlayerNumber, std::string name) { // p[i]. Station s ; s.StationName = name; s.StationId = 1; s.PlayerId = PlayerNumber; s.position = { 2.1f, 1.1f , 1.1f}; // s.position = { { 2.1f }, { 2.3f }, { 2.3f } }; this->Stations.push_back(s); } My question is this . this->Stations.push_back(s); Is this the correct way to add station to the stations vector ? Is this copy or move Semantics ? Is there another way of doing this with pointers and references ? And is this the most efficient way of working with Vectors in a class ?
Is this the correct way to add station to the stations vector ? It's a perfectly fine approach, just a little inefficient. Is this copy or move Semantics ? Copy semantics (this->Stations.push_back(s); invokes the version of push_back taking a const reference and copies it into the vector). Minimalist changes could avoid unnecessary copies by changing s.StationName = name; to s.StationName = std::move(name); and this->Stations.push_back(s); to this->Stations.push_back(std::move(s));, which is enough to replace all copies with moves (though additional changes could reduce the number of moves and potentially eliminate some temporaries). Is there another way of doing this with pointers and references ? Yes. Pointers don't help, but more careful use of move semantics and/or emplace* semantics (to avoid temporaries entirely) could improve things (see below). And is this the most efficient way of working with Vectors in a class ? No. This could be done far more efficiently by avoiding some unnecessary copies and/or moves. Without changing Station, you could replace the entire body of AddStations with either: this->Stations.push_back({std::move(name), 1, PlayerNumber, {2.1f, 1.1f , 1.1f}}); or: this->Stations.emplace_back(Station{std::move(name), 1, PlayerNumber, {2.1f, 1.1f , 1.1f}}); adding std::move() around name to avoid a copy in favor of a move, and avoiding a copy of Station (it probably still needs to move-construct it into the vector though). If you defined an explicit constructor for Station, e.g. Station(std::string sn, int sid, int pid, std::vector<float> pos) : StationName{std::move(sn)}, StationId(sid), PlayerId(pid), position(std::move(pos)) {}, you could also use: this->Stations.emplace_back(std::move(name), 1, PlayerNumber, std::vector<float>{2.1f, 1.1f , 1.1f}); which would definitely avoid a move of a Station object itself (though it still has to move the name and the temporary vector in the process of constructing it directly into the Stations). The various forms of weirdness in why each form of push_back or emplace_back works, or doesn't, with varying levels of explicitness is explained on this question.
72,939,460
72,939,842
curl_easy_perform() API crashes
I am trying to get the idea about libcurl and I am trying to download simple photo from the url. But my program crashes when it goes inside curl_easy_perform() API. Any idea about it? #include <stdio.h> #include <curl/curl.h> #include <QDebug> #include <string> int main(void) { CURL *curl; FILE *fp; CURLcode res; curl_global_init(CURL_GLOBAL_ALL); std::string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Nusfjord_road%2C_2010_09.jpg/1280px-Nusfjord_road%2C_2010_09.jpg"; //std::string url = "https://ra-jenkins-nyk01.siemens.net/job/TestCase_Logs/ws/OBU_Int_Build/TestCases/TC_30520_OBU_detects_dir_to_increase_whn_conf_increase_dir/TC_30520_OBU_detects_dir_to_increase_whn_conf_increase_dir.ctr"; char outfilename[FILENAME_MAX] = "D:/ankit.jpg"; curl = curl_easy_init(); if (curl) { fp = fopen(outfilename,"wb"); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); //curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); //curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); if(res == CURLE_OK) printf("Download Successful."); else printf("Not sucessful"); curl_easy_cleanup(curl); fclose(fp); } return 0; } Compiler :- mingw libcurl version :7.84.0
I wonder if you are using libcurl library as a win32 dll or static library, according to the libcurl official documentation, it says If you are using libcurl as a win32 DLL, you MUST use a CURLOPT_WRITEFUNCTION if you set this option or you will experience crashes. You may want to see in here: click
72,939,957
72,940,037
How to pass in a callable object into a template class's constructor, able to call it later?
I want a class template whose constructor accepts (among other things), a callable argument. The class can then store a reference/pointer to this callable object and later call the function. I'll try to sketch out what I'm looking for here: template <typename T> class MyClass { public: MyClass(T _a, Callable& _f) : a(_a) , f(_f) {} float getFloat() { return f(a); } private: T a; Callable f; }; static float minus1(int num) { return num - 1; } class Stateful { public: Stateful() : num_calls(0) {} float operator()(int num) { ++num_calls; return static_cast<float>(num) - (static_cast<float>(num_calls) * 0.5); } private: int num_calls; }; static std::function<float(float)> invert = [](float a){ return -a; }; MyClass<int> option1(-5, &minus1); MyClass<int> option1a(99, &minus1); option1.getFloat(); // -6 option1a.getFloat(); // 98 static Stateful stateful{}; MyClass<int> option2(10, &stateful); option2.getFloat(); // 9.5 option2.getFloat(); // 9 MyClass<int> option2a(100, &stateful); option2a.getFloat(); // 98.5 option2.getFloat(); // 8 MyClass<float> option3(1.602, &invert); MyClass<float> option3a(-6.022, &invert); option3a.getFloat(); // 6.022 option3.getFloat(); // -1.602 float pi = 3.14f; MyClass<bool> option4(true, [&pi](bool b){return (b ? pi : 0.f);}; option4.getFloat(); // -3.14 I know I can solve this somewhat with some classical inheritance, i.e. use some BaseCallable subclass in MyClass and have all client Callable types inherit from that subclass. However, I don't like this because it would be nice to be able to pass in a lambda, or a std::function, into MyClass. I tried using Callable as a template, but I don't like this approach because I am using a variant so that I can have a container of MyClass: using Element = variant<MyClass<int>, MyClass<float>, MyClass<bool>>; vector<Element> vec; ... and I think the idea is unworkable if there is another template parameter there, especially with lambda types. I've tried implementing Callable as a type erasure Concept, which I think is the best way to go here but I can't seem to get it to work without throwing exceptions due to the internal shared_ptr of f being nullptr in the getFloat() call. Any help here would really be greatly appreciated! EDIT to add how the vector is used: using Element = variant<MyClass<int>, MyClass<float>, MyClass<bool>>; vector<Element> vec; vec.push_back(option1); vec.push_back(option2); vec.push_back(option2a); vec.push_back(option3); vec.push_back(option3a); vec.push_back(option4); for (auto& option : vec) { std::visit([](auto&& arg) { std::cout << arg.getFloat() << std::endl; }, option); } EDIT2: final working version following @aschepler's answer: https://godbolt.org/z/MbdK8o891
I've tried implementing Callable as a type erasure Concept That's a good idea, but the implementation has already been done for you. Use the type std::function<float(T)> as your Callable. The template argument to std::function is a function type, written in general as ReturnType(ParamType1, ParamType2,...). See std::function on cppreference.com.
72,940,070
72,940,120
I cant make the asterisk operator overloading it does nothing on the code below it should repeat my string 5 times but it doesnot
I can't make the asterisk operator overloading work. It does nothing on the code below. It should repeat my string 5 times, but it doesn't. .h file class Mystring { friend std::ostream &operator<<(std::ostream &os, const Mystring &rhs); friend std::istream &operator>>(std::istream &in, Mystring &rhs); private: char *str; // pointer to a char[] that holds a C-style string } .cpp file Mystring Mystring::operator * (int n) const { size_t buff_size = std::strlen(str) *n + 1; char *buff = new char[buff_size]; std::strcpy(buff,""); for (int i =1; i <=n; i++) std::strcat(buff,str); Mystring temp{buff}; delete [] buff; return temp; }; int main(){ Mystring s3{"abcdef"}; s3*5; cout << s3 << endl; }
Your operator* will repeat the string, but you throw away the result of s3*5. Try cout << s3*5 << endl;.
72,940,647
72,940,901
C++ : curly brackets with std library type
I try to understand the docs for std::less, where the following example is given for the usage with a template. #include <functional> #include <iostream> template <typename A, typename B, typename C = std::less<>> bool fun(A a, B b, C cmp = C{}) { return cmp(a, b); } int main() { std::cout << std::boolalpha << fun(1, 2) << ' ' // true << fun(1.0, 1) << ' ' // false << fun(1, 2.0) << ' ' // true << std::less<int>{}(5, 5.6) << ' ' // false: 5 < 5 (warn: implicit conversion) << std::less<double>{}(5, 5.6) << ' ' // true: 5.0 < 5.6 << std::less<int>{}(5.6, 5.7) << ' ' // false: 5 < 5 (warn: implicit conversion) << std::less{}(5, 5.6) << ' ' // true: less<void>: 5.0 < 5.6 << '\n'; } Output: true false true false true false true My question is: How is a std:: function used as a template argument? And in this concrete case, why are there curly brackets {} behind the C cmp = C or in the call std::less<double>{}(5, 5.6)?
This demo-code suffers from so-called 'uniform initialisation' (broken by design, be careful with its use especially in template code!), classic way to write the same code before uniform initialisation is: std::less<int>()(5, 5.6); // others analogously std::less is a callable class, a so-called 'functor', which means it provides an operator() by which objects of the class can be called just like a function (to be precise: the operator is a member function that gets called, just the syntax for getting called actually is the same). The code presented now first constructs such an object (calls the constructor; first pair of parentheses) while afterwards the so constructed object is called (the operator() with two arguments, second pair of parentheses). Equivalent code could be: std::less<int> li; // note that the parentheses need to be left out as you would // declare a function then instead of creating an object; // braces for uniform initialisation could remain li(5, 5.6); Note, though, that the life-time of the object li is now longer is longer (until leaving the current scope) than the one of the temporary (only current expression). In given case, there are no visible side effects, though, notably as std::less doesn't have any in its destructor.
72,940,979
72,941,406
Storing 2^31 in an `int`
Looking at links such as this and this, I understand that unsigned int in C++ should be of 16 bits. As such, the maximum value that it can store should be 32767. a. Why can we store INT_MAX in an int variable, such as: int res=INT_MAX; b. How is the code like below which calculates the power of 2 valid (runs without any error/warning): class Solution { public: bool isPowerOfTwo(int n) { return n>0 && (!(n&n-1)); } }; because the constraints say: -2^31 <= n <= 2^31 - 1, shouldn't we be using long?
a. Why can we store INT_MAX in an int variable, such as: int res=INT_MAX; INT_MAX is the maximum value that can be store in int. Per definition that can be stored in an int. b. How is the code like below which calculates the power of 2 valid (runs without any error/warning): ... because the constraints say: -2^31 <= n <= 2^31 - 1, shouldn't we be using long? The constraints are wrong. First they assume int to be 32bit, which is not the case on e.g. AVR. Second they assume int is two's-complement, which is only true since C++20. It would be more accurate to say the contraints are INT_MIN <= n <= INT_MAX. But really what is the point. The argument is int. That already says that. Better would be to use unsigned int, uintmax_t or a template. There is no reason to limit this function to int. Since C++20 there is std::has_single_bit for this.
72,941,116
72,941,252
CUDA optimise number of blocks for grid stride loop
I have started implementing a simple 1D array calculation using CUDA. Following the documentation I have first tried to define an optimal number of blocks and block size ... int N_array = 1000000 ... int n_threads = 256; int n_blocks = ceil(float(N_array / n_threads)); dim3 grid(n_blocks, 1, 1); dim3 block(n_threads, 1, 1); ... For the kernel, I have used a grid-stride approach as suggested in the nvidia blog ... int global_idx = blockIdx.x * blockDim.x + threadIdx.x; int stride = gridDim.x * blockDim.x; int threadsInBlock = blockDim.x; for (unsigned long long n = global_idx; n < N_array; n += stride) { ... My questions are: Is it fine to define the number of blocks as before? Or should they be defined such that the total number of requested threads is smaller than the number of available CUDA cores? (thinking that blocks in this way will take advantage of the grid-stride loop by doing more calculations). Since for this large array the number of requested threads is larger than the number of CUDA cores, is there any penalty on having many blocks inactive? Compared to requesting less blocks and keeping most of them active? (this is related to 1.)
Conventional wisdom is that the number of threads in the grid for a grid-stride loop should be sized to roughly match the thread-carrying capacity of the GPU in question. The reason for this is to maximize the exposed parallelism, which is one of the 2 most important objectives for any CUDA programmer. This gives the machine the maximum opportunity to do latency hiding. This is not the same as the number of CUDA cores. Divorce yourself from thinking about the number of CUDA cores in your GPU for these types of design questions. The number of CUDA cores is not relevant to this inquiry. The thread carrying capacity of the GPU, ignoring occupancy limiters, is the number of SMs in the GPU times the maximum number of threads per SM. Both of these quantities can be retrieved programmatically, and the deviceQuery sample code demonstrates how. If you want to be more precise, you can do an occupancy analysis on your kernel to determine the maximum number of threads that can actually be resident on a SM, then multiply this by the number of SMs. Occupancy analysis can be done statically, using the occupancy calculator spreadsheet provided as part of the CUDA toolkit, or dynamically using the occupancy API. (You can also inspect/measure occupancy after the fact with the nsight compute profiler.) There are many questions already here on the cuda SO tag discussing these things, and it is covered in the programming guide, so I'll not provide an occupancy tutorial here. The number you arrive at via occupancy analysis is upper-bounded by the calculation of number of SMs times max threads per SM. You will want to choose threads per block and number of block values based on that which allows the maximums to be achieved. For example, on a cc8.6 GPU with 1536 maximum threads per SM, you would want to choose perhaps 512 threads per block, and then a number of blocks equal to 3 times the number of SMs in your GPU. You could also choose 256 threads per block and 6 times the number of SMs. Choosing a value of 1024 threads per block, in this particular example, and ignoring occupancy considerations, might not be a good choice.
72,941,449
72,942,838
operator aligned new/delete vs operator aligned new[]/delete[]
I was writing an aligned operator for vector and I realize that I don't know the difference between operator aligned new/delete vs operator aligned new[]/delete[]. Both seem only de/allocate memory, not call de/constructor, both take the size in byte. So what the point having both ? What I am missing ? Demo code : https://wandbox.org/permlink/ErBIKvtt3t7wczpm #include <iostream> #include <iterator> #include <vector> #include <new> #include <type_traits> #include <memory> template <class T> T* allocate_bracket(std::size_t count) { return static_cast<T*> ( ::operator new[](count * sizeof(T) , std::align_val_t{64})); } template <class T> void deallocate_bracket(T* p, size_t count ) noexcept { ::operator delete[](p, count, std::align_val_t{64} ); } template <class T> T* allocate_basic(std::size_t count) { return static_cast<T*> ( ::operator new(count * sizeof(T) , std::align_val_t{64})); } template <class T> void deallocate_basic(T* p, size_t count ) noexcept { ::operator delete(p, count, std::align_val_t{64} ); } struct Noisy { Noisy() { std::cout << "ctr" << std::endl; } ~Noisy() { std::cout << "~" << std::endl; } }; int main() { const size_t nb = 2; std::cout << "Only alocate bracket \n"; { auto ptr = allocate_bracket<Noisy>(nb); deallocate_bracket<Noisy>(ptr, nb); } std::cout << "Only alocate basic \n"; { auto ptr = allocate_basic<Noisy>(nb); deallocate_basic<Noisy>(ptr, nb); } std::cout << "alocate/create bracket \n"; { auto ptr = allocate_bracket<Noisy>(nb); new (ptr) Noisy[nb]; ptr[nb-1] = Noisy(); for (size_t i= 0 ; i < nb; i++) (ptr+i)->~Noisy(); deallocate_bracket<Noisy>(ptr, nb); } std::cout << "alocate/create Basic \n"; { auto ptr = allocate_basic<Noisy>(nb); new (ptr) Noisy[nb]; // dunno if there is an other syntaxe ptr[nb-1] = Noisy(); for (size_t i= 0 ; i < nb; i++) (ptr+i)->~Noisy(); deallocate_basic<Noisy>(ptr, nb); } } Valgrind is clean (no miss match new/new[]/free) ==3200== Memcheck, a memory error detector ==3200== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==3200== Using Valgrind-3.17.0 and LibVEX; rerun with -h for copyright info ==3200== Command: ./op_new.out ==3200== Only alocate bracket Only alocate basic alocate/create bracket ctr ctr ctr ~ ~ ~ alocate/create Basic ctr ctr ctr ~ ~ ~ ==3200== ==3200== HEAP SUMMARY: ==3200== in use at exit: 0 bytes in 0 blocks ==3200== total heap usage: 6 allocs, 6 frees, 73,736 bytes allocated ==3200== ==3200== All heap blocks were freed -- no leaks are possible ==3200== ==3200== For lists of detected and suppressed errors, rerun with: -s ==3200== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Both seem only de/allocate memory, not call de/constructor, both take the size in byte. So what the point having both ? They do the same thing because you called the default operators, which do the same thing. In fact the default operator new[] just calls operator new. The reason for having two versions is that they could do different things, and a user might overload them separately.
72,941,731
72,942,885
qt and Opencv linking error "undefined reference"
I tried to set up opencv in qt and followed the steps exactly from here https://wiki.qt.io/How_to_setup_Qt_and_openCV_on_Windows, but got linking error like "undefined reference to cv::imread(cv::String const&, int)' debug/mainwindow.o: In function MainWindow::MainWindow(QWidget*)': C:\Users\Han\Desktop\QT_projects\build-TEST_OPENCV-Desktop_Qt_5_15_2_MinGW_64_bit->Debug/../TEST_OPENCV/mainwindow.cpp:17: undefined reference to `cv::imread(cv::String const&, >int)'" Here's the path of my opencv: C:\opencv-build\install\x86\mingw\lib Things I tried: Using the "add library" on Qt. However, qt coudlnt find the file that I specified. My code: .pro file #------------------------------------------------- # # Project created by QtCreator 2017-03-05T12:30:06 # #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = opencvtest TEMPLATE = app # The following define makes your compiler emit warnings if you use # any feature of Qt which as been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += main.cpp\ mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui INCLUDEPATH += C:\opencv\build\include LIBS += C:\opencv-build\bin\libopencv_core343.dll LIBS += C:\opencv-build\bin\libopencv_highgui343.dll LIBS += C:\opencv-build\bin\libopencv_imgcodecs343.dll LIBS += C:\opencv-build\bin\libopencv_imgproc343.dll LIBS += C:\opencv-build\bin\libopencv_features2d343.dll LIBS += C:\opencv-build\bin\libopencv_calib3d343.dll # more correct variant, how set includepath and libs for mingw # add system variable: OPENCV_SDK_DIR=D:/opencv/opencv-build/install # read http://doc.qt.io/qt-5/qmake-variable-reference.html#libs #INCLUDEPATH += $$(OPENCV_SDK_DIR)/include #LIBS += -L$$(OPENCV_SDK_DIR)/x86/mingw/lib \ # -lopencv_core320 \ # -lopencv_highgui320 \ # -lopencv_imgcodecs320 \ # -lopencv_imgproc320 \ # -lopencv_features2d320 \ # -lopencv_calib3d320 main #include "mainwindow.h" #include "ui_mainwindow.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // read an image cv::Mat image = cv::imread("f://1.jpg", 1); // create image window named "My Image" cv::namedWindow("My Image"); // show the image on window cv::imshow("My Image", image); } MainWindow::~MainWindow() { delete ui; } I appreciate any kind of help. Thanks!
Try specifying LIBS as LIBS += -Lpath/to/lib -llibname qmake reference LIBS += -LC:\opencv-build\bin -lopencv_core343 -lopencv_highgui343 -lopencv_imgcodecs343 -lopencv_imgproc343 -lopencv_features2d343 -lopencv_calib3d343
72,941,766
72,942,189
Non-Standard Syntax Error in Thread Constructor
I'm currently looking at producing a C++ library. I've not much experience with C++ and have what is probably a very basic question about class instance method calling. main.cpp msgserver m; std::thread t1(m.startServer, "192.168.50.128", 8081); msgserver.h class msgserver { public: msgserver() { } int startServer(std::string addr, int port); }; msgserver.cpp int msgserver::startServer(string addr, int port) This code results in: [C3867] 'msgserver::startServer': non-standard syntax; use '&' to create a pointer to member I know i can fix the compiler error by making this method static but I'm unsure if that is a requirement imposed by the fact it's being called in a thread constructor (which doesn't allow the parens on the call signature) or if I need to figure out the syntax. I've read around this and it's actually left me a bit more confused that when I started. It seems any fix I apply like: int &msgserver::startServer(string addr, int port) or std::thread t1(&m.startServer, "192.168.50.128", 8081); Is actually illegal syntax according to the compiler. How can I call this as an instance method? Or is actually a good idea to start a thread running in the background on a static function?
The syntax for a getting a pointer to a member function is &<class name>::<function_name>. In this case &msgserver::startServer would be the correct expression. Since std::invoke is used on the background thread, you need to pass the object to call the function for as second constructor parameter for std::thread, either wrapped in a std::reference_wrapper or by passing a pointer: std::thread t1(&msgserver::startServer, std::ref(m), "192.168.50.128", 8081); or std::thread t1(&msgserver::startServer, &m, "192.168.50.128", 8081);
72,943,094
72,946,444
Make all types passed as template-template argument a friend
In the following code, I would like whatever type I pass through to MyStruct to be declared as a friend of that structure. I anticipate having many different types being passed through and I don't want to have to manually add each one as a friend, like I have shown for the two current possible classes. I cannot figure out the syntax for this, can someone tell me please? template<typename MyStructType> struct OTHER_SUB_TYPE { OTHER_SUB_TYPE(MyStructType* p) { p->private_function(); } // Need to access other private members of MyStructType }; template<typename MyStructType> struct DEFAULT_SUB_TYPE { DEFAULT_SUB_TYPE(MyStructType* p) { p->private_function(); } // Need to access other private members of MyStructType }; template<template<typename> class SUB_TYPE = DEFAULT_SUB_TYPE> struct MyStruct { SUB_TYPE<MyStruct> Get() { return SUB_TYPE{this}; } // Would like to avoid having to declare each type individually! template<typename T> friend struct DEFAULT_SUB_TYPE; template<typename T> friend struct OTHER_SUB_TYPE; private: void private_function() {} }; int main() { MyStruct<> def; def.Get(); MyStruct<OTHER_SUB_TYPE> other; other.Get(); }
A solution is to declare a common base class Wrapper as a friend of MyStruct and the wrap the private function. Declare xxx_TYPE as a derived class of this common class Wrapper. template <typename T> struct Wrapper { void private_function(T* p) { p->private_function(); } protected: Wrapper() = default; }; template<typename MyStructType> struct OTHER_SUB_TYPE: Wrapper<MyStructType> { OTHER_SUB_TYPE(MyStructType* p) { this->private_function(p); } // Need to access other private members of MyStructType }; template<template<typename> class SUB_TYPE = DEFAULT_SUB_TYPE> struct MyStruct { SUB_TYPE<MyStruct> Get() { return SUB_TYPE{this}; } template<typename T> friend struct Wrapper; // Wrapper as a friend class private: void private_function() {} }; Demo
72,943,194
72,943,226
How can i fix this displayer image error in ImGui?
I have started to make a program with ImGui and opengl, besides stb for the images. When I show the default image of the demo it appears correctly. While if I load one using stb and link it with opengl and then display it, it looks like this. I do not know what it could be. Btw loading the same image as icon for the window works just fine. FUNCTION TO LOAD THE IMAGE: bool FeatherGUI::loadImage(std::string _path) { //Load texture from file CurrentImage.data = stbi_load(_path.c_str(), &CurrentImage.width, &CurrentImage.height, &CurrentImage.channels, 3); if (!CurrentImage.data) { fprintf(stderr, "Cannot load image '%s'\n", _path.c_str()); CurrentImage.loaded = true; return false; } // Create a OpenGL texture identifier and binding glGenTextures(1, &CurrentImage.texture); glBindTexture(GL_TEXTURE_2D, CurrentImage.texture); // Setup filtering parameters for display glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Upload pixels into texture #if defined(GL_UNPACK_ROW_LENGTH) && !defined(__EMSCRIPTEN__) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); #endif glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, CurrentImage.width, CurrentImage.height, 0, GL_RGB, GL_UNSIGNED_BYTE, CurrentImage.data); stbi_image_free(CurrentImage.data); CurrentImage.loaded = true; return true; } FUNCTION TO CREATE THE GUI: void FeatherGUI::BuildGUI() { using namespace ImGui; Begin("Imagen Displayer"); Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / GetIO().Framerate, GetIO().Framerate); if (!CurrentImage.loaded) { //load image if (!loadImage("B:/naranja.png")) { Text("Error loading image"); } } //Show CurrentImage data in ImGui if (CurrentImage.loaded) { Text("------------------------------------------------"); Text("Identifier = %p", CurrentImage.texture); Text("Size = %d x %d", CurrentImage.width, CurrentImage.height); Text("Channels: %d", CurrentImage.channels); } //Show CurrentImage in ImGui if (CurrentImage.data != NULL) { Image((void*)(intptr_t)CurrentImage.texture, ImVec2(CurrentImage.width, CurrentImage.height)); } End(); }
By default OpenGL assumes that the start of each row of an image is aligned to 4 bytes, because the GL_UNPACK_ALIGNMENT parameter by default is 4. Since the image has 3 color channels (GL_RGB), and is tightly packed the size of a row of the image is not aligned to 4 bytes, when 3*CurrentImage.width is not divisible by 4. Therefore GL_UNPACK_ALIGNMENT has to be set to 1, before specifying the texture image with glTexImage2D: glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, CurrentImage.width, CurrentImage.height, 0, GL_RGB, GL_UNSIGNED_BYTE, CurrentImage.data);
72,943,196
72,943,280
Determine at compile time if argument type is void
Please consider this simple example of a wrapper around a member function. I have updated this to be more complete code to aid in answering, as suggested. #include <cstring> #include <utility> using namespace std; template <typename FunctionWrapperType> struct THE_PROXY { THE_PROXY(FunctionWrapperType* wrapper) : wrapper_(wrapper) {} template<typename T> THE_PROXY& operator=(T val) { if constexpr (std::is_same_v<typename FunctionWrapperType::ARG_TYPE, void>) { void* address_to_write_to = wrapper_->Set(); memcpy(address_to_write_to, &val, sizeof(val)); } else { wrapper_->Set(val); } return *this; } private: FunctionWrapperType* wrapper_; }; template<typename Function, typename ContainingClass, typename ArgType> struct FunctionWrapper { FunctionWrapper(Function func, ContainingClass* c) : func_(func), containingClass_(c) {} using ARG_TYPE = ArgType; THE_PROXY<FunctionWrapper> operator*() { return THE_PROXY(this); } private: template<class T> friend struct THE_PROXY; template<typename Arg> void Set(Arg arg) { std::invoke(func_, containingClass_, arg); } void* Set() { return std::invoke(func_, containingClass_); } Function func_; ContainingClass* containingClass_; }; struct MyStruct2 { void* Func() { return &n_; } void Func2(int n) { n_ = n; } private: int n_; }; int main() { MyStruct2 ms; FunctionWrapper<decltype(&MyStruct2::Func), MyStruct2, void> fw(&MyStruct2::Func, &ms); FunctionWrapper<decltype(&MyStruct2::Func2), MyStruct2, int> fw2(&MyStruct2::Func2, &ms); *fw = 100; // This assignment will involve the memcpy update *fw2 = 65; // This is plain and simply member update } Now, admittedly this is a little weird. I am basically wrapping an API which has two ways of updating a member variable; where the updater function takes no argument, it requires the new value to be memcpyd over the returned address; otherwise, the updater function takes the new value to be written. I currently determine which version of Set() to call based on the template type ArgType which I pass through. If I don't use the constexpr in operator= I get compilation errors about error C2672: 'invoke': no matching overloaded function found ...which I think is because both branches of the if are being compiled and the call to Set() with no arguments expects an argument, so clearly I need to use template argument deduction. What I would like to know is if I can determine whether or not argument type for a function is void, then I don't need to pass it through as an argument manually. Note that there are some updater functions which return void* but also take an argument, so I cannot simply determine this behaviour based on the return type of void*. Does such a trick exist?
With specialization, you might do something like: template<typename MethodType> struct FunctionWrapper; // 1 arg template<typename Class, typename ArgType> struct FunctionWrapper<void (Class::*)(ArgType /*, ...*/) /* const volatile noexcept & && */> { using Function = void (Class::*)(ArgType); FunctionWrapper(Function func) : func_(func) {} Function func_; }; // No args template<typename Class> struct FunctionWrapper<void (Class::*)(/*...*/) /* const volatile noexcept & && */> { using Function = void (Class::*)(); FunctionWrapper(Function func) : func_(func) {} Function func_; // special stuff. }; In your case, you might check if method is invocable, and get rid of your extra template parameter: template <typename FunctionWrapperType> struct THE_PROXY { THE_PROXY(FunctionWrapperType* wrapper) : wrapper_(wrapper) {} template<typename T> THE_PROXY& operator=(T val) { wrapper_->Set(val); return *this; } private: FunctionWrapperType* wrapper_; }; template<typename Function, typename ContainingClass> struct FunctionWrapper { FunctionWrapper(Function func, ContainingClass* c) : func_(func), containingClass_(c) {} THE_PROXY<FunctionWrapper> operator*() { return THE_PROXY(this); } private: template<class T> friend struct THE_PROXY; template<typename Arg> void Set(Arg arg) { if constexpr (std::is_invocable_v<Function, ContainingClass, Arg>) { std::invoke(func_, containingClass_, arg); } else { void* address_to_write_to = std::invoke(func_, containingClass_); memcpy(address_to_write_to, &arg, sizeof(Arg)); } } Function func_; ContainingClass* containingClass_; }; Demo
72,943,472
72,943,521
Function returning the wrong kth value while using sets
I was attempting to solve this question on some website where you have the find the kth smallest value in c++ so I came up with: #include <bits/stdc++.h> using namespace std; int kthSmallest(int arr[], int l, int r, int k) { // l is the first index // r is the index of the last element (size - 1) // k is the kth smallest value set<int> s(arr, arr + r); set<int>:: iterator itr = s.begin(); advance(itr, (k - 1)); return *itr; } int main() { int arr[] = {7, 10, 4, 20, 15}; cout << kthSmallest(arr, 0, 4, 4); return 0; } This shows the output of 20 instead of 15 which is the right answer and I cannot figure out what I did wrong here.
The 2nd argument of the constructor of std::set should be an iterator for an element next to the last element, not one for the last element. Therefore, you are operating with a set whose members are {7, 10, 4, 20}. The line set<int> s(arr, arr + r); should be set<int> s(arr, arr + r + 1); or (to match the comment) set<int> s(arr + l, arr + r + 1);
72,943,719
72,945,780
C++ 20 dependent template in a concept
I would be really grateful if somebody could explain why the below code does not compile due to 'associated constraints are not satisfied' / 'no matching overloaded function found' (MSVC 2022, 17.2.1). The Listener concept below requires a template input param of an Update < V > where V matches the template param V of MySignal. If I change the parameter of the listen(...) to take a Func it compiles - but my assumption is that the concept / lambda approach must resolve to exactly the same type - so why is the constraint not satisfied? EDIT: So I made a rather silly copy and paste error on my initial code snippet (now corrected) that confused matters. My question could also have been worded better - the crux of what I am failing to understand is why it seems I can define a concept with a templated param in my requires clause (ie Update<V>) but the compiler subsequently rejects the below code as not satisfying constraints. template <typename V> struct Update { V val; }; template <typename T, typename V> concept Listener = requires(T t, Update<V> update) { { t(update) } -> std::convertible_to<void>; }; template <typename V> struct MySignal { using UpdateV = Update<V>; using Func = std::function<void(UpdateV)>; void listen(Listener<UpdateV> auto&& listener) { listeners_.emplace_back(Func{ listener }); } std::vector<Func> listeners_; }; int main(int argc, char** argv) { MySignal<int64_t> sig; sig.listen([](Update<int64_t> u) { std::cout << "Got a signal"; }); }
Listener<UpdateV> - this is your issue I think. In the concept you already check Update<V> and now you pass UpdateV as the parameter V. So your concept ends up checking for an operator()(Update<Update<V>>).
72,943,770
72,949,093
Unable to properly render a triangle in SDL2 (MAC M1)
I'm trying to render a triangle using SDL2 on my MAC (M1), however, the triangle i'm able to generate is too much pixellated and unnecessary pixels are being rendered. Output: My Code: int main(int argc, char *argv[]) { // returns zero on success else non-zero if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { printf("error initializing SDL: %s\n", SDL_GetError()); } SDL_Window* win = SDL_CreateWindow("GAME", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 900, 900, SDL_WINDOW_ALLOW_HIGHDPI); if(!win) { std::cout << "Failed to create window\n"; return -1; } int *w_t = new int (); int *h_t = new int (); SDL_GetWindowSize(win,w_t,h_t); std::cout<<"width:"<<*w_t<<"height:"<<*h_t; SDL_Renderer* brush = SDL_CreateRenderer(win, -1, 0); SDL_SetRenderDrawColor(brush, 255, 0, 0, 0); SDL_Point a = {0,500}; SDL_Point b = {800,500}; SDL_Point c = {250,250}; bool quit = false; SDL_Event e; while (!quit) { while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { quit = true; } } SDL_RenderDrawLine(brush, a.x, a.y, b.x, b.y); SDL_RenderDrawLine(brush, a.x, a.y, c.x, c.y); SDL_RenderDrawLine(brush, b.x, b.y, c.x, c.y); SDL_RenderPresent(brush); } return 0; } OS: macOS Monterey IDE: Xcode Compiler: Clang
Try clearing the renderer before drawing the lines: SDL_SetRenderDrawColor(brush, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(brush); SDL_SetRenderDrawColor(brush, 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(brush, a.x, a.y, b.x, b.y); SDL_RenderDrawLine(brush, a.x, a.y, c.x, c.y); SDL_RenderDrawLine(brush, b.x, b.y, c.x, c.y); SDL_RenderPresent(brush);
72,943,913
73,055,888
Issues with libgcc_s_dw2-1.dll and libstdc++-6.dll on build
I know that these are required to compile a C++ app but what I don't know is how do I build my app so that other users won't need them. I tried to use -static flags to build but it still won't work when I remove mingw\bin\ and msys2\usr\bin\ from my path or when my friends who don't have a C++ compiler try to run it. For the record, I did include every library for the project when I asked for friends to run it. Here's my Makefile : rtx.exe: base.o objects.o rtx.o g++ -O3 base.o objects.o rtx.o -o rtx -pthread -Lsrc\lib -lsfml-graphics -lsfml-window -lsfml-system -ljsoncpp -static -static-libgcc -static-libstdc++ rtx.o: rtx.cpp g++ -Isrc\include -O3 -c rtx.cpp -static -static-libgcc -static-libstdc++ objects.o: objects.cpp objects.hpp g++ -Isrc\include -O3 -c objects.cpp -static -static-libgcc -static-libstdc++ base.o: base.cpp base.hpp g++ -Isrc\include -O3 -c base.cpp -static -static-libgcc -static-libstdc++ clean: -rm *.o $(objects) rtx.exe And here's one of the pop-op I (and my friends withour a C++ compiler) get : There are 4 pop-ups, 2 of them being this one and the other says the same thing for libstdc++-6.dll. I tried a bunch of things, including compiling objects.o and base.o into a library using the ar ru command but it gives the same pop-ups. My guess is that one of the libraries I'm using, either jsonCpp or SFML is not built statically, but I couldn't find anything about how to fix it.
So, as advised by HolyBlackCat, I fully reinstalled MSYS2 and downloaded SFML and jsonCpp with mingw and after a bit of research and trial and error I ended up with this makeFile : rtx.exe: base.o objects.o rtx.o g++ -O3 base.o objects.o rtx.o -o rtx -pthread -lsfml-graphics-s -lsfml-window-s -lsfml-system-s -lopengl32 -lwinmm -lgdi32 -ljsoncpp -static rtx.o: rtx.cpp g++ -Isrc\include -O3 -c rtx.cpp -DSFML_STATIC -static objects.o: objects.cpp objects.hpp g++ -Isrc\include -O3 -c objects.cpp -DSFML_STATIC -static base.o: base.cpp base.hpp g++ -Isrc\include -O3 -c base.cpp -DSFML_STATIC -static clean: -rm *.o $(objects) rtx.exe And now, it does make a static build.
72,944,176
72,944,658
How to convert cv::Mat to torch::Tensor and feed it to libtorch model?
I read image with cv2.imread() and trying to feed it to torch model in c++. It has datatype cv::Mat. I think i need to convert it to tensor somehow and then use model.forward(), but i am confused how to do it. Is there some function similar to .Tensor() in python?
The function torch::from_blob can be used to create a tensor view over the image data, like this: torch::Tensor to_tensor(cv::Mat img) { return torch::from_blob(img.data, { img.rows, img.cols, 3 }, torch::kUInt8); }
72,944,329
72,944,613
Print multiple COUT using looop
I am making a program to calculate taxes and tips based on the meal price. Is there anyway for me to loop the cout and print different percentages for each cout for 5 times? This is the code I wrote but I am stuck, I can write 5 cout but I need to use looping so I think there must be a way to print with cout until it stops. #include <iostream> using namespace std; int main( ) { //Declare variables int counter = 0; const double taxrate = 0.0625; double meal = 0.00; double tax = 0.00; double tips = 0.00; double total = 0.00; double tip_percentage = 0.00; //Prompt the user for number of tests cout << "Enter total meal price: "; cin >> meal; //Loop for (double tips_percentage = 0.05; tips_percentage < 0.26; tips_percentage +=0.05) { tax = meal * taxrate; tips = tip_percentage * meal; total = tips + tax + meal; cout <<"Your tax is $"<< tax << "and.." <<endl; cout << "a" << tip_percentage * 100<<"% tip is"<< tips << "giving a total of" << total <<endl; } system("pause"); return 0; } //end of main taxrate is constant 6.25% and the output is something like this. a 5% tip is $... your total is $... a 10% tip is $... your total is $... a 15% tip is $... your total is $... a 20% tip is $... your total is $... a 25% tip is $... your total is $... instead writing 5 cout, can I do a loop and print it 5 times? For example, if the meal is $100, it will calculate the tax price which is 6.25% and then show the tips %. After that it will add everything together. So, 6.25% of $100 is $6.25 and 5% of the tip is $5. The total would be $111.25. The taxrate is constant so it will always be 6.25%.
As I suggested in the comment, I think that the point breaking your loop is the fact that you change tips inside the loop itself and, in yuour example, in the first cycle you start with a tip of 0.05, then multiply it by 100, and at the next iteration you do not even enter because you do not comply with the condition tips < 0.26. I think it would be a good idea to keep separed the percentage from the tip itself. Somehting like this: #include <iostream> using namespace std; int main( ) { //Declare variables int counter = 0; const double taxrate = 0.0625; double meal = 0.00; double tax = 0.00; double tips = 0.00; double total = 0.00; // You do not need this, you can declare it in the loop. //double tip_frac = 0.0; //Prompt the user for number of tests cout << "Enter total meal price: "; cin >> meal; //Loop // Tax is fixed, can be calculated outisde the loop. tax = meal * taxrate; cout <<"Your tax is $ "<< tax << " and.." <<endl; for (double tip_frac = 0.05; tip_frac < 0.26; tip_frac +=0.05) { tips = meal * tip_frac; total = tips + tax + meal; // Just a small reshuffle of pieces to get the output you seek. // Always remember spaces to get a nice output. // Factor 100 is to pass from fraction to percentage. cout << "a " << tip_frac * 100 <<"% tip is $"<< tips << " giving a total of " << total <<endl; } //system("pause"); // What do you want to do with this pause? return 0; } //end of main you should always pay attention when you change the variable you are looping on, it's dangerous. There are some other suggestions that might be given, like Why is "using namespace std;" considered bad practice?, but I think it is important for you to get the main part of this issue.
72,944,361
72,944,434
Getting segmentation fault (core dump) for binary search(recursive) to find a number in an array
This is a problem to find the target number in an array using the binary search recursive method. Getting segmentation fault. Have tried a lot but cannot find what is causing it. need some help to avoid such mistakes. which part is wrong in my code?? I have pasted the complete code. #include<iostream> #include<vector> #include<algorithm> using namespace std ; int recursivebinarysearch(vector <int>& arr ,int target , int ans ){ int high = arr.size() - 1 ; int low = 0 ; int mid = (high + low) / 2 ; for(int i = 0 ; i < arr.size() ; i++){ mid = (low+high)/2 ; if(low > high){ mid = -1; return mid; } if(target > arr[mid]){ low = mid +1 ; recursivebinarysearch(arr , target , ans ); } else if(target < arr[mid]){ high = mid -1; recursivebinarysearch(arr , target , ans ); } else{ mid = ans ; return ans ; } } } int main(){ int n, target , ans = 0; cin >> n ; vector<int> arr ; int j = 0; for(int j = 0 ; j < n ; j++){ cin >> arr[j]; } cin >> target ; sort(arr.begin() , arr.end()); ans = recursivebinarysearch(arr, target , ans); cout<<ans<<endl; return 0; }
high, low, mid are local to your function. So, each time you call recursivebinarysearch with the same vector arr, you get the same values. So, you infinitely recurse. The segmentation fault happens when the stack overflows. If you want to keep this approach, you need to pass high and mid to the function and have it search this range only. Alternatively, you can have a single while and adjust local values high, low as you go. This would be better, but some professors out there want to see explicit recursion. Also, thanks to the comments, cin >> arr[j]; doesn't work. Either: int value; cin >> value; arr.push_back(value); or arr.resize(j+1); cin >> arr[j];
72,944,373
72,944,716
gdb : Adding a breakpoint and rerun using existing coredump
my task crashed on production server, and I downloaded the binary and the core dump. I then run : gdb task coredump And I can do some basic debugging in gdb including bt, frame, info locals etc. I have identified a variable that it's content look weird to me. Assuming I am in here : (gdb) frame 8 .... (gdb) list ... (gdb) print d_variable .... I now want to go a few lines up, and inspect d_variable and how it got populated or at what point the value isn't correct. I can add a break point and run my task, but this as far as I can tell, it doesn't use the existing coredump and I cannot reproduce the error. The question is, can I run the same coredump, with breakpoints this time so I can inspect how this "abnormal" value occurred? I am not very experienced with gdb so hope the above makes sense.
can I run the same coredump, with breakpoints this time so I can inspect how this "abnormal" value occurred? No. In order to achieve what you want, you need need to record the crash under a reversible debugger, such as rr. Since you haven't done so, your only option is to guess where the variable became corrupt, add logging and hope that the future crash will provide more info. Before doing that, I suggest: instrumenting all your unit tests (you do have unit tests, right?) with -fsanitize=address (assuming your platform is supported) and making sure they are AddressSanitizer-clean. instrumenting the actual server with AddressSanitizer and running it though load-test. There is a high chance that doing above steps will reveal one or more bugs.
72,944,612
72,944,677
'NumberOfCharsWritten' could be '0': this does not adhere to the specification for the function 'WriteConsoleOutputCharacterW' 22
Im trying to write a console screen buffer, but i keep getting different errors pointing at the LPDWORD variable no matter what values i assign to it #include<iostream> #include<Windows.h> using namespace std; int main() { COORD cell{0, 0}; LPDWORD NumberOfCharsWritten = 0; wchar_t* screen = new wchar_t[80 * 30]; HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ, FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL); SetConsoleActiveScreenBuffer(hConsole); DWORD dwBytesWriten = 0; while (true) { screen[10 * 80 + 15] = L'P'; WriteConsoleOutputCharacter(hConsole, screen, 80 * 30, cell, NumberOfCharsWritten); } }
You are passing a NULL pointer to WriteConsoleOutputCharacter(), but the pointer needs to point to an actual DWORD instead. Declare a DWORD variable and use the & operator to get a pointer to that DWORD: DWORD NumberOfCharsWritten = 0; ... WriteConsoleOutputCharacter(..., &NumberOfCharsWritten);
72,944,798
72,945,066
reassignment/move of std::future waits for existing future to complete
The main method below launches two std::asyncs. The future f in the main method is initially used to hold the future for the first async before being reassigned to the future of the second std::async. Both threads still appear to still complete on schedule which surprised me. Initially I (foolishly?) expected the first thread to be terminated/suspended on the reassignment of the future but was surprised to find it still lingering around. Based on what I observed today I think I understand that the first async thread becomes detached at the future reassignment. I kept seeing segfaults during my ordeal today and I reckon this was simply the main thread terminating before the orphaned async processes could finish. //////////////////////////////////////////////////////////////////////////// #include <iostream> #include <future> #include <thread> #include <chrono> #define WAIT_A_MINUTE std::this_thread::sleep_for(std::chrono::seconds(5)); int myBusyFunc() { WAIT_A_MINUTE std::cout<<"done!"<<std::endl; return 71675; } std::string futureStatusStr(std::future<int>& f){ switch (f.wait_for(std::chrono::seconds(0))){ case std::future_status::ready: return "ready"; case std::future_status::timeout: return "timeout"; case std::future_status::deferred: return "deferred"; default:return "unknown"; }; } void printFutureStatus(std::future<int>& f){ std::cout<<futureStatusStr(f)<<std::endl; } ///////////////////////////////////////////////////////////////////////////// int main() { std::future<int> f = std::async(std::launch::async,myBusyFunc); printFutureStatus(f); f = std::async(std::launch::async,myBusyFunc); // waits a minute printFutureStatus(f); f.wait(); // no wait required - ready printFutureStatus(f); return 0; } Additionally, it is noteworthy that the second printFutureStatus(f); statement immediately after the future reassignment doesn't flush immediately. It does appear that the future reassignment causes the main thread to wait. This still surprises me - could anyone offer an explanation?
This behavior is actually documented in std::future::~future. Excerpt from the documentation below: these actions will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state. In practice, these actions will block only if the task’s launch policy is std::launch::async (see "Effective Modern C++" Item 36), either because that was chosen by the runtime system or because it was specified in the call to std::async. So, you can see that this result is not unexpected. When you reassign f, the old object is destroyed and in that process the caller becomes blocked. Taking the above into consideration, if you need to replace the future without blocking, you have a few options: Use deferred execution policy (std::launch::deferred) Store the shared state before replacing: auto g = f.share(); If you want to discard or "abort" the old async call, introduce a mechanism to signal it for early-out.
72,945,222
72,946,371
Compiling Makefile in Windows runs into "collect2: fatal" error
I am trying to remake the run and infer binaries from this open source repository in GitHub: files here. The Makefile is the one creating the run and infer files. I am currently on Windows 11, with msys2. I have: make-4.3.3 installed gcc-11.3.0, and also installed. and binutils-2.37-5 installed Currently, when I run make (when standing in the src directory) with msys2, I get the following error: $ make g++ obtm.o ibtm.o main.o -o run collect2: fatal error: ld terminated with signal 11 [Segmentation fault], core dumped compilation terminated. make: *** [Makefile:9: run] Error 1 If you check Makefile:L9, that line has the following (copyng lines8-9 below): run:obtm.o ibtm.o main.o $(CC) $^ -o $@ Running the make gives me a 0KB "run.exe" file, and a ld.exe.stackdump file. I am copying the content of the latter below: Exception: STATUS_ACCESS_VIOLATION at rip=0010042CA94 rax=0000000000000000 rbx=0000000100597700 rcx=0000000100597700 rdx=0000000800094010 rsi=0000000800870140 rdi=00000008008D5640 r8 =000000080087013A r9 =0000000000000002 r10=FEFEFEFEFEFEFEFF r11=000000010042C9DF r12=0000000000000000 r13=000000010054170C r14=0000000800094010 r15=00000000FFFFC698 rbp=0000000100514E80 rsp=00000000FFFFC570 program=C:\msys64\usr\x86_64-pc-msys\bin\ld.exe, pid 2480, thread main cs=0033 ds=002B es=002B fs=0053 gs=002B ss=002B Stack trace: Frame Function Args 00100514E80 0010042CA94 (008008D2000, 008000F9CC8, 008008700F0, 00000000000) 00000000000 00100423245 (008000F9CC8, 008000937B0, 008000DC968, 00100597700) 00800870140 0010042BAD2 (00800086220, 008000C00F8, 0010045202F, 00000000001) 0080087013A 0010042BE7A (000FFFFC890, 00800084718, 001005374E0, 00180374818) 001005981A4 001004240D7 (0010052B6E2, 008000007D0, 0010044AFF9, 00430B3954B) 00800078138 00100413CA8 (00430B39600, 00180234000, 001802B5BF3, 001802B5BED) 0010052B6E2 00100512BEC (000FFFFCAA0, 00000000000, 00000000000, 00180156FA8) 000FFFFCD30 00180049B91 (00000000000, 00000000000, 00000000000, 00000000000) 000FFFFFFF0 00180047716 (00000000000, 00000000000, 00000000000, 00000000000) 000FFFFFFF0 001800477C4 (00000000000, 00000000000, 00000000000, 00000000000) End of stack trace I did try to check similar topics (like this collect2: fatal error: ld terminated with signal 11 [Segmentation fault] and compiler gives error ld terminated with signal 11 to no avail).
Just in case someone else is in the same debacle--the folders have some *.o files. I just had to delete those, alongside the older run and infer, simply run make while standing in that folder, and it worked!
72,945,477
72,952,886
Mapping a texture in OpenGL
I am trying to map a texture to a simple quad for the first time, but all it won't render. I am using freeglut for the implementation, and the stb_image.h header to load the texture. The code: #include <GL/glut.h> #include <stb_image.h> #include <iostream> int ww = 500, wh = 500; void display() { glClearColor(1.0, 1.0, 0.7, 1.0); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_QUADS); glEnable(GL_TEXTURE_2D); glTexCoord2f(0.0, 0.0); glVertex3f(10,10,0); glTexCoord2f(0.0, 1.0); glVertex3f(10,wh-10,0); glTexCoord2f(1.0, 1.0); glVertex3f(ww-10,wh,0); glTexCoord2f(1.0, 0.0); glVertex3f(ww-10,10,0); glDisable(GL_TEXTURE_2D); glEnd(); glFlush(); } void myinit() { glViewport(0, 0, ww, wh); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (GLdouble)ww, 0.0, (GLdouble)wh); glMatrixMode(GL_MODELVIEW); unsigned int texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int width, height, nrChannels; unsigned char* data = stbi_load("container.jpg", &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowSize(ww, wh); glutCreateWindow("texture-try"); glutDisplayFunc(display); myinit(); glutMainLoop(); return 0; } It successfully loads the texture, but the quad appears just white. What am I missing? Edit: I moved the glBegin(GL_QUADS); and glEnd(); inside the glEnable(GL_TEXTURE_2D); and glDisable(GL_TEXTURE_2D); commands as was suggested, but it still won't render the texture. I also checked the glGetError command, but it returns GL_NO_ERROR.
Several things: The aforementioned "don't use prohibited functions within a glBegin()/glEnd() pair" issue; as of posting this hasn't been fixed in the question code. GL_LINEAR_MIPMAP_LINEAR is being used without providing any mipmaps. Drop to GL_LINEAR or provide some mipmaps. Pass 3 to stbi_load()'s desired_channels parameter (instead of the current 0) to guarantee you get 3-channel image data instead of just assuming nrChannels is 3 for all input images. Using GL_RGB with the default GL_UNPACK_ALIGNMENT of 4 can result in wonky display if your image width isn't a nice multiple of 4 so drop that down to 1 via glPixelStorei(GL_UNPACK_ALIGNMENT, 1) before calling glTexImage2D(). Switch to GLUT_DOUBLE & glutSwapBuffers() instead of using GLUT_SINGLE and glFlush(). All together: #include <GL/glut.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <iostream> int ww = 500, wh = 500; void display() { glClearColor(1.0, 1.0, 0.7, 1.0); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(10,10,0); glTexCoord2f(0.0, 1.0); glVertex3f(10,wh-10,0); glTexCoord2f(1.0, 1.0); glVertex3f(ww-10,wh,0); glTexCoord2f(1.0, 0.0); glVertex3f(ww-10,10,0); glEnd(); glDisable(GL_TEXTURE_2D); glutSwapBuffers(); } void myinit() { glViewport(0, 0, ww, wh); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, (GLdouble)ww, 0.0, (GLdouble)wh); glMatrixMode(GL_MODELVIEW); unsigned int texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int width, height, nrChannels; // https://commons.wikimedia.org/wiki/File:Container.JPG unsigned char* data = stbi_load("container.jpg", &width, &height, &nrChannels, 3); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutInitWindowSize(ww, wh); glutCreateWindow("texture-try"); glutDisplayFunc(display); myinit(); glutMainLoop(); return 0; }
72,946,790
72,946,982
Why is the hash function O(1)
Why does finding the hash of a given string only run in constant time? I am trying to write an optimized program to compare two strings by using string hashing. From what I know, the hash of a string is usually defined by a polynomial rolling hash function. Online sources say calculating this hash and doing the comparison is O(1). For example, https://cp-algorithms.com/string/string-hashing.html says that The idea behind the string hashing is the following: we map each string into an integer and compare those instead of the strings. Doing this allows us to reduce the execution time of the string comparison to O(1). However, the actual implementation (according to https://cp-algorithms.com/string/string-hashing.html) of this hash function includes looping through the entire string: long long compute_hash(string const& s) { const int p = 31; const int m = 1e9 + 9; long long hash_value = 0; long long p_pow = 1; for (char c : s) { hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } Wouldn't this guarantee linear time complexity to compare two strings, instead of O(1)? Any help is appreciated!
Big-O notation is a way of describing how the execution time of an algorithm will grow with the size of the data-set it is working on. In order for that definition to be applied, we have to specify what the data-set is that will be growing. In most cases that's obvious, but sometimes it's a bit ambiguous, and this is one of those cases. Does "data set" in this case refer to an individual string? If so, then the algorithm is O(N), since the sequence of operations it has to perform grows linearly with the size of the string. But if by "data set" you mean the number of items in the associated hash table, then the algorithm can be considered O(1), since it will operate just as quickly (for any given string) when dealing with a million-entry Hashtable as it would for a two-entry Hashtable. Regarding using hashing to compare two strings: once you have computed the hash values for the two strings, and stored those hash values somewhere, you can compare the two hash values in O(1) time (since comparing two integers is a fixed-cost operation, regardless of the sizes of the strings they were calculated from). It's important to note, however, that this comparison can only tell you if the two strings are different -- if the two hash values are equal, you still can't be 100% certain that the two strings are equal, since (due to the pigeonhole principle) two different strings can hash to the same value. So in that case you'd still need to compare the strings the regular O(N)/char-by-char way.
72,946,813
73,368,811
Why does the function 'CGAL::draw' draw a black triangle instead of a polygon in the latest version of CGAL?
I've upgraded my CGAL installation to the latest version (5.4.1) and I can't use the function CGAL::draw anymore - it draws a black triangle instead of everything I need. It's not a problem in my code - even standard examples from the CGAL distribution behave this way. The script below unpacks the CGAL tar-file, then builds and runs the draw_polygon example from this tar-file. #!/bin/bash VERSION=CGAL-5.4.1 tar xJvf ${VERSION}.tar.xz && cd ${VERSION} mkdir -p build && cd build cmake -DCMAKE_BUILD_TYPE=Release -DWITH_examples=ON .. make cd examples/Polygon make draw_polygon ./draw_polygon& The result is below: If to set the VERSION variable in the script above to the value CGAL-5.2.4 - then the drawing will be correct. What's the problem here? OS: Ubuntu 20.04.4 LTS Compiler: g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 UPDATE. I've opened an issue on the CGAL bug tracker.
I'm answering my own question. The issue here is that starting from the version 5.3 the CGAL library Qt5-based visualization subsystem doesn't support old graphics hardware - at least on Linux machines (no idea about Windows or Mac worlds). It looks like the OpenGL implementation on Linux (called Mesa) checks the graphics hardware in run time and creates graphics context, corresponding to this hardware. So, for the CGAL visualization to work correctly this context must be at least OpenGL 3.2, and corresponding shading language must be at least GLSL 1.50. For more information about these versions etc. please see here.
72,947,048
72,949,314
QFileSystemWatcher not sending fileChanged() SIGNAL
I apologize in advance am very new to QT (and fairly new to C++) I am trying setup a program that will execute a function anytime a specific file is changed. Despite hours on google and reading the docs provided on QT I cant find a way to get myfunction() to execute when SSOpen_Log is edited currently my code looks something like this (SOpen_Log is a QString declared in .h): MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QFileSystemWatcher watcher; watcher.addPath(SOpen_Log); MainWindow::connect(&watcher, SIGNAL(fileChanged(QString)), this, SLOT(myfunction())); } MainWindow::myfunction() { //mycode executes here }
You allocated your instance on the stack and it thus get destructed when the constructor ends. I would suggest that you make a class member for the instance so that it remains valid throughout the class. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); m_watcher.addPath(SOpen_Log); MainWindow::connect(&m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(myfunction())); } There is no need to complicate this by putting it on the heap, effectively using a pointer, although that is also an option to consider. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QFileSystemWatcher *watcher = new QFileSystemWatcher(this); watcher->addPath(SOpen_Log); MainWindow::connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT(myfunction())); } While we are at it, I would also like to mention to use the new signal-slot syntax style rather than the old. The old one is checked at runtime and the new one is checked at compilation time. So, you catch any issues with it during compilation rather than at runtime.
72,947,052
72,964,557
how can I receive all message by libevent
Currently, I use libevent to send and receive messages. The issue I am currently encountering is that I do not receive all messages on the server; and only receive the first message I sent. Client Code: for (int i=0; i < 10 ; i++) { bufferevent_write(bev, data, strlen(data) + 1); } Server Code: static void read_cb(struct bufferevent* bev, void* arg) { char buf[2048] = {}; bufferevent_read(bev, buf, sizeof(buf)); //do something } I have modified the client like this: for (int i=0; i < 10 ; i++) { bufferevent_write(bev, data, strlen(data) + 1); sleep(1) } When I add a sleep(1),I can receive all messages. I would like to avoid using sleep(1). What needs to be added / changed in code, such that all messages can be received, and sleep is not used.
This situation seems to be a bit like a spacket splicing problem, you can try this static void read_cb(struct bufferevent* bev, void* arg) { char bufs[2048]; struct evbuffer *input = bufferevent_get_input(bev); size_t lens = evbuffer_get_length(input); char * rline = bufs; while( lens > 0){ char buf [1024] memcpy(buf, rline, strlen(data)); rline = rline + strlen(data); lens = lens -strlen(data); // use buf do something else } }
72,947,518
72,947,620
How do I check whether an index of array is empty and then, if it is, skip to the next?
I'm trying to build a program that can register a user to the database (still learning cpp, I hope that in the near future I'll be able to work with database). What I'm trying to do with this code is to check whether an index of array is empty for the user to store an ID in it. If it isn't empty, I want the program to keep looking for an empty index of array, for the new info to be stored in. Here is the code: void registro() { std::string userid[3]; userid[0] = "Houkros"; // eventually I'll try to have this being read from a file or server database.. std::string userpass[3]; std::string usermail[3]; std::string userkey[3]; std::string getUid[3]; std::string getUpass[3]; std::string getUmail[3]; std::string getUkey[3]; std::cout << std::endl << " >>>> REGISTRATION <<<< " << std::endl; std::cout << " =============================================== " << std::endl; std::cout << std::endl; std::cout << "Please, enter the desired user id: " << std::flush; if (userid[0].empty()) { std::cin >> userid[0]; } else { std::cin >> userid[1]; } for (int i = 0; i < 2; i++) { std::cout << " Element of array: " << i << " is > " << userid[i] << std::endl; }
Please consider the following definitions for an "empty" array element: a) not initialised (unhelpful, cannot be checked) b) never yet written to (same as a) ) c) contains "" (possible, but means that "" must not be accepted as an actual content) d) is empty according to a second array in which that info is maintained (this is what I almost recommend) e) contains a struct with a string and a maintained "empty" flag (this I recommend) Whatever you do, make sure that you init all variables and array elements before first read-accessing them; i.e. in all cases first write something meaningful to it.
72,948,090
72,948,176
How avoid code duplication in visitor and const visitor base classes
I have 2 classes ConstVisitorBase and VisitorBase which contain some code to visit objects. for example: struct Node { enum class Type { ... }; Type type; } class ConstVisitorBase { public: virtual void VisitType1( Node const & node ); ... private: void VisitNode( Node const & node ) { switch( node.type ) { case Node::Type::type1: VisitType1( node ); } ... } } class VisitorBase { public: virtual void VisitType1( Node & node ); ... private: void VisitNode( Node & node ) { switch( node.type ) { case Node::Type::type1: VisitType1( node ); } ... } } The code for the private method VisitNode is identical other than the const specifier. Is there a way to avoid this duplication? Even when there are multiple methods involved ( VisitNode calling EnterNode and LeaveNode )?
Since VisitType1 are public and the two classes are unrelated, you can use a template function: template<typename Visitor, typename T> void dispatch_visits(Visitor& visitor, T&& node){ switch( node.type ) { case Node::Type::type1: visitor.VisitType1( node ); } ... }
72,949,147
72,949,529
C++ possible to call function with same name in different class with single pointer?
Is it possible to call run() with p without concerning different class they are(for example class cast on a void*) and different implementation of run() in each class? class A { void func() { //new B //new C //new D //*p points to the instance of one of B,C,D p->run(i); } // some pointer *p } class B { void run(int i); } class C: public B { void run(int i); } class D: public B { void run(int i); }
This works: #include <iostream> class B { public: virtual int run(int i); }; class A { public: int func(B* obj, int i) { return obj->run(i); } }; class C: public B { public: virtual int run(int i){ return 2*i;} }; class D: public B { public: virtual int run(int i){ return 3*i;} }; int main(){ A a; C obj1; D obj2; B* ptr1 = &obj1; B* ptr2 = &obj2; std::cout << a.func(ptr1, 3) << "\n"; std::cout << a.func(ptr2, 3) << "\n"; }
72,949,300
72,949,373
how are these functions called if I didn't call them?
I'm new to QT. How are these functions automatically called if I didn't call them? Maybe somewhere inside the parent class there are connections that somehow connect them and launch them? I know there will be a default constructor here, but how are these functions called, if the default constructor is empty class CustomItem : public QGraphicsItem{ public: QRectF boundingRect() const override{ return QRectF(0, 0, 80, 80); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override{ Q_UNUSED(option); Q_UNUSED(widget); painter->fillRect(boundingRect(),Qt::red); } }item;
Public methods can be called by anyone who has a pointer or reference to objects of your class. Presumably objects of this type are added to a QGraphicsScene, which among other things will call boundingRect to determine how much space your CustomItem occupies, and paint when it needs to draw the part of the scene with that item.