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
66,417,878
66,417,908
How can I introduce base class member to derived class definition, but only one overload?
With 'using declarations' I can introduce a base class member into definition of my class: class Base { public: void baseMemberFn(); /* ... */ }; class Derived : private Base { public: using Base::baseMemberFn; }; However, in my case, I want to only 'use' one specific overload of the member from t...
There's no syntax for that. Make a new member function with the same name, that forwards the call to the parent: void baseMemberFn() {Base::baseMemberFn();}
66,417,895
66,475,264
format function declaration Clang-format
I want to format my code like this : all parenthesis MUST BE align (cause of my company coding rules :)) bool Start (void); void Stop (void); void Run (void); all I have seen format it like this : bool Start(void); void Stop(void); void Run(void); all function ...
so, to align all parenthesis I have download code alignment in VScode and I applied alignment by ( in all function declaration.
66,417,946
66,419,205
How to import package in cmake from vcpkg?
When I vcpkg install simdjson , it returns : The package simdjson:x64-linux provides CMake targets: find_package(simdjson CONFIG REQUIRED) target_link_libraries(main PRIVATE simdjson::simdjson simdjson::simdjson-flags simdjson::simdjson-headers) So I add find_package(simdjson CONFIG REQUIRED) target_l...
Unfortunately, redis-plus-plus doesn't supply CMake config files. Someone should open an issue with upstream. It's honestly pretty unacceptable to not support find_package for your library. Thus, thanks to the authors' negligence, you will have to create an imported target for their library yourself. Here's an example ...
66,418,054
66,418,599
Qt C++11 Handing out raw pointer from QList
I am working on a problem where I have some sort of custom made "container" DTO which contains a series of items. The user of the class should be able to retrieve an item at a position from the container. I wanted the container to not keep a refrence of raw pointers to the items it contains, but really own them so no c...
Returning a pointer to a memory address inside the QList storage is ill-advised. From the QList documentation "be aware that any non-const function call performed on the QList will render all existing iterators undefined". If the inner container stored actual pointers then that would not be a problem. These could even ...
66,418,315
66,418,360
Counting the sum of prime number
I am trying to count the sum of how many times I found the prime number b/w 1-100. So say I am running the iteration 100 times and between those iterations whenever I find a prime number, I go ahead and print it. But how do I add that how many total prime numbers have I found? Any help would be appreciated. bool isPri...
You can keep a counter and increment in the loop if it is prime, like this. bool isPrimeNumber(int number){ bool isPrimeFlag; for(int i =2; i<number; i++){ //bcze its divisible and gets you 0 as a remainder //we set the flag as false if(number % i==0){ //is...
66,418,449
66,418,524
how to return value from while loop in c++?
I have changed the scenario of the originally code. Generally, given that there is a rate of the factory producing certain number of sweets per day. For example, rate is 0.5. And if at first (day 0) the factory produce 1000 sweets. After day 1, the factory should be produced 1000*(1+0.5)=1500 sweets. And after day 2, t...
You do not assign the result of your function to anything, so the value is lost.
66,418,746
66,457,329
Meson build system - change compiler to g++
Here is my meson.build project('lab1', 'cpp', version: '0.1.5') executable('lab1', 'main.cpp', 'Graph.cpp', 'Matrix.cpp', 'menuUtils.cpp', cpp_args : '-Wall' ) The problem is: Sanity check compile stderr: c++: error: D:\Programming\?++ progr...
First of all, to change the compiler to the g++ I have added a new environment variable CXX with the value g++. On Windows OS, just search Edit the system environment variables and than click on Environment Variables. Then set the CXX to the appropriate value. Now the CXX is set. My problem was: Sanity check compile ...
66,418,776
66,418,935
Displaying rounded off values instead of exact value in decimal in C++
I'm using MS Visual C++ 6.0 (as my work requires) on a pretty decent Windows 10 PC. I'm having trouble with displaying the value after the decimal that is entered manually via "cin >>", I've tried the fix that was answered thru DSKVP's question (Show two digits after decimal point in c++) but it still won't show the de...
I tested your code, and the only thing I changed was the return type of readResults() from int to double. Once I did that, I got the results I expected!
66,418,830
66,419,015
Generate a member name using preprocessor directives?
I would like to achieve the following but I can't get it right: struct SamplerState { int i; }; #define SAMPLER_TYPE Point #define SAMPLER_MODE_U ClampU #define SAMPLER_MODE_V ClampV #define SAMPLER_NAME( a, b, c ) ( ##a ##_ ##b ##_ ##c) #define SAMPLER SamplerState SAMPLER_NAME(SAMPLER_TYPE, SAMPLER_MODE_U, SAMPL...
You can't join ( with a in (##a. No need to tho. You have to have another level of expansion, another macro, to let a, b and c expand. struct SamplerState { int i; }; #define SAMPLER_TYPE Point #define SAMPLER_MODE_U ClampU #define SAMPLER_MODE_V ClampV #define SAMPLER_NAME_IN(a, b, c) ( a##_ ##b##_##c ) #def...
66,419,089
66,419,147
C++ Errror: "FL/Fl_xyz_Button.H: No such file or directory" in Fltk?
I'm new to C++ and Fltk. Guys this code is working fine: #include <FL/Fl.H> #include <FL/Fl_Window.H> #include <FL/Fl_Box.H> #include <FL/Fl_Button.H> int main(int argc, char **argv) { Fl_Window *window = new Fl_Window(800, 400); Fl_Box *box = new Fl_Box(20,40,300,100,"Hello, World!"); box->box(FL_NO_BOX);...
xyz is just a placeholder name for one of the possible button types, check the documentation for available types and the corresponding header: Fl_Button - A standard push button. Fl_Check_Button - A button with a check box. Fl_Light_Button - A push button with a light. Fl_Repeat_Button - A push button that repeats whe...
66,419,314
66,419,392
Why delete of templete copy constructor cause assignment operator disfunctional?
I have code like below which looks a little bit Confusing. I define a template class. It has a user-defined constructor. When I declare two objects of this template class by "operator =", its user-defined contructor is called to my surprise. Besides, After deleting its copy constructor, the compiling cannot even pass d...
Does templete constructors have different rules than non-templete class? No. MyPtr<int> p = i; (and MyPtr<int> pp = j;) is copy initialization. Note that this is initialization but not assignment, as the effect p is initialized by the constructor MyPtr::MyPtr(T). e.g. MyPtr<int> p = i; // initialization; constructors...
66,419,826
66,420,177
Why does macro expansion add a space sometimes?
If I do this: #define F a F/ It expands to a/ godbolt If I do this: #define F / F/ It expands to / / with a space in between goodbolt But if I convert it to a string, and print it, it doesn't add any spaces goodbolt: #include <stdio.h> #define STR_IMPL(x) #x #define STR(x) STR_IMPL(x) #define F / int main() { p...
The language specification is like this, at a high level: Break up the input into a sequence of tokens. Run the preprocessor on that sequence of tokens (resulting in another sequence of tokens) Compile that resulting sequence of tokens. There is no specification of any intermediate plain-text representation between t...
66,420,197
66,420,931
Is the initialization of global variable the same as the initialization of static variable inside a function
I'm trying to figure out all different kinds of initialization in C++. Now I'm reading this link: https://en.cppreference.com/w/cpp/language/zero_initialization In the example of this link, we have such a piece of code: std::string s; // zero-initialized to indeterminate value // then default-initialized...
But is it still initialized with two methods: first zero initialization, then default initialization, just like the first s? Assuming, the "as-if"-rule effectively forces the compiler to consider the existence of this variable, yes. Excerpts from the standard: Zero initialization is performed in the following situat...
66,420,370
66,420,488
Is there a better and shorter way of my for loop?
I'm a newbie here and this my first question. I learn basic c++ on Visual Studio 2019. I study functions and loops. I have a homework that wants print: I solved it with my code of 30 lines. But I just wonder is a there a shorter and better way of this? using namespace std; int main() { for (int j = 0; j < 5...
You have made several mistakes in your code. break statements should actually be continue statements. break terminates the entire loop altogether (ie. absolutely nothing will be printed in the code you provide). i == 5 can never be true, as the loop terminates before thet happens (see the condition i < 5). To answer ...
66,420,404
66,421,032
Need to fix switch statement and increasing an integer
I'm making a very simple proof of concept for my parents and tried to create a simple management game, however, in my switch statement, the second case doesn't increase a material - stone. Any idea why? Any other advice would also be appreciated. #include <iostream> using namespace std; int main() { bool alive =...
The problem is that these lines: stone - 50; ... stone + 50; just calculate the result of the expression and then throws it away. There is no assignment. You could change them to: stone -= 50; ... stone += 50;
66,420,444
66,451,925
Is it possible to use/define nested structure in CycloneDDS IDL file?
I found RTI DDS and OpenDDS are capable to define nested structures and complex structure in IDL file, but couldn't find any example for CycloneDDS on defining nested structures/ complex structures in the IDL file, does Cyclone DDS support nested structures in IDL? in the cyclones developer guide they do not mention an...
It does. It is a standard OMG IDL feature and is the same across all DDS implementations.
66,421,802
66,422,023
Pass different variables into a template function
I have a function that assigns 2 variables some values: bool get(int& value1, string& value2); I need to call a template function with one of these returned variables. How do I do this exactly? bool get(int& value1, string& value2) { /* assign them */ }; template<typename T> doWork(const T& value) { /* do some work */...
You can use if constexpr (since C++17) together with std::is_same (from <type_traits>). As you want to use it inside the loop condition, I wrapped it in a lambda: template<typename T> void foo() { int value1; string value2; get(value1, value2); auto doWorkIntOrString = [&](){ if constexpr (std::is_same_v<...
66,421,843
66,421,924
Why this formula could not be calculated in c++?
Here i want to calculate the number of sweets that i have been sold in Day 2. int main() { float rate; int left, total, sell ; cout << "rate" ; // the rate that sweets have been sold per day cin >> rate; cout << "sell"; // number of sweets that have been sold in day1. cin >> sell; cout << "total"; // total number that...
As mentioned in the comment, you are doing an integer division. Here is the corrected code:- #include<iostream> using namespace std; int main() { float rate; int left, total, sell ; cout << "rate" ; // the rate that sweets have been sold per day cin >> rate; cout << "sell"; // number of sweets that have been sold in...
66,421,947
66,422,352
Use macro to generate empty code for C++ class methods
Let's say I have a class like below: #define LOGGER_CLASS_ENABLED #ifdef LOGGER_CLASS_ENABLED class Logger{ public: void println(const String&); }; Logger this_is_a_singleton_logger; #define MY_LOGGER this_is_a_singleton_logger #endif Throughout my code, whenever I want to log somethi...
Whereas having a macro "LOG" #if defined(LOGGER_CLASS_ENABLED) #define LOG(msg) MY_LOGGER.println(msg) #else #define LOG(msg) do {} while(false) #endif would allow to entirely disable logging (and so msg is not evaluated, so LOG argument should not have side effect). To keep usage MY_LOGGER.println(x) and does "nothi...
66,422,250
66,422,428
How to detect if a type is one of a list of generic types
If I have template <typename T> struct A; template <typename T> struct B; template <typename T> struct C; template <typename T> struct D; what is the most compact way of testing if some candidate type X is one of them? I'm looking for something like boost::enable_if< is_instantiation_of_any<X,A,B,C,D> > but A,B,C and...
Not sure if there exists a std::is_instantiation_of, though if all templates have same number of parameters, it is straightforward to implement it (if they don't it is more complicated). To check if a type is an instantiation of any of given templates you just need to fold it (requires C++17): #include<iostream> #inclu...
66,422,584
66,422,790
copy elision in c++03
Copy-elision is, in some cases, mandatory in c++17, and permitted in c++11/14. This in particular concerns copy initialization. For example, the following program #include <iostream> struct A { explicit A(int){ std::cout << "conversion" << std::endl; } A(const A&) { std::cout << "copy constructor" << std::endl; } ...
Yes, copy ellision is permitted in C++03 and C++98. That's the paragraph for C++98 and C++03: Non-mandatory elision of copy operations Under the following circumstances, the compilers are permitted, but not required to omit the copy construction of class objects even if the copy constructor and the destructor have obs...
66,422,778
66,422,808
If a variable is assigned an object returned by a function, is it copied or created in-place?
I have something like this in my CPP file to initialize an object outside any class. I've simplified it but the point is there is some complex initialization going on but I want a single instance created: static MyBigObject o = []() { MyBigObject ret; ret.Init(); return ret; }(); My question is, does this objec...
In this case: this depends on your compiler. This is named return value optimization, which is optionally elided. C++17 allows, but not requires, the copy to be elided even if the object has observable side effects in its copy/move constructors (and its destructor).
66,422,869
66,422,922
How can I see the actual implementation code of different data structures in C++?
Is there a way to look at the actual code which is used to implement different data structures like list, vector<>, unorderd_map<>, map, set in C++. I was willing to see just how efficient these implementations are. And I am surprised that Google has no reasonable result on this. Thanks.
There are different implementations of the C++ standard, and some of them are open-source. For example, gcc's implementation is called libstdc++. The source code for std::vector<T>, for example, can be consulted here: https://gcc.gnu.org/onlinedocs/gcc-4.6.3/libstdc++/api/a01115_source.html An interesting example of wh...
66,423,058
66,423,876
Throw string exception from inherited exception class
I implemented my exception class which inherited from std::exception like the following : class MyException : public exception { public: MyException(string exc) { this->exc = exc; } const char * what() const throw () { return exc.c_str(); } private: string exc; }; Now i th...
You are experiencing object slicing. This happens when a derived instance is received by value as its base class -- In your case, catching std::exception by value. Your derived class' member is "sliced off" in the process of conversion to the base class. Receiving by pointer or by (const) reference is always preferable...
66,423,221
66,423,348
Cant display the numbers lost over 100
So in my little game, there is a happiness mechanic, I want it to be capped at 100, and show the player how much happiness they lost due to the overflow, but it keeps showing 100. (I created the integer happiness at the very start), its in a switch statement, all other parts of the switch work well. case 5: if (happine...
You are using the same formula to calculate both the lost_happiness and new happiness values: int lost_happiness = happiness - (happiness%100); // Notice the similarity happiness = happiness - (happiness%100); // in the two RHS codes? This is incorrect, and the former should just be happiness % 100....
66,423,495
66,430,238
Poco Option with optional argument
I have a Poco (v1.9.4) based class class PreprocessingApp : public Poco::Util::Application with these 2 methods: void PreprocessingApp::defineOptions(OptionSet& options) { Application::defineOptions(options); options.addOption( Option("proxy", "p", "Proxify connection") .required(false) ...
According to the Poco documentation: Option arguments can be specified in three ways. If a Unix short option ("-o") is given, the argument directly follows the option name, without any delimiting character or space ("-ovalue"). In default option mode, or if a Unix long option ("--option") is given, the option argument...
66,423,561
66,423,752
Synchronisation in C++ 11 with std::atomic
I have the following code that runs fine on Intel processors but produces weird data on ARM processors. I suspect that this is a synchronisation problem. Basically I have a producer thread calling setLiveData(...) periodically and a consumer thread calling getLiveData(...) periodically as well. .h file class DataHandle...
Your problem is that your code doesn't synchronize, not that your loop doesn't end. if(this->lastValuesValid){ *val = this->lastValues_; return true; }else return false; you can check if last values are valid, get true, and by the time you assign they aren't valid. Any check of validity isn't going to hol...
66,423,789
66,424,164
invalid use of member function (did you forget the '()' )
I'm trying to wrap arduino's RF24 functions into a simpler class that I could use more intuitively in the future, so I have made a .h file: #ifndef RADIO_H #define RADIO_H #include <RF24.h> #include <Arduino.h> class Radio { private: RF24 radio(int ce, int csn); int opMode; byte address; ...
You want an instance of RF24 called radio but you've declared a function called radio that returns an RF24 instance: class Radio { private: RF24 radio; // remove: (int ce, int csn); ... Then in your constructor, initialize it like this: Radio::Radio(int ce, int csn, int mode, byte channel) : /...
66,424,009
66,424,491
Drawing a chess board with SDL2's SDL_RenderDrawRect
I am fairly new to SDL2 and as my first project I wanted to just create a chess board. This has proven to be harder than I thought. I have tried lots of different ways to draw the fields of the chess board with SDL_RenderDrawRect, this is the current state: #include <SDL2/SDL.h> int main() { bool quit = false; ...
There are multiple errors in your for loops. You have to change your conditions in your for loops. Both iteration variables(x and y) start with 0, but your condition to run the foor loop is that they are greater than 3 or 8, so they wont get executed. Change it to less than the value(< instead of >) You have to change ...
66,424,337
66,424,580
Right way to write a base class that has a function that depends on a inherited member
I have two classes that I want to be derived from a base class, since they share extremely similar functions and member variables, and the only main difference between the two classes will be SomeClass vs SomeOtherClass for algo. What is the best way to approach such a problem? class A { virtual doSomething(); // i...
I think the most common way to do this is to use the strategy pattern, i.e. SomeClass and SomeOtherClass will need to derive from a common interface and you'll inject the algorithm into the base class through the constructor: class Algorithm { public: virtual ~Algorithm() = default; virtual void algo() = 0; }; cla...
66,424,777
66,424,856
I don't think that some of my code is optimized
I need some help with optimizing code, this isn't all of the code, just a part that repeats very similarly, so id like to optimize it if (training && palisade) { cout << "what would you like to do?" << endl << "1.Build a stone wall" << endl << "2.Build training ...
You can use variables to store the changing part. Assuming that no tricly operator overload are defined, it can be done like this: const char *trainingStr, *palinsadeStr; if (training) { trainingStr = "Built"; } else { trainingStr = "Allows more militia to be trained"; } if (palisade) { palinsadeStr = "st...
66,425,285
66,431,897
std::ranges::copy will not accept std::vector in visual studio
The code below does not compile in Visual Studio, giving Error C2672 'operator __surrogate_func': no matching overloaded function found sortms C:\Users\David\source\repos\sortms\sortms.cpp 103 The function works as written when I use a C-style array. The function also works if I use the commented code specifying in...
Since someone else might fall in the same mental trap that I did. The following works for either a c-style array or a std::container auto r1 = std::ranges::copy(input, std::begin(output));
66,425,466
66,426,010
Run function without duplicate
I want to know if it's possible, to make the function run without duplicates? If it's looping through array with numbers 1,2,2,3,4 I would want the 2 to be run only once instead twice. Like 1,2,3,4. How can I check if tab[i] has been already inserted? I need to do this in c++ 98. std::vector<int> noDup(n); for(...
You did if(exists == false) { noDup.push_back(tab[k]); } in wrong place. It have to be after checking all elements. Also the vector std::vector<int> noDup(n); already has n elements and push_back() will add elements after the initial n elements. It seems you want to pre-allocate without adding elem...
66,426,254
66,426,547
How do I join two arrays of struct?
So this is my code: #include <iostream> using namespace std; typedef struct { float during; double high_fre; double mid_fre; double low_fre; double extra_fre; } notes; int main() { const notes song[5] = { 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,1, 1,1,1,1,...
C-style arrays can't be assigned or concatenated, and can't be used as the initializer for another array. You can use memcpy() to copy them if the element structure is POD, as in your code. But the destination array can't be const in this case. Also, sizeof returns the number of bytes in an object, not the number of ar...
66,426,568
66,426,840
Is there a way to make a vector of objects on construction via which members can be altered?
I'm trying to find a way to add objects to a vector upon construction which allows for the members of the objects to be altered. I'm familiar with using a static member vector, but these seem to lock the instance values at the initialized state, i.e: class This { public: static std::vector<This> group; ...
If you store pointers to the elements in your vector instead of copies then it'll work class This { public: static std::vector<This*> group; std::string name; explicit This(std::string n) : name{std::move(n)} { group.push_back(this); } This(This const&) = delete; This(This&&) = delete; This...
66,426,909
66,427,142
This simple Mutex does not have any effect
I am trying to learn basics of multi-threading. Below example is from the book "Art of Multiprocessor Programming" which has (in Java): class Counter { private long value; private Lock lock; public long getAndIncrement() { lock.lock(); try { long temp = value; ...
The effect of the mutex should be to make sure no two threads are simultaneously reading or writing to the member (only reading is fine). In your code thats not the case because at the same time one thread locked the mutex and writes to the member the main thread might call show. You need to protect any access: void sh...
66,426,963
66,427,626
Docker: run binary inside container after build - permission denied
The entrypoint of my Dockerfile is: ENTRYPOINT ["/bin/bash", "-l", "/runner/run.sh"] The run.sh simply builds a binary file and tries to execute the result, like: [....] cd /tmp/repo cmake . make ./main But at the execution of the binary, an error occurs: /runner/run.sh: line 16: ./main: Permission denied I checked...
The problem is within docker-compose that mounts tmpfs as (rw,nosuid,nodev,noexec,...) https://github.com/docker/compose/issues/3425. Using: version: "3.6" services: svrunner: image: runner:latest tmpfs: - /tmp:exec,mode=777 solved the problem.
66,427,083
66,428,368
How to forward declare a C++ struct in case nested namespaces are used?
I have following C++ code A.h namespace x { namespace y { namespace z { struct Container; class A { public: A(Container& _container); void info(); private: Container& container; }; } } } A.cpp #include "A.h" #include <iostream> namespace x { namespace y { namespace z { A::A(Container& _co...
The problem is that you never declared x::y::Container in A.h. You did declare x::y::z::Container, but that doesn't name the same type. Simply move the declaration into the y namespace: namespace y { namespace z { struct Container; Into -> namespace y { struct Container; namespace z {
66,427,313
66,427,501
When should we set the C++ Windows desktop application's entry point?
I'm a bit confused as to what the best practices are for setting entry points for C++ applications, I've tried to find some answers to this but everything I've seen deals with how to do it rather than why. Let's say I have a Windows desktop application with 2 build configurations: Debug and Release. Debug has subsystem...
I would say use the same entry point for both and skip the console build entirely. Instead use the VS debug console. The only time you would use the custom entry point is if you aren't using the MS C runtime at all. And I have never had reason to do so.
66,427,573
66,429,390
C ++ Stack Memory Usage
As a c ++ beginner, I have a problem with when variables should be used in methods and when in classes. For example, does define a variable that we send continuously in the method as below and defining it in the header file means the same thing for memory? void my_method() { int my_val=0x04; Send(my_val); } Is this us...
Just putting the dots on the i here (forgive me for being verbose). If your class my_class has a method my_method and my_val is defined in the class instead of the method, when you instantiate my_class you get an object, along with its attributes, that resides either in the heap or in the stack (depending on whether yo...
66,427,588
66,428,062
How to change function so that the difference between target and any element is minimum?
how can I change these two (or either of them) functions to get the minimum dist where dist=pow(target-v[i],2). I want to get the index of the element in the vector with the smallest distance from target considering that the vector is ordered and I want to find the element efficiently using binary search. Thanks a lot....
First of all, to use binary search algorithm, you must be sure about the given array or the vector is sorted or not. If the vector is sorted then only you can apply binary search to find the index of the closest distance. Now considering the given vector is sorted, we can apply binary search. Another thing that I see i...
66,427,731
66,428,063
C++ DLL import class unresolved external symbol
Hi I'm sorry I've seen that there is a lot of "unresolved external symbol error" questions, and I've seen them but none of the answers that I found fixed my error. I've tested 2 ways to compile the DLL and use the HelloWorld method from SerialPort class. btw I'm using VS2019 community edition Both ways are throwing the...
You are calling HelloWorld which is missing its implementation in your application. There is some fundamental misunderstanding about how C++ executables are compiled and linked against DLLs. No libraries: All symbols that the Application needs must be defined in the Application. All needed symbol definitions must be a...
66,427,864
66,428,226
To remove double quotes from vector<string> c++ 98
I am trying to remove the double quotes characters from my vector string value. for eg: if my vector string has values (50,40,"50GB","40GB",60). i am trying refine the vector by erasing Double quotes(" "). so the my final vector (50,40,50GB,40GB,60). Below is the piece of code I tried to make it work, I got compilation...
str[p][i] is of type char, so you need to compare it to a char. Putting your double quote in two single quotes should do the trick: if(str[p][i] == '"') { str[p].erase(i, 1); i--; } Full code: #include <iostream> #include <string.h> #include <algorithm> #include <vector> using namespace std; void removeChar...
66,428,171
66,428,217
Is there a way to get a pair having both the lower_bound and upper_bound in a sorted array?
If I have a std::vector having elements {1,1,1,2,2,2,3,3,3} Is there a way to get a pair containing the lower_bound and upper_bound for value = 2 ? Instead of me calling std::lower_bound and std::upper_bound separately.
You could use std::equal_range.
66,429,139
66,429,338
Error trying to use AccessibleObjectFromWindow()
I'm trying to use the AccessibleObjectFromWindow() function, but my main.cpp returns these errors: main.cpp:24: error: undefined reference to 'IID_IAccessible' main.cpp:27: error: undefined reference to 'AccessibleObjectFromWindow' main.cpp:-1: error: collect2.exe: error: ld returned 1 exit status main.cpp #include <i...
For the 1st error, you need to link in uuid.lib. For the 2nd error, you need to link in Oleacc.lib, it is not enough to just include oleacc.h. See Adding Libraries to Projects in the Qt Creator documentation. Or, you can use #pragma comment(lib, "filename.lib") statements in your code, eg: #pragma comment(lib, "uuid.li...
66,429,191
66,430,706
clang-query: Examining name of template parameter of a function argument's type
I have a big project, and a slew of C++ class member functions of the form: Return CClass::MemberFunction( Arg1 arg1, //... std::weak_ptr<IMemberFunctionListenerInterface> listener) { //... } I'm trying to write a matcher that finds functions like these, which have arguments whose types have the string "Liste...
On one line: clang-query> m cxxMethodDecl(hasAnyParameter(hasType(allOf(cxxRecordDecl(matchesName("weak_ptr")), classTemplateSpecializationDecl(hasTemplateArgument(0, templateArgument(refersToType(hasDeclaration(cxxRecordDecl(matchesName(".*Listener"))))))))))) clang-formatted: cxxMethodDecl(hasAnyParameter( hasTy...
66,429,404
66,452,905
xtensor : How to write an vector to an array
What is the equivalent in xtensor or the most optimized way to write a vector to an array. Thanks import numpy as np array = np.zeros((4, 4)) array[0] = np.array([1, 2, 3, 4]) # this
The easiest way is #include <xtensor/xtensor.hpp> #include <xtensor/xarray.hpp> #include <xtensor/xview.hpp> #include <xtensor/xio.hpp> int main() { xt::xtensor<double, 2> array = xt::xtensor<double>({4, 4}); xt::xtensor<double, 1> row = {1, 2, 3, 4}; xt::view(array, 0) = row; return 0; } You can use...
66,429,501
66,430,016
Static Signals in QT
Im looking for the elegant pattern to follow the events of all instances of a class. So in theory it should be possible to emit a signal as from the class either directly or within a static method (which doesn't seem to be necessary then) because: The connect() method declares a sender and the signature of it. In this ...
In theory, Qt Could implement this feature, by basically adding code generation for the helper object code you showed to the moc compiler. Because any signal is a function declaration, of which the implementation is generated by the moc compiler. This implementation is basically just a: for( auto& slot: connected_slot...
66,429,815
66,435,163
JNI: is the return value of GetObjectClass supposed to vary for the same object?
Here's some JNI behavior that's baffling me on OpenJDK 8.272 (code is in C++): JNIEXPORT jlong JNICALL Java_/*name omitted*/(JNIEnv *env, jclass, jobject obj) { assert(env->GetObjectClass(obj) == env->GetObjectClass(obj)); return 0; } This assert fails. Is this expected behavior? If so, for how long is it safe to ...
To cite the specification: Local References Local references are valid for the duration of a native method call. They are freed automatically after the native method returns. Each local reference costs some amount of Java Virtual Machine resource. Programmers need to make sure that native methods do not excessively al...
66,430,027
66,430,630
How to use correctly Constructor-Function-Try-Block?
I am trying to understand "constructor function try block"; in "C++ Primer, 5th edition", chapter 18: template <typename T> Blob<T>::Blob(std::initializer_list<T> il) try : data(std::make_shared<std::vector<T>>(il)) { /* empty body */ } catch(const std::bad_alloc &e) { handle_out_of_memory(e); } Notice ...
I didn't understand the second and third paragraphs; it looks to me like it is contradictory, because it is said that to handle exceptions from a constructor-init list we use ctor-function-try block, and from the other side it said that "it's worth noting that an exception... such exceptions are not a part from functi...
66,430,215
66,430,682
English and arabic mixed string not ordered correctly Qt
So I have a code in Qt that goes joins the Strings “john جونسون” and “(جيد جداً), but when i add them up I get the answer in a wrong order ex.: john (جيد جداً) جونسون’
This has nothing to do with Qt. It is a unicode thing. Qt just adds the characters. The problem arises because the string starts of in LTR(left to right), with 'jhon' because that is in latin alphabet, but then when you add an arabic word to that, the first letter of that word, should be on the right, because arabic is...
66,430,460
66,430,507
Getting a "Use of undeclared identifier" error
I am to create a custom String class in C++ with different methods in it. The problem I have is that I get a "Use of undeclared identifier" error with a method that is declared in another file: #include <iostream> #include "String.h" int main() { std::cout << "Hello World!\n"; char str[] = "Today I am happy."...
If these functions are independent of the class, you can declare them static. static void strlwr(char *s1){ //method static int strlen(char *s1) //method And them use them like this: cout<<String::strlen(str); // error String::strlwr(str); //error
66,431,143
66,433,064
binary sum through <bitset> and HEX
I'm trying to build a simple BIN -> HEX converter using a class, I would like to save it later in a header file for eventual need <.<" . It kinda works. Kinda because I have some output, but I cannot understand what is happening when it prints X. Why Am I getting those else exceptions ? I should get only 4 bit combinat...
You can do much simpler by simply combining four subsequent characters into a number: char const* const digits = "0123456789abcdefg"; // or upper case, if you prefer for(auto i = x; i < byteCount; i += 4) // ^: to be considered later! { unsigned int n = (stringa[i + 0] == '1') << 3 | (str...
66,431,203
66,431,358
What is the easiest way to parse a json file using rapidjson?
So I am just getting familiar with rapidjson.h but I can't find this one basic piece of example code of parsing the *.json file. I found the official [turorial][1]. But here however they parse the json stored in a C string. I know how this string is supposed to look like but I'm lazy to make a custom Parser just to con...
You can use FileReadStream and ParseStream instead of the IStreamWrapper. According to the documentation, FileReadStream is much faster than IStreamWrapper. The R means that it's a raw string literal. Without it, the backslashes are interpreted as the start of escape sequences and you would have to write it like this t...
66,431,523
66,431,668
Class variable in a class of itself C++
I have a class called Node: class Node { private: Node right; Node left; std::string value; public: Node(Node right, Node left, std::string value) { this->right = right; this->left = left; this->value = value; } }; And I need to declare a private variable of type Nod...
You must declare the members as being pointers to Node instances. Especially since you want to be able to set them to NULL, which can only be done with pointers: class Node { private: Node* right; Node* left; std::string value; public: Node(Node* right, Node* left, std::string value) { t...
66,431,703
66,431,752
Probably defect in wording of C++ working draft (integer conversion rank rules)
I have found a possible contradiction in the working draft of standard C++. First I present the facts, and my question comes at the end. When the integer conversion ranks are established, [conv.rank]/1.1 says No two signed integer types [...] shall have the same integer conversion rank, even if they have the same rep...
we have two different signed integer types I see nowhere in the standard that it says that wchar_t is a "signed integer type". Or an "unsigned integer type". I see where it says that it is an "integer type": Types bool, char, wchar_­t, char8_­t, char16_­t, char32_­t, and the signed and unsigned integer types are col...
66,432,039
66,432,066
Find average of grades and find largest value (c++)
So I need to find the average of x amount of students' grades (its a loop). It will keep adding until you enter -1. I got the average correct but to find the largest value is where the problem is at. It always prints out a garbage value instead of the largest value out of the list Example input-output: Enter the gades ...
You forgot to initialize largest. Also your indentation and brackets need to be reviewed to ensure they are balanced. Right now it looks a right mess.
66,432,181
66,434,056
Inherited constructor cannot be used to copy object
This program does not compile: template <class T> struct Base { Base(); template <class U> Base(const Base<U>&); }; template <class T> struct Doh : Base<T> { using Base<T>::Base; }; template <class T> struct Derp : Base<T> { using Base<T>::Base; }; Doh<void> x = Derp<void>(); The error messa...
Because that is how it is prescribed to work. [over.match.funcs/9] A constructor inherited from class type C ([class.inhctor.init]) that has a first parameter of type “reference to cv1 P” (including such a constructor instantiated from a template) is excluded from the set of candidate functions when constructing an ob...
66,432,468
66,432,891
Where does the rule in the standard specify that a function with a trailing-return-type whose return type contains a placeholder type should be `auto`
auto* fun()->int*{} int main(){ } This snippet is rejected by both Clang and GCC, and they report an error, which is 'fun' function with trailing return type has 'auto*' as its type rather than plain 'auto' However, I haven't found any rule that forbids this usage in the standard. The only relevant rule that I feel ...
It's the grammar. This was core issue 681. declarator: ptr-declarator noptr-declarator parameters-and-qualifiers trailing-return-type ptr-declarator: noptr-declarator ptr-operator ptr-declarator noptr-declarator: declarator-id attribute-specifier-seq_opt noptr-declarator parameters-and-qualifiers noptr-...
66,432,644
66,432,756
Should I store a reference to map in a member variable?
I have the following classes: class State { std::string name; int id; }; class Device { private: int stateID; public: const std::map<int, State> possibleStates; Device(std::map<int, State> states) : possibleStates(states) {} }; I would like to be as memory efficient as possible. My question is, do...
A reference member is allowed, but a dangerous thing. It needs to refer to another object outside the class object, where some other code makes sure the object referred to is certain to exist for as long as the class member might be used again. And if you changed just the member type and had: class Device { private: ...
66,433,018
66,506,082
2D Rectangle rotated in 3D coordinates
I have a 2D Rectangle defined with 4 points ordered in counter clockwise fashion - e.g. point 0(x0,y0), point 1(x1, y1), etc.I would like to know how to rotate each of these points in 3D space (even though the Rectangle is 2D). I would like to randomly choose the axis (x, y or z) to rotate around. Something along the l...
Your implementation doesn't look correct to me. I were you I would just write one function for rotation around any axis through the origin of the coordinate system pointing in a general direction. Then you choose the specific directions as you please. Here is code in python (it is more concise and presents the idea mor...
66,433,092
66,433,291
./a.out on visual studio code on windows wont work - gives a 'look for an app in the Microsoft Store' prompt
I am trying to run a simple hello world code of CPP. Nothing fancy. Just a couple of header files with a basic hello world class. I have the following sequence of commands. g++ -c HelloWorld.cpp -o HelloWorld.o g++ -c main.cpp -o main.o g++ HelloWorld.o main.o -o a.out All goes well. Then, I do the next logical step ...
[with help from comments from @MarkTolonen above] g++ -c HelloWorld.cpp -o HelloWorld.exe g++ -c main.cpp -o main.exe g++ HelloWorld.exe main.exe -o a.exe ./a.exe The above worked for me.
66,433,336
66,436,016
Error due to rvalue to lvalue conversion and not using forward
The following code shows a segmentation fault both in windows & Linux machines. The Parent class stores a pointer, but due to rvalue to lvalue conversion, the Parent ends up storing a reference to a pointer. (This is as per my understanding, please correct it otherwise) #include <iostream> #include <vector> class Root...
First, here's what's happening, keeping in mind that getInt returns an rvalue: when you don't forward ptr, you end up invoking (post-reference collapsing) MyFunction<int*>(int*&&) which invokes Child::Child<int*&>(int*&) which constructs and stores a Parent<int*&>. When you do forward ptr, you end up invoking MyFunc...
66,433,509
66,433,586
Using an istringstream With ASCII 26 Character
I have a fairly simple ask, but I haven't been able to find any help anywhere, so I was hoping for some help. I'm working with some C++ stringstreams and I have string data that is causing my stream to fail. Specifically, the stream fails when I encounter the Ctrl-Z character (26 or 0x1A), which isn't particularly surp...
I suggest avoiding use of std::istringstream altogether. Since you seem to be working with one character at a time, just iterate over the string and process each character as you see fit. std::string data = getImageData(); for (char ch : data) { // Use ch }
66,433,559
66,434,351
How to use parallelization properly in C++ to make the code faster?
I am trying to use parallelization in C++. Below is just a sample code I wrote. I heard that I need enough amount of N in order to make parallelization work.(In this code 'i' I guess...) So I came up with 3-dimensional arrays. (I increase the size of 'Stack Reserve Size' to run the code below.) And I used 'chrono' to m...
Your problem is memory-bound. This means that the program spends much more time moving data to/from memory/caches than actually computing. Indeed, the computation consists only in two additions. You could increase your arrays (on the heap, not in the stack of course), the ratio between memory transfer and computation t...
66,433,585
66,433,746
Vulkan Array of Specialization Constants
Is is possible to have an array of specialization constants such that the glsl code looks similar to the following: layout(constant_id = 0) const vec2 arr[2] = vec2[] ( vec2(2.0f, 2.0f), vec2(4.0f, 4.0f) ); or, alternatively: layout(constant_id = 0) const float arr[4] = float[] ( 2.0f, 2.0f, 4.0f, 4.0f...
The shading languages (both Vulkan-GLSL and SPIR-V) makes something of a distinction between the definition of a specialization constant within the shader and the interface for specializing those constants. But they go about this process in different ways. In both languages, the external interface to a specialization c...
66,433,786
66,434,793
My code works with input files, but doesn't with others. (Debug Assertion Error)
Write and test a program that prompts the user to input a file name and a string to test for. Search the file for every occurrence of the specified string – when the string is found, display the line that contains it. When all occurrences of the string have been found display the number of times the string appeared in ...
I debugged the program and WhozCraig is right. In your input text in the line Don’t be silly, you're going to the game! In the word "Don’t", you do not have the normal apostrophe as you have in the word "It's" or "you're" This special character is encoded as -110 in temp_string. In the description of std::ispunct you...
66,434,355
66,434,475
Does C or C++ guarantee array < array + SIZE?
Suppose you have an array: int array[SIZE]; or int *array = new(int[SIZE]); Does C or C++ guarantee that array < array + SIZE, and if so where? I understand that regardless of the language spec, many operating systems guarantee this property by reserving the top of the virtual address space for the kernel. My questi...
Yes. From section 6.5.8 para 5. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. Expression array is P. The expression array + SIZE - 1 points to the last element of arr...
66,434,359
66,434,812
error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::_List_iterator<int>’)
Hello im trying to print a list of ints and i keep getting that erro. I have a structure that have a list on it. struct faceFiguration{ int faceID; list<int> setofVertices; }; And i have a list of that sructure list<faceFiguration> pattern; and heres where i get confuse, i trie to print the lists here: voi...
You've already gotten answers telling you to dereference the iterator: for(auto currentVertices = currentFace->setofVertices.begin(); currentVertices != currentFace->setofVertices.end(); currentVertices++) { cout << *currentVertices; // dereference } You could however do that automatically by using a ran...
66,435,166
66,441,090
setting QComboBox text with multiple columns
I have a QComboBox that contains QTableView like below. When I select a row, QComboBox title shows only "Alex" but i want "Alex - Alex address". How can i do it? Thanks.
I suggested: Have you tried signal QComboBox::currentIndexChanged(int index) in combination with QComboBox::setEditText()? I'm not quite sure whether this works as well if editable is false but might be worth to check out. and OP asked for an answer as this seemed to be valuable. So, here we go: // standard C++ heade...
66,435,279
66,435,402
Forwarding additional arguments via lambda function
Here is the minimal reproducible code, #include <iostream> #include <string> void bar(std::string s, int x){ std::cout <<std::endl<< __FUNCTION__<<":"<<s<<" "<<x; } using f_ptr = void(*)(std::string); void foo(f_ptr ptr){ ptr("Hello world"); } template<typename T> void fun(T f){ s...
Is there any way to forwards additional arguments like case:3 via lambda? What conversion is causing error in case:3? Lambdas with capture list can't convert to function pointer implicitly; lambdas without capture could. You can use std::function instead, void foo(std::function<void(std::string)> f){ f(...
66,435,317
66,436,692
How to find how many items(values) are in lua stack
I'm working with lua in C++ and I want to find how many "slots"(you can say) are being used in lua stack, and if possible, what is the size of lua stack?
lua_gettop(lua_State* L) The number of elements in the stack is the same as the index of the top slot. If you are interested here is something that will print the whole stack for you using this information. int top = lua_gettop(L); std::string str = "From top to bottom, the lua stack is \n"; for (unsigned index = top;...
66,435,598
66,436,028
Alias Declarations for template members
I'm trying to generalize runtime attribute getter/setters for my classes with compile time declarations. I thought I could do something like this: // header class arguments { public: template <typename T, char const *NAME> void set_id(T const &id) { ///.. set(NAME, id); } }; class test : public arguments...
You cannot use using for that, you have to write the method: class test : public arguments { static constexpr const char AlphaStr[] = {'A', 'l', 'p', 'h', 'a', '\0'}; public: auto set_alpha(double d) { return arguments::set_id<double, AlphaStr>(d); } }; Demo
66,435,720
66,435,840
C++ Powershell not executing command properly?
So, I have a quick bit of code that should give me the drive serials that are currently installed on the system, however, when I run this, powershell gets an error. I'm not entirely sure what's wrong here, as when I type the command on powershell it works fine. Here is some of the code : std::string exec(const char* cm...
_popen spawns cmd.exe to run your command. The _popen function creates a pipe. It then asynchronously executes a spawned copy of the command processor, and uses command as the command line. Thus the | is being interpreted by cmd, which tries to run % as a command. Thus the output coming out of cmd: '%' is not recogn...
66,435,943
66,508,881
std::cin >> c; gets ignored after reading numbers into array
I'm trying to input some numbers into an array. Pretty simple task. int array[100], n = 0, length = 0; std::cout << "Input numbers: " << std::endl; while (std::cin >> n) { array[length++] = n; } I press shift + F10 in CLion, trying to run it and it won't end the while (I pressed enter 5 times in a row), it goes o...
The approach of reading user inputs until Ctrl+D is not a good idea since it causes many problems to your program and may have potential errors when running on other platforms. Ctrl+D closes the system level pipe so I am not sure if there is a proper way to restore the input stream after being stopped by EOF. As I said...
66,436,095
66,436,236
How to get the type of constructor and dereference operator (decltype) without assuming any constructor?
Assume I have the following template: template<typename T> struct S { typedef decltype(foo(T{})) TypeThatSomeFooFunctionReturns; typedef decltype(*TypeThatSomeFooFunctionReturns{}) TypeOfDereferenceOfWhateverFooReturns; ... }; Now, this works just fine if the type T has a default constructor and if whateve...
You might use std::declval, and type_traits to modify the type: template<typename T> struct S { using TypeThatSomeFooFunctionReturns = decltype(foo(std::declval<T>())); using TypeOfDereferenceOfWhateverFooReturns = std::remove_pointer_t<decltype(foo(std::declval<T>()))>; // ... };
66,436,230
66,436,561
Deserialize a const member object in a constructor
I need to initialize the const member object of a class in a constructor, but the member's constructor creates just an empty object, whereas real initialization has to be done by deserialization of this object from a file. The class of the member object is not mine and I can't change it. Namely, it's a Dlib model, the ...
Just make the member variable non-const. Having const member variables is usually a pain and is rarely useful. if you absolutely must have it const, you could make a class that inherits from ShapePredictor and add a constructor that does the streaming. struct ShapePredictorStreamable : public ShapePredictor { Shape...
66,436,579
66,436,695
OpenGL: cylinder misshaped after turning it 90 degree
I and my college project partner are doing this project. We write this in c++ and OpenGL 2.1 with the freeglut.lib We turned the cylinder to lay down on the ground by 90 degrees. Now the cylinder is oddly misshaped. How can we fix the misshape? Is this a perspective thing? We wanted to use the cylinder later as wheels ...
You need to enable the Depth Test: glEnable(GL_DEPTH_TEST); and clear the depth buffer as well glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Example: float angle = 0.0f; void display(void) { glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTrans...
66,437,715
66,452,051
How to handle VK_MENU (alt) keypresses properly using WinAPI?
I am writing a windows application using the WinAPI (win32) on C++, but can't figure out what's happening with the ALT key. I am handling both WM_KEYDOWN and WM_SYSKEYDOWN, so all keypresses should be coming through. However, while every ALT keyup is detected, every second ALT keydown is being skipped. Do I have to gen...
I can reproduce the problem through code, and then I capture the message of the window through spy++. We can see that when the ALT key is pressed for the first time, the WM_SYSKEYDOWN and WM_SETTEXT messages are successfully triggered: When the ALT key is pressed the second time, it actually triggers the WM_SYSKEYDOWN...
66,437,730
66,437,951
how do I fill the gaps between pixel in bmp file after loading the pixel array into the array with padded rows
I wrote a program in c++ to draw the pixel of bmp image into the console using SetPixel windows function, but after loading the pixel array into the array the image got printed on the console with gaps between the pixels. Thanks in advance for your help! This is the output of the printed image on the console. This is ...
A pixel is described by three bytes, one for each RGB channel. You are dealing with two indices here: The index of the pixel in the row data and the position of the pixel in width direction. You place the pixel and access the row data with the same index. So: for (int jj = 0; jj < width; jj++) { // jj: positio...
66,437,909
66,487,280
Destructor called more times than it should. Bug in MSVC or not?
This program: #include <iostream> using namespace std; struct B { B() { cout << "B"; } //B(const B& b) { cout << "copyB"; } ~B() { cout << "~B"; } }; struct C : B { }; void f(B b) { } int main() { C c; f(c); return 0; } outputs B~B~B~B, i.e. three times calling destructor, why? Only in ...
The conclusion is it's a bug of MSVC. Although the standard specifies a temporary object can be created when passing the argument to a function, however, many restrictions should be obeyed. The relevant rule is written in the following: [class.temporary#3] When an object of class type X is passed to or returned from a...
66,438,091
66,438,200
C++ '+' concatenation operator changing contents of pointers in pointer vector
So I wanted to write a program that did the following: Accept a string input from user using std::getline(std::cin,str) Append this input to std::string object using + operator Initial value of object is object="\n" After user inputs a line and it is appended to object , add a '\n' to object so for example, if hello i...
object is likely to be reallocated as you concatenate stuff into it. This means the pointers to its content in lines are invalidated. That's undefined behavior.
66,438,201
66,439,799
C++ Aliasing a type with the same name
Consider the following code: class A {}; class B { using A = A; }; With Clang and ICC this compiles fine, while GCC fails with the following message: error: declaration of ‘using A = class A’ changes meaning of ‘A’ [-fpermissive] 4 | using A = A; | ^ Question: Which compiler is correct and why?...
Clang and ICC have it right. [basic.scope.pdecl] 3 ... The point of declaration of an alias or alias template immediately follows the defining-type-id to which the alias refers. Where the grammar for an alias declaration is [dcl.pre] 1 ... alias-declaration: using identifier attribute-specifier-seqopt = defining-ty...
66,438,317
66,438,404
Duplicates when inserting into std::set<std::tuple<std::string, ...>>
I tried to use std::tuple as an element of std::set where std tuple consists of std::string and a bool (for this example only, in normal use case the tuple consists of 3 elements). The string of the tuple shall be unique, therefore I created comparator that would sort the elements on the first element of the tuple. How...
std::string::compare returns int (neg, 0, positive) not bool (less than), you want std::get<0>(l).compare(std::get<0>(r)) < 0; or std::get<0>(l) < std::get<0>(r);
66,439,562
66,440,546
How to get largest n values in c++ vector (Eigen)?
I have a quite large Eigen matrix in c++, but now I want in each column only 6 values that are unequal 0. Herefore, I want to set all values to 0, except for the largest 6. I don't know how I can do that, can anyone help me?
//std #include <iostream> #include <vector> #include <numeric> //eigen #include <Eigen/Dense> using namespace std; int main() { Eigen::MatrixXf m(4,4); m << 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16; // Take the 2nd column auto col1 = m.col(1); // Generate a sequence...
66,439,676
66,439,875
C++ User interaction in classes
In first semester CS when I had procedural programming the lecturer always told not to mix program functionality and interaction with the user in the same functions. Now I have object oriented programming and I am confused how to implement interaction with the user in the classes. Here I started coding a project that l...
cout << something is not exactly "interaction with the user", it just informs the user of something, so this is ok I think. And as you have no input in your code, you are fine so far. But there is no sense in having multiple if statements in a row to check which operation is being use, use else if instead.
66,440,041
66,440,740
Pass nested types to a parent class without repeating yourself (DRY) in C++20
As shown in the example below, I need my Component struct to be able to access all the "fields" structs defined in a child struct. But I have some constraints: The fields must be declared as nested types of the inheriting struct. I cannot use any library like BOOST to solve that problem There can be a theoretically in...
With MACRO, up to hard coded limit, you might do something like: #define COUNT_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N #define COUNT(...) COUNT_N(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) #define CONCAT(A, B) A ## B #define FIELDS_VAR(N) CONCAT(FIELDS_, N) #define USING_VAR(N) CONCAT(USING_, N) #...
66,440,424
66,440,541
Error: Illegal or missing hexadecimal sequence in chunked-encoding
I'm writing my own http server and right now I'm trying to tmplement chunked transfer encoding. My attempt looks like this: void HttpServer::SendRespons(HttpServer::Connection &socket_) noexcept { int sent = 0; int counter = 0; int index = 0; std::size_t response_size_; std::ifstream t(this->conf_.GetRootPath...
I think only one \r\n is needed at the end of this portion of code. strVec.push_back("3ff6\r\n" + socket_.respons.substr(index, 16374) + "\r\n\r\n"); You should not insert an empty line between the previous chunk and the hexadecimal size of the next chunk. (and the same goes for the last chunk...
66,440,497
66,440,544
Why do I get a segmentation fault for this?
I just want to create a simple C++ struct that has an int index and an int grayValue .The function is given the vector with the gray values. When I try to compile it I get a segmentation fault, does anyone know why? (didn't sort the vector) Thank you. vector<gray> createStruct( vector<int> grayValues) { vector <gray...
It is because you are using elements of grayStruct, which actually doesn't exist, in the function createStruct. You have to create elements before use or use push_back() to create elements. Create elements via the constructor: vector<gray> createStruct( vector<int> grayValues) { vector <gray> grayStruct(grayValues.s...
66,440,500
66,441,166
Why is this part repeated three times?
Here is my code: #include <iostream> using namespace std; class motor { public: motor(); ~motor(); private: }; motor::motor() { cout << "I'm the motor of this car." << endl; } motor::~motor() { cout << "the motor of this car is removed." << endl; } class doors { public: doors(); ~doors();...
You missed the copy constructor and thus you are facing the problem. #include <iostream> using namespace std; class motor { public: motor(); motor(const motor& c); ~motor(); private: }; motor::motor() { cout << "A new motor was made" << endl; } motor::motor(const motor& c) { cout << "A motor wa...
66,440,894
66,441,313
How to achieve a simplified interface for C++ function template?
I have function templates with two arguments, but the second argument is dictated by the first, and I would like to avoid writing both arguments when I call the function - that will help prevent mistakes and also be cleaner. I am looking for design advice or language features that will let me do this. Given: /* E1 and ...
auto might be a good way: template <MyEnum E> auto Function() { if constexpr (E == MyEnum::E3) { /* do something and return a T2* */ } else { /* do something and return a T1* */ } } Else, you can create custom "traits": #if 1 // In your case a simple `std::conditional` does the job templat...
66,441,238
66,446,966
Is it possible to build task based on the specific file extension?
Specifically, I'd like one keyboard shortcut to build an executable file with the correct compilation command and flags, whether the source file is a .c or a .cpp. For example, my current tasks file, which compiles .cpp files, is as follows: { "version": "2.0.0", "tasks": [ { "type": "cppbui...
You can use the extension Command Variable. Use the command: extension.commandvariable.file.fileAsKey The order of the extensions is important. { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "${input:pickComp...
66,441,360
66,442,851
mremap will not expand past size of one page
I'm creating a template class with a dynamic array that behaves like std::vector but the underlying array is stored in shared memory so that it can be shared between processes. At this time, there is no synchronization built in, just working on getting the memory mapping resizing to work as intended and the code is a m...
mremap cannot resize mapping that is both shared and anonymous. Every virtual address region has an optional file object associated with it that is used to fetch new pages and writeback old modified ones. Since anonymous mappings have no such file, there is nowhere to store pages when you shrink it and nowhere to get m...
66,441,691
66,441,926
Different std::map size when inserting with operator[] (vc++ vs g++)
This code #include <iostream> #include <map> int main() { std::map<int, std::size_t> m; m[0] = m.size(); std::cout << m[0] << std::endl; } will print 0 with vc++ and 1 with g++. Is this code valid? If yes, which compiler is correct? Intuitively I would expect 1. How does vc++ end up with 0?
Since C++17 the order of evaluation is guaranteed, m.size() is sequenced before m[0]; the result is guaranteed to be 0. In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect...
66,442,286
66,442,674
How to override a method with template parameter as an argument in C++?
I have declared a class template which contains a virtual method with template parameter as its argument: template<typename T> class BaseClass { ... virtual void SomeMethod(T arg) = 0; ... }; Now, I want to create a class which is derived from the template and override the method: class DerivedClass : publ...
To override a virtual member function in a template class is like what we do for normal class. A possible reason for that compiler message could be that DerivedClass declared pure virtual function or a pure virtual function of BaseClass<int> doesn't have its implementation in DerivedClass, then DerivedClass is still ab...
66,442,314
66,442,785
Size of string data type in C++ array
This is a very simple code in C++. The address of the strings are separated by a constant gap of 28 bytes. What does these 28 bytes contains. I am trying to find an analogy with the gap of 4 bytes of an array containing integers. As far as I know the 4 bytes ensures the upper limit of the value of an integer that can b...
What does these 28 bytes contains. It contains the object of type string. We don't know any more unless we know how you have defined that type. If string is an alias of std::string, then it is a class defined by the standard library. The exact contents and thus the exact size depend on and vary between standard libra...
66,442,708
66,446,969
How to use reference in boost graph property?
I'm trying to define a boost adjacency list which holds a reference to a property defined in an external container (not necessarily 0 based!). As I want to filter the resulting graph at runtime I'm trying to add all vertices at startup and connect all of them with each other (no loops). However the compiler always comp...
The restriction is that properties need to be default-constructible. std::reference_wrapper is not. In fact, a simple AdjLst graph(4); would run into the same trouble. The reason is that add_edge is able to grow the vertex space: // Here we override the directed_graph_helper add_edge() function // so that the number o...
66,442,971
66,447,785
determine whether wchar_t is a built-in type or alias
Yes, wchar_t is supposed to be a built-in type in C++; unfortunately, that's not the case with some (very) old compilers. Is there a (compiler-specific, e.g., GCC/g++) way to determine whether wchar_t is a built-in type (keyword) or a typedef? The reason is to determine whether f(wchar_t) can be an overload; if wchar...
Ayxan Haqverdili's suggestion in comment of using a template with sizeof() solves my problem. (It also illustrates why sufficient context regarding "why?" is necessary.) My code is now: void f_(uint16_t ch_utf16) { /* UTF-16 processing */ } void f_(uint32_t ch_utf32) { /* UTF-32 processing */ } template<typename T> v...
66,443,003
66,443,124
How to setup a c++ project for 2D graphics with hardware accelleration
I'm trying to create a project in c++ that emulates the rendering pipeline to get a better understanding of how it works. I also want to use hardware acceleration (using compute shader programs) to increase the speed of the program, but I can't find much helpful information on the internet. I'm thinking of using OpenGL...
There is no 2D rendering acceleration in OpenGL. You can use OpenGL for 2D graphics, though, if you simply ignore the Z coordinate. Set it to 0 in the shapes you render; set up an orthographic camera pointing along the Z axis so that only the X and Y coordinates make any difference. Actually, this is the default camera...
66,443,320
66,445,836
Error when returning pointer from method, but not when accessing the pointer directly. C++
When I do this: int main() { Student *head = new Student(); Student *second = new Student(); head->S_getStudentPtr() = second; //Expression must be a modifiable Ivalue head->S_nextStudent = second; delete head; delete second; std::cout << std::endl; return 0; } I get an error whe...
You must declare the return type as a reference to a pointer: Student*& Student::S_getStudentPtr() { S_nextStudent = new Student(); return S_nextStudent; } However, do not do this. It's very prone to abuse. A better solution would be to create a real linked-list data structure using std::forward_list's interfa...