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,992,509
66,995,793
UE4 C++ Inventory Items mutating after time
I am new to C++ and UE4. I come from a Java background. So, please be gentle here. I am currently trying to build a game that allows the player to pick up items (I know... completely unique idea...). The items are being stored in a TArray of custom inventory item objects. Each inventory item object represents the item ...
Ok! So, after scouring the interwebs for a solution I came across this webpage: https://www.programmersought.com/article/40121301538/ As I was reading through it, I came across a bit that talked about UPROPERTY() handling the GC for TArrays. I then realized that I had not added the UPROPERTY() to the TArray (I figured ...
66,992,653
66,993,052
RE2 Nested Regex Group Match
I have a RE2 regex as following const re2::RE2 numRegex("(([0-9]+),)+([0-9])+"); std::string inputStr; inputStr="apple with make,up things $312,412,3.00"); RE2::Replace(&inputStr, numRegex, "$1$3"); cout << inputStr; Expected apple with make,up,things $3124123.00 I was trying to remove the , in the recognized number,...
RE2 based solution As RE2 does not support lookarounds, there is no pure single-pass regex solution. You can have a workaround (as usual, when no solution is available): replace the string twice with (\d),(\d) regex and $1$2 substitution: const re2::RE2 numRegex(R"((\d),(\d))"); std::string inputStr("apple with make,up...
66,992,762
66,995,705
Cannot Convert From 'Initializer List' to 'Char'
#include <iostream> using namespace std; void nullTest(); struct studentType { char name[26]; double gpa; int sID; char grade; }; int main() { studentType student; studentType* studentPtr; studentPtr = &student; student.gpa = 3.9; studentPtr->gpa = 3.9; // or (*studentPtr).gpa...
In the statement: studentPtr->name[26] = { 'M','a','r','k'};, you are accessing the 27th char in the array (which is out of bounds!) and trying to assign a <braced-init_list> to that single char. That can never work. But even if you were to remove the [26] from the assignment so that you are assigning to the array it...
66,993,258
66,993,378
How to save an image in Qt without having to manually add .jpeg or .png extension?
I want to save an image to disc and the user can choose to save it as .png or .jpeg. When the FileDialog pops up if I set the image name to img.jpeg it works but if I set it to just img it doesn't save it. How can I fix it? QImage image; QString imagePath = QFileDialog::getSaveFileName( this,tr("Save File"),"", tr(...
A possible solution is to check if it has an extension, and if it doesn't then add the extension: const QStringList validSuffixes({"png", ".jpg"}) QString imagePath = QFileDialog::getSaveFileName(this, tr("Save File"),"", tr("JPEG (*.jpg *.jpeg);;PNG (*.png)" )); QPixmap pm =ui->label2->pixmap(); if (!pm.isNull() &&...
66,993,377
66,996,698
Seconds since epoch for a specific date
Currently, I have A solution and another semi-solution. The semi-solution is linked here, Get seconds since epoch in Linux but that gives the time since epoch for the current datetime. I need to have it tell me the seconds since epoch for a specified date instead. I do have a function for this, however I can't find the...
Here's the general purpose solution using the preview C++20 chrono library: #include "date/tz.h" #include <iostream> #include <sstream> long double SecondsSinceEpoch(const char* date) { //Taking in a date such as "2020-01-01 00:00:00" (Local Time) //And also be able to take in a simpler date such as "2020-01-0...
66,994,832
66,996,811
C++ Initialization by making a copy or using reference depending on the condition
І have a bool variable named do_copy. If do_copy == true, I want to work with a copy, like some_type model = input_model If do_copy == false, I want to work with a reference, like some_type& model = input_model Code that does what I want: some_type copy_model; if (do_copy) copy_model = input_model; some_type& model...
You might make the copy as part of the ternary expression: some_type copy_model; some_type& model = do_copy ? (copy_model = input_model, copy_model) : (input_model); This still requires default constructing copy_model even when do_copy is false. If your default constructor is really expensive, you might us...
66,994,909
67,028,708
Unconstrained requires-expression parameter
Can I use constrained generic types inside C++20 constraints for a concept? As an example, say I'd like to write a requirement that a candidate class T have a function func that can take an argument of any type that satisfies std::ranges::range: template<typename T> concept Foo = requires (T t, std::ranges:range s) { ...
I have learned that, no, this is not possible. The following article by Arthur O'Dwyer explains that in general, C++20 concepts cannot check mathematical quantifiers (https://quuxplusone.github.io/blog/2020/08/10/concepts-cant-do-quantifiers/) People frequently ask how to do things like this in C++20: Make a concept...
66,994,959
66,995,324
Using static constexpr member variables as template method parameters
I'm trying to simplify some template code by defining some information about the class as static constexpr members. Here's a much simplified example: template <typename _Tp> class Test { public: static constexpr bool is_array = std::is_array_v<_Tp>; template <typename U = _Tp, typename std::enable_if_t<!is_arr...
If you want that SFINAE works for a method of a class, you have to have a test based over a specific template parameter of the method (so U, in your case). If you check is_array, if depends from _Tp (the template parameter of the class), not from U. But, if you can use at least C++14, you can have template variables, s...
66,994,965
66,995,003
How to randomly generate a string each iteration?
I am wondering how to randomly generate a string per iteration. My code currently generates the same string each iteration. If I type in 3 times, then it will give me the same string 3 times. I want a different and randomly generated string each time. #include <iostream> #include <string> #include <cstdlib> /* sran...
You need to call the function at every iteration, place it inside the for loop: int main() { srand(time(NULL)); int user_input; cout << "Enter how many codes you want: "; cin >> user_input; for (int i = 0; i < user_input; i++) { string random_str = RandomString(32); //<-- here ...
66,995,218
66,995,246
exit(int) gives wrong value
I have a multi-process program that runs 4 processes that should return exit value. But when process reaches exit(int) line it actually returns other value to wait() For example: exit(1) will give value of 256 to wait() exit(3) - 768 exit(4) - 1024 and so on. I guess it returns a value in exit(int) multiplied by 256. W...
You cannot directly consume the value provided by wait as it encodes additional information in an implementation-defined manner. You must use the WEXITSTATUS macro if the process exited and/or other macros like WTERMSIG or WSTOPSIG if a signal was involved. Adapted from man 2 wait: int wstatus; w = wait(&wstatus); if (...
66,995,404
66,995,462
Identifier not found even though it's there?
When trying to compile in VS19 I keep getting the error of 'isReserved': identifier not found> Im not too sure where to go because isReserved is declared as a boolean function in the exact same file. Error Segment ScannerForIdents aScanner(inFile); int nextToken; while((nextToken = aScanner.getIdent()) == 1) ...
Given that you posted aScanner before isReserved perhaps you need to declare it beforehand Please note that you can forward-declare a function without implementing it: bool isReserved(string lexeme); at the top of the file, or in your header file.
66,996,334
66,999,987
How to deal with char array which '\0' is inserted into?
When I try to copy a struct into a char array buffer using memcpy function, '\0' is inserted into the char array. I pass the buffer pointer to a function. the content before the first '\0' is past, but the rest is lost. How can I solve this problem? I would appreciate it if you help me. here is the code, although the t...
C-string function works with nul-terminating string. if you want to handle char* with nul non terminal string, you need size (or other sentinel). MyStruct mystruct; std::string buffer {(char*) &mystruct, sizeof (MyStruct)}; Demo Notice that that way of serializing has lot of pitfall: padding (you might see random va...
66,996,916
66,997,023
C++ constexpr function to checksum an array
Is there away to achieve the behavior shown in the example (non compiling) code below? I (think I) understand why it doesn't compile given that the required calls to std::initializer_list functions are not constexpr. The goal is to be able to create an array from a constant initialiser list when an additional element ...
The issue is not the calls to the members of std::initializer_list, those functions are actually constexpr. The issue is that you are using the result of i.size() in a template parameter, but i is not a constant expression, since it's a function parameter. You can solve this by making the argument an array type, and so...
66,996,951
66,997,028
sfml does not compile anymore
I have the following basic code #include <SFML/Graphics.hpp> #include <iostream> using namespace std; int main() { sf::ContextSettings settings; settings.antialiasingLevel = 8; sf::RenderWindow window(sf::VideoMode(800, 600), "PONG", sf::Style::Default, settings); sf::Cloc...
Solved by adding the following to CMakeLists.txt (thanks @alterigel) find_package(SFML 2.5 COMPONENTS system window graphics REQUIRED)
66,997,434
66,998,369
How to add hyphens inside 32 alpha numeric strings
My program randomly generates 32 alpha numeric strings and I want to add hyphens between the characters exactly like this format 56C13783-RR1B-1B66-7685-83C9343667AE. My code before trying to add changes was previously in this format EA25D82041974B9089459223D74E84DA. #include <iostream> #include <string> #include <cstd...
I was able to solve my question with a few steps using int counter and replacing the faulty version of the hyphens code with a corrected version of it. It puts hyphens in the correct spots where I want it placed. This was the simplest one I could think of, but I'm sure you can create better ones for it. #include <iostr...
66,997,937
66,998,030
How to use templated methods to take a function as input which can be used with every signature
I have a class that has the task to run functions in an async context and therefore can take a function (or method) as input. Right now I am keeping two functions with different names to take the functions as input, because I need to differentiate between void return type and other return types. Naming both functions t...
Since C++17 you can use if constexpr. In the condtion you check if function f has return type other than void, if so, call the function and return its value. Otherwise, auto as return type will be deduced to be void - no return in false-statement. template<typename Func, typename ...Args> auto Foo(Func f, Args&&... arg...
66,998,018
66,998,060
Exception thrown at 0x7A2A93B6 (vcruntime140d.dll) in file.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD
I'm having issues while trying to get the typeid of an array. When I type typeid(*ptr[0]).name(), it works perfectly fine. but as soon as I change the 0 to a variable in a loop it gives me this error please help me! #include "Cellphone.h" #include "Electronic_device.h" #include "Laptop.h" #include "Smartwatch.h" #inclu...
You are reading uninitialized memory. First, initialize your array to zero, so that all pointers are null: Electronic_device** ptr = new Electronic_device*[100](); Secondly, you must check that the value is not null before you dereference the pointer (call *ptr[i]), for example: for (i = 0; i < 100 && ptr[i] != nullpt...
66,998,103
66,998,176
erasing from vector after remove_if, with reverse iterators: rbegin(), rend()
Consider the following vector: std::vector<int> arr = {20, 37, 11, 20, 15} I need to remove the duplicate, that is encounter more than n times (in this example n=1) The resulting vector should look like: {20, 37, 11, 15} i.e. the succeeding elements should be deleted, but not the preceding ones. I had an idea of usin...
The functor passed to std::remove_if can have a memory. Code using a functor struct remove_duplicates { std::map<int, int> seen_values_; bool operator()(int x) { seen_values_[x]++; return seen_values_[x] > 1; } }; int main() { std::vector<int> arr = {20, 37, 11, 20, 15}; arr.erase( std::remove_if...
66,998,336
66,998,463
Destructing stack object vs deleting heap-allocated object of non-final class with virtual functions
Let's say you have a derived class with virtual functions and non-virtual destructor like: class Base { public: ~Base() {} }; class Derived : public Base { public: Derived() {} virtual void foo() {} }; And let's say you create a heap-allocated object of a Derived class and delete it using delete keyword l...
When an object has automatic storage duration or is a member of a class, polymorphism need not be considered. In the code given, the lvalue d cannot reference a more-derived object. Therefore, calling Derived::~Derived is always correct and need not be warned about.
66,998,504
66,998,590
Ternary operator, if I avoid writing ' expression 2 ' it works but if I not write 'expression 3 ' it gives an error
Code #include<iostream> int main() { int a=4,b,c; a==3 ? : b=a*a ; // Works fine a==4 ? c=a*a : ; // ERROR Expected Primary expression before ; } 1st conditional statement I did not write 'Expression 2' but it will not produce error 2nd Conditional statement I did not write 'Expression 3' it giv...
This is supported in GNU C/C++ and is called the Elvis operator. It's not allowed in standard C++ (e.g. MSVC++ doesn't support it). It's described in the official documentation 6.8 Conditionals with Omitted Operands The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, it...
66,998,980
67,004,258
How to extend boost geometry union_ strategy to handle own polygon type with additional data?
I've created an application with boost geometry which defines an own polygon type with some additional data called struct taggedPolygon_t : bg::model::polygon<point_t> { taggedPolygon_t() {} std::string mask_; }; Which carries some additional information. What I want to achieve is the boost::geometry::unio...
This is frequently requested, sad thing is due to the concepts there is no way to piggy-back meta data in geometry entities (specifically, points). Points are default constructible, and are assigned coordinates using the accessor functions. This is important for the generic case: if the output geometry has an entirely ...
66,999,617
66,999,696
"No match operator==" error when using std::equal and namespace
I get compile error ("no match for operator==") when using std::equal and my classes are define in separate namespaces (proper operators are defined). This is my working example using std::equal but without namespace and there is no compile error #include <vector> #include <algorithm> struct K { int a; }; struct ...
The problem is that the library like std::equal can't find the operator== defined in global scope. You can move operator== into either the namespace where K or V is defined to validate ADL. (PS your 1st code snippet works because of ADL too.) E.g. namespace nk { struct K { int a; }; } namespace nv { struct...
66,999,647
67,000,518
Build/linker error for a C project using GoogleTest
So I have a simple template for C projects that I have created, and have used it to implement the bowling game kata to shake out the bugs. The template is for a C project using C11, and it uses GTest as the testing framework. I have got stuck with a linker issue when CMake is trying to build the test binary. The CMakeL...
Your structure basically looks like this: project main_binary (just the startup code for the main code) main_library (code which needs to be tested) google_binary main_library is then added as target_link_libraries to main_binary and google_binary. Either that, or you have to replicate the main_binary sour...
66,999,831
67,000,535
Create and print 2D board functions, using specific seed value with no repetitions
Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific. I am writing a code that has 2 functions. The first function creates or initializes a 5*5 matrix for an array with numbers from 1 - 25 in random positions. The second function prints ...
You can use a Int Array with 26 element(cause its final index is 25) then set all of the element to 0 use a while loop to try to generate a X number,if it hasnt been used(Check[X] =0), let matrix[i][j] = X and let Check[X] = 1, if it has been used (Check[X]=1) then break the while loop) And with the seed 233, I dont kn...
67,000,116
67,001,196
Is it possible to make a function always run in the same thread? [C++]
Simple Example you have two functions, foo and baz. Baz calls foo. Even baz is launched from a separate thread can you run the foo it calls in the main thread? int foo(int Z) { cout << Z; return 0; } int baz(int Z) { return foo(-Z); } int main() { foo(6); // foo is run in main thread baz(6); // ...
foo can be a wrapper around the actual implementation fooImpl. foo would figure out if it can call fooImpl directly, or if it has to use some synchronization mechanism to provide all the input parameters to a forever running thread, and trigger that thread to execute the fooImpl, and then retrieve the output (if there ...
67,000,270
67,000,446
Can C++20 using enum apply to templates?
According to cppreference, both gcc and msvc have completed the implementation of C++20 feature using enum, which means we can using-declaration with an enum: struct A { enum e { /* ... */ }; }; struct S { using enum A::e; }; But when I apply it to the templates: template <class T> struct S { using enum T::...
From the proposal: The elaborated-enum-specifier shall not name a dependent type and the type shall have a reachable enum-specifier. In your example T::e is a dependent type.
67,000,651
67,000,734
Change condition of replaced member function operator bool()
I have this struct called Status which have this member function bool(): struct Status { public: Status(); operator bool() const; private: bool ok_; //!< true if successful and false otherwise ErrorMessage message_; //!< Message with "Ok" or error }; Status::Status(): ok_(true), message_("Ok") { } ...
You can change it like this: if (!(status = CheckLength(currentIndexFrom, currentIndex, currentLexemStartLineNum)).isOk()) but why would you do this? AFAIK the operator makes the code more readable so I would keep it as it is, and only use isOK where it makes sense.
67,000,822
67,001,128
Why my "Reso"(resources) file is not recognized in Clion while trying to run OpenCV?
I'm trying to run a single program that opens a image file in Clion C++: See image: As you can see here, i have a file named "Reso" and a image named "test.png", but this code always will promt "Error reading image" NOTE: I have proven that this does work in Visual Studio perfectly, but for some reason the file is not...
When you run a binary in CLion, your application will have by default the current working directory set to where your binary is located, which is probably somewhere in your cmake-build-debug directory. In your case you expect a certain directory, because your resource file is somehwere else. You can either change your ...
67,001,019
67,001,239
Capturing frame from webcam, it return only 1 frame in opencv cv2.VideoCapture()
I'm new to image processing. I'm trying to build traffic light detection following one of papers in Python OpenCV. But I got an error I can't understand. Here is the code. # TL_Detection.py import cv2 import numpy as np def Video(): try: cap = cv2.VideoCapture(0) # cap = cv2.VideoCapture('/home...
you release your cap too early, it's in the true loop. so get it out of this loop and you program will run without any problems.
67,001,163
67,020,649
Import C++ DLL Pointers-to-functions to C#
I am working on import C++ DLL Pointers-to-functions to C#. My Code C++: class __declspec(dllexport) deviceImport { public: deviceImport(); virtual ~deviceImport(); int __stdcall init(char* deviceName); int __stdcall close(); int __stdcall getDLLVersion(char* value); private: int handle; ...
I solved my question. It might help others. Solution: [DllImport(dllLocation, CallingConvention = CallingConvention.StdCall)] public static extern int Device_setPassword(string password); [DllImport(dllLocation, CallingConvention = CallingConvention.StdCall)] public static extern int Device_getDLLVersion(int handle, o...
67,002,857
67,004,017
std::string_view complexity for constant strings
I am developing libraries with tons of static strings inside. To optimize the runtime a bit, this shall be changed from null-terminated strings (classic C-style char arrays) to pre-known-length structures, like std::string or std::string_view or custom pointer+length-pairs. std::string is well known and versatile but h...
Although std::string_view(const char*) constructor has linear complexity, it is a constexpr constructor and a string literal is a compile time constant, and optimisers are often able to perform the linear complexity at compile time in practice, making the runtime constant. In constant evaluation contexts, this is guara...
67,002,935
67,003,288
Clarification about object lifetime in destructor
Another question cites the C++ standard: 3.8/1 "The lifetime of an object of type T ends when: — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or — the storage which the object occupies is reused or released." It would seem that this means accessing members of an object from a...
The C++ Standard does seem to be just a little bit self-contradictory regarding the exact status of class members during execution of the destructor. However, the following excerpt from this Draft C++ Standard may give some reassurance that your call to the removeFromGuestList function should be safe (bold italics form...
67,002,962
67,010,671
What is a view_closure in range-v3?
In a case like this: auto pow = [](int i) {return i * i; }; auto closure = ranges::views::transform(pow); closure seems to be a view_closure. I do get that last line does not make much sense, since transform is not applied anywhere. Actually, I could may as well pipe a vector x into closure and it would both compile a...
The view_closure class template in range-v3 that is an implementation strategy for what in C++20 became the range adaptor closure object concept: A range adaptor closure object is a unary function object that accepts a viewable_range argument and returns a view. For a range adaptor closure object C and an expression R...
67,003,016
67,003,123
What does "-nan" mean and what causes it?
I know that nan means "not a number",but this code using the Gaussian elimination algorithm output "-nan" : #include <bits/stdc++.h> #include <algorithm> using namespace std; typedef long long ll; const int N=55; const double eps=1e-7; int n; struct mat { int l,c; double p[N][N]; double* operator [] (int...
It's a not-a-number value with a representation with negative in the sign bit, that your runtime has decided to show as "negative nan".
67,003,221
67,003,399
What do `()` `{}` mean in a member initializer list? What's wrong with my code that the output is not what I expect?
In my opinion, p{n} stands for this.p=n and n(a) means this.n=this.a, is this right? I already define a constructor like task1(int a,int n):a{a},n(n).... Why am I gettnig the output a=1,n=2 when I input 1,2 and suppose this.a=1,this.n=2? class task1 { public: int a; int n; int p, q; task1(int a, int n) ...
No. Thats not right. In the initializer list shadowing is a bit special. When you write struct foo { int n; foo(int n) : n(n) {} }; then it means the obvious: initialize the member n with value of parameter n. However inside the constructor, the parameter n does shadow the member of same name: #include <io...
67,003,668
67,003,828
C++ string pass by value
C++ string passing by value is puzzling me here. I'm expecting that it prints out aa ab ba bb However, it prints aa aab aba abab. Why does this happen? std::string s, ab = "ab"; test(s, 0, ab); void test(std::string s, int i, std::string ab){ if(i == ab.size()){ cout << s << ' '; return; } ...
When you use +=, you add one character to s in each iteration, so you're passing a longer and longer string to test until all the characters of ab have been appended. Perhaps it becomes more obvious if you unroll the loop: s += ab[0]; // s is now "a" test(s, i+1, ab); s += ab[1]; // s is now "ab" test(s, i+1, ab); ... ...
67,003,969
67,007,262
QT Creator defining exceptions
I want to define a simple exception but when I do this Im getting an error saying "expected class name" #include <exception> class MyException : public exception{ }; This is in a QT (https://www.qt.io/) widget application. Wont let me inherit from exception, why is this?
#include <exception> class MyException : public std::exception{ };
67,003,984
67,070,716
c++ udp broadcast. Do I need a socket to read and another to send?
I have seen many examples where they use two sockets. One to send and one to receive. But apparently both can do it. The difference that I have seen is that one is binded and another not. Example: http://www.cs.ubbcluj.ro/~dadi/compnet/labs/lab3/udp-broadcast.html
Yes you can ! However Just be cautioned that the next read or recv might read a different datagram. UDP datagrams are always discardable you can still flag your recv() with MsgPEEK or something like that see this topic here and this one may be better if your lazy here is the code from the topic struct sockaddr_in si_m...
67,004,099
68,199,091
How to implement HFP on linux with bluez?
I'd like to implement HFP on Linux. As far as I understand I need to first create SPP connection between my phone and a computer in order to exchange some setting. In BT specification, there is a spp service. is it this one what i need or do i have to use dbus? Can I use a serial communication to send the AT commands? ...
HFP in Linux is implemented as part oFono. You can refer ofono code for this. SPP and HFP use cases are different. Once install ofono, you can connect to mobile device to Linux machine then you can use below command to make call from your phone. dbus-send --system --print-reply --dest=org.ofono /hfp/org/bluez/hci0/dev_...
67,004,241
67,004,467
Not getting proper output!! Can anyone explain, what is wrong?
#include<iostream> using namespace std; class parent { public: string parnt_name; int age; }; class child:public parent { public: string chld_name; int age_child; child() { cout<<"Name of child"<<chld_name<<" and age is "<<age<<" his/her parent name is"<<parent::parnt_name<<"and age of parent is "<<parent:...
Object constructors are called upon its creation. Meaning that the child class's constructor is called in this line: child c1;. Now at this line, does it have any data? Since your not initializing the internal variables (the two integers) it will most often contain garbage values. This is why you get an output like tha...
67,004,863
67,004,922
Why would I want to implement virtual functions without implementation in an abstract class?
I am sorry but I have to ask a stupid question. I understand the benefit of implementing an abstract class as such. If I have virtual function with a basic implementation that is always called in cases when the derived classes don't have a specific implementation there is definitely a benefit, e.g. virtual void Impleme...
virtual void f(); // virtual member function virtual void g() = 0; // pure abstract member function A class with at least one pure virtual member function is an abstract class, and cannot be constructed itself, which is often desired (only non-abstract, "concrete" if you will, derive classes should be able to be c...
67,005,773
67,006,276
C++ Initializing a 2d vector by 1d vector's function
This is what I have: vector<int> A {5,4,3,1}; vector<int> B {3,1}; I want make 2d vector C to 5*5 2d vector filled in 0.0 so I tried this: vector<vector<double>> C((A.size() + 1), vector<double>((B.begin() + 2),0.0)); But this is an error I'm getting. There is no instance of a constructor with a matching C++ argument...
vector<vector<double>> C((A.size() + 1), vector<double>((B.begin() + 2),0.0)); Here you are invoking this constructor of std::vector (number 3 on cppreference): constexpr vector( size_type count, const T& value, const Allocator& alloc = Allocator()); You can see that it takes in si...
67,005,837
67,005,907
How to combine base-class explicit constructor and designated initialization in g++-10?
I have a trivial example: struct A { explicit A(int a) : a(a) {} protected: int a; }; struct B : public A { int b = 0, c = 0; }; // Attempts to get the code compiled: B b1 { A(1), .c = 2 }; // fine with clang-11 B b2 { A{1}, .c = 2 }; B b3 { .A{1}, .c = 2 }; B b4 { {1}, .c = 2 }; B b5 { .a = 1, .c = ...
You cannot. At present, there is no way to use designated initializers in a braced-init-list that also needs to initialize a base class. There's a proposal for it, but it's obviously not in C++ at present.
67,006,290
67,006,743
Why does "&& true" added to a constraint make a function template a better overload?
Consider the following two overloads of a function template foo: template <typename T> void foo(T) requires std::integral<T> { std::cout << "foo requires integral\n"; } template <typename T> int foo(T) requires std::integral<T> && true { std::cout << "foo requires integral and true\n"; return 0; } Note th...
As per [temp.constr.order], particularly [temp.constr.order]/1 and [temp.constr.order]/3 /1 A constraint P subsumes a constraint Q if and only if, [...] [ Example: Let A and B be atomic constraints. The constraint A ∧ B subsumes A, but A does not subsume A ∧ B. The constraint A subsumes A ∨ B, but A ∨ B does not subsu...
67,006,519
67,007,964
How do I save/load information onto/from my device?
I'm developing an application, but I need it to save its information onto the computer, and load it from there next time it's opened. To give the simplest example: I have an array of strings and I want to save them as a *.txt file in the application's directory. And every member of the array should be on a new row of t...
MainFrame::MainFrame() { wxFileName f(wxStandardPaths::Get().GetExecutablePath()); wxString appPath(f.GetPath()); std::ifstream inputFileStream; inputFileStream.open(std::string(appPath.mb_str(wxConvUTF8)) + "data.txt"); std::string data; inputFileStream >> data; } MainFrame::~MainFrame() { ...
67,006,646
67,006,977
Dynamic cast specification (rule) clarification
We have the general form of dynamic_cast: dynamic_cast < new-type > ( expression ) I am specifically confused about the bold part of this rule (5a): 5: If expression is a pointer or reference to a polymorphic type Base, and new-type is a pointer or reference to the type Derived a run-time check is performed: a) The ...
Fleshing out the multiple inheritance example @Peter summarized: Base1 / \ <-- Virtual inheritance here Base2 Base2 | | <-- Nonvirtual inheritance here and below Left Right \ / Derived Base1* p_base1 = new Derived(); Base2* p_base2 = dynamic_cast<Base2*>(p_base1); // Which Base2...
67,006,925
67,007,030
How to initialise custom vector type with a standard vector
I have created a sample container which internally stores in a std::vector. I want to be able to initialise the container with a std::vector. So I created constructors that take a std::initializer_list and also taking a begin and end. But I can't seem to initialise like this: const std::vector< uint8_t > vec1 { 1,2,3...
The problem here is that your iterator constrcutors are explicit. That means vec1.begin() can't be converted to a UsingVectorExample::const_iterator without you doing it explicitly like UsingVectorExample ex{ UsingVectorExample::const_iterator{vec1.begin()}, UsingVectorExample::const_iterator{v...
67,007,097
67,007,202
How to generate a unique ID using the date and time program by C ++? There is no need to use a library such as windows UUID
I want to write a C++ program that generates a unique ID without the need for a library, and the date must be represented when the ID is generated.
On Windows you can use UuidCreate.
67,007,126
67,007,326
Are you not allowed to erase a vector element from an instantiated vector?
Is it not possible to erase a vector element when I have declared it in my function instead of building it? I have tried the code below but it crashes my app at if I leave the erase in (with only a vague stack trace as output). If I remove it all is fine. I thought I understood the right way to use erase but evidently ...
Your for (int i = 0; i < 14; i++) assumes that the vector has a fixed size of 14 elements. However, each time you call erase, you are reducing the size, and a later attempt to access element 13 (say) will be attempting to access an out-of-bounds element. So, make your loop look something like this: for (size_t i = 0; i...
67,007,297
67,008,110
C++ MySQL connector execute stored procedure corrupts connection
In a MySQL Database I have a stored procedure defined by the following create statement: DROP procedure IF EXISTS `get_next_ticket_number`; DELIMITER $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `get_next_ticket_number`() BEGIN SELECT IFNULL((SELECT `number` FROM ticket ORDER BY `number` DESC LIMIT 1)+1, 1) as 'next_...
Wrapping the call in a do-while fixed the issue: do { // execute code } while (stmt->getMoreResults());
67,007,305
67,014,175
Questions about third-party library(oat++) configuration in visual studio
As a beginner, I want to use oat++ as a third-party library in visual studio, but I encountered some configuration problems. First I downloaded the source file of the oat++ project and opened it in visual studio and cmake and install. Then I created a new project in visual studio and started running the first example o...
As far as I'm concerned, the problem is you are not linking against the Ws2_32.lib library. To fix this you could try to add that to your additional dependencies tab of linker/Input settings for your project. And you could also try to add: #pragma comment(lib, "Ws2_32.lib") Best Regards, Jeanine
67,007,497
67,007,540
extern enum in header file
In my project, I have a header file containing the following lines. extern enum class options {alpha, beta, gamma, theta}; extern options P1, P2; Compilation gives me error: a storage class can only be specified for objects and functions Why? How can I rectify this? Compiler: GCC 9.2.0
extern is applied to variables to specify that they have external linkage. What you have is not a variable but an enum definition, therefore extern cannot be applied to it. What you can do is apply extern to variables at file scope of the enum type. For example, your header file would have: enum options {alpha, beta, ...
67,007,601
67,007,617
Why am I not getting a range error while accessing elements in an std::vector outside the range?
I am not sure what silly mistake I am making but I am expecting an out-of-range error in the following code but it just prints values of 0. #include <iostream> #include <vector> int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; try { for (int i = 0; i <= v.size() + 1; ++i) ...
You can't get an out-of-range error because operator[]() is just a memory offset. It doesn't throw. If you want to catch an exception, use the member function at() instead.
67,007,793
67,008,638
Expand parameter pack into tuple with tuple_cat
Godbolt link: https://godbolt.org/z/18nseEn4G I have a std::map of various types of vectors (cast to void*) and a T& get<T> method that gives me a reference to an element in one of the vectors in the map. class Container { public: Container() { auto v1 = new std::vector<int>({1, 2, 3, 4, 5}); auto v...
I would suggest using type erasure. Here is an example: #include <vector> #include <typeindex> #include <memory> #include <any> #include <unordered_map> #include <iostream> #include <experimental/propagate_const> // If no library implementation is availble, one may be copied from libstdc++ template<class T> using prop...
67,007,886
67,008,096
Fast inverse square root using fixed point instead of floating point
I am trying to implement Fast Inverse Square Root for a fixed point number, but I'm not getting anywhere. I am trying to follow exactly the same principle as the article, except instead of writing the number in the floating point format x = (-1) ^ s * (1 + M) * 2 ^ (E-127), I am using the format x = M * 2 ^ -16, which ...
It can't be done. The fast inverse sqrt is due to the floating point representation, that has already split the number into powers of two (exponent) and the significant. It can be done. With the same tricks as done for floating points, it's possible to convert your fixed point into 2^exp * x. Given uint32_t a, uint8_t ...
67,008,445
67,008,694
How to separate declaration and definition for template function with trailing return type?
I stumbled upon the same problem as in this question: Can't Separate Function Into Declaration and Definition with Trailing Return & Template, but there are no answers. Basically, I want to write the following: namespace ALGLIB_wrappers { class Linear_least_squares { public: template<typenam...
Replacing sizeof...(funcs) with sizeof...(Basis_function) seems to work with g++, but I cannot explain why... (note that your code works with clang++)
67,009,096
67,025,742
How Can I Assemble ARM and Flash to STM32 in Linux?
In this term, I have Microprocessors lectures and we're working on ARM Development with C/C++ and Assembly. For a while I've been looking for an alternative for Keil uVision which is compatible with Linux Distributions (now using Arch) and able to assemble ARM and flash, but could not find anything. The most related pl...
Be aware that Keil uses ARM's own compiler version 5 or 6 (current releases of Keil MDK support both v5 being ARM's legacy ARMCC, and 6 is based on clang/llvm). If you are following a course, and the course material is based on a different toolchain, you may encounter difficulties - or worse your tutor may not be able...
67,009,171
67,009,211
ERROR: std::thread arguments must be invokable after conversion to rvalues
I am trying to build this relatively simple code but failing with the error mentioned in the title. I've eyeballed the code a couple of times, yet failed to figure out what stupidity is causing this. Can someone please give a hint or a clue ? #include <thread> #include <iostream> #include <vector> #include <chrono> #in...
Your statement tv.emplace_back((fill_the_vec, std::ref(v2d[i]), c)); is invoking the comma operator, which evaluates its left argument and then returns its right argument. Thus, fill_the_vec and std::ref(v2d[i]) would be evaluated and discarded, and then tv.emplace_back(c) would be evaluated, which won't work because...
67,009,484
72,346,035
Link CorePrivate from Qt6
I am writing a server using QtHttpServer (from Qt6). It's time to implement chats for the system using web sockets, but it hasn't been added to Qt6 yet. I see two ways out – either use long-pulling instead of web sockets, or download the web sockets code from qt5 and add it to the project. I decided to try the second o...
It seems CorePrivate is part of the Core component so you don't need to add it in your find_package. All you need to do is to call Qt6::CorePrivate in target_link_libraries.
67,010,136
67,010,152
Have a C++ variable able to be either Class Foo or Class Bar
I am interested to write a printer to output two different formats. Let's call them txt and csv. Can something like below be implemented in C++? class Printer { public: virtual void header() = 0; }; class CSV : Printer { public: void header() { printf("csv\n"); } }; class TXT : Printer { public: void header() { p...
Instead of auto you'd want a pointer to the base class int decider(int type) { Printer* prt; if (type == 1) { prt = new CSV; } else { prt = new TXT; } prt->header(); } but instead of raw pointers and new (since you are leaking memory from a missing delete) I'd instead use smart pointers here #inclu...
67,010,171
67,056,609
How to test restart() method from Stopwatch class?
I want to test restart() method from Stopwatch class, a part of class looks like this: class Stopwatch { public: Stopwatch(); void start(); void restart(); // stopwatch reset and start ... uint64_t getTime() const; // gets the running time of the stopwatch in nanoseconds private: ... }; How to...
I used "Some programmer dude" solution
67,010,817
67,011,077
How to play sound on specific audio device with C++ on windows?
I know that winapi provides PlaySound() function, but how to select output audio device for it? I want my program to play sound on specific devices, is there some way to do this on C++ on Windows?
check this library mmeApi and here's audio streaming sample code from microsoft
67,010,881
67,010,971
Why can't I acces the virtual function through an object call?
I am trying to do an OOP simulation of using a bank Card, just for practice, nothing too complex; I'm getting a strange error. The call is a little bit silly, but i was just trying to see if "read" function works ok, not to test it's real purpose. I don't understand why I get the error below, i know that i can acces a...
"undefined reference to vtable" is compiler's way of saying "not all virtual methods are implemented". Implement all virtual members (or mark them pure) and the error will go away. BTW, virtual getCredit(); is missing a return type (probably double?).
67,011,232
67,018,199
C++ multi threading: how do I reuse threads for many "jobs"?
I'm learning c++ and was making a realtime raytracer. First I used std::thread to spread the work, but turned out starting 32 threads every frame is way slower than the actual work that needs to be done. Then I found C++ also uses threadpools to deal with that issue through std::async(): void trace() { constexpr un...
Thanks for all the comments. I ended up incorporating Ted Lyngmo's example which improved performance from 80ms to 7ms per frame using all my cores. The task struct: #ifdef __cpp_lib_hardware_interference_size using std::hardware_constructive_interference_size; using std::hardware_destructive_interference_size; #el...
67,011,485
67,011,644
Can I cause a Meyers singleton to reinitialize in forked child processes?
Say I have a meyers singleton Data& get() { static Data data = initialization_work(); return data; } that's already been used and initialized in a parent process. I then fork(2) a child process, and in the child process data may need to be different (ie, i'd like initialization_work() to rerun the first time get()...
First, will data automatically be reinitialized in the forked child? My suspicion is no Why just a suspicion? Indeed, nothing will be initialized. As @MartinYork mentions - you get a copy of the original process. That's the magic of forking - no need to initialize the world. The parent and the child both proceed to a...
67,011,794
67,011,886
When the code goes in the print_city function, the variable "code_search" reset to 0
Here's where my code freak out Ive tried to initialize in the main, in the search but nothing works, thank you in advance, and i have to kept the two functions I can't put them in the same one! so code_search is at 1 but when it goes to the print_city it goes back at 0.
As SuperStorme said, you are passing code_search by value. Try to pass it by reference: void search_city(City cities_array[], const int MAX_Cities, int & code_search){...} Passing by value, you are changing only the local variable code_search in the function scope.
67,012,043
67,012,087
How do I pass a defined in a concept reference to a template function?
I have a function: template<std::same_as<int&> T> void f(T value) {} Compiler gives me an error that I don't have a function with these arguments f(int) if I call it like this: void g() { int a; int& b = a; f(b); } Why does the compiler assume that I use a regular type and not a reference and is there som...
Unless you have a forwarding reference, the template type is never deduced as a reference type. Instead, it gets the type the reference refers to. In this case that means T is deduced as an int and that does not match int&. Instead you can use template<std::same_as<int> T> void f(T& value) {} Which forces T to be a...
67,012,144
67,012,386
C++20 Deducing the dimensions of a multidimensional array into a parameter pack
I am implementing a container in the form of a multidimensional array. I am trying to replicate std::to_array (C++ 20), a function that creates a std::array from a one dimensional built-in array, using my multidimensional array: template<typename T, std::size_t... N> constexpr mdarray<std::remove_cv_t<T>, N...> to_mdar...
Unfortunately my usual trend of Boost.Mp11 one-liners will come to an end here, since Boost.Mp11 doesn't really deal with values very well and we need to convert int[5][12] into mdarray<int, 5, 12> and there's no easy mechanism to do that with that library. Instead we just do it by hand. std::extent gives you the Nth e...
67,012,229
67,013,066
boost geometry area with a vector of pairs?
Is there any way of making boost::geometry::area work with a vector of pairs? It says here https://www.boost.org/doc/libs/1_75_0/libs/geometry/doc/html/geometry/reference/algorithms/area/area_1.html that it should work with MultiPoint. So I have called BOOST_GEOMETRY_REGISTER_MULTI_POINT - which works for convex_hull, ...
Yes it support MultiPoint. And you get the documented behaviour: So, you get area is 0, like you should be expecting. Clearly you want to adapt as an areal geometry. Let's assume your pairs are Points that form a Ring. using Point = std::pair<double, double>; using Ring = std::vector<Point>; BOOST_GEOMETRY_REGISTER_...
67,012,359
67,012,552
A way to guarantee that a bunch of derived classes have static functions that do the same thing and that are guaranteed to be named in the same way?
I know that it isn't possible to have class methods that are both pure virtual and static (see this discussion). So, I ask: is there a way to guarantee that a bunch of derived classes have static functions that do the same thing and that are guaranteed to be named in the same way? Consider the following example: #inclu...
You could use CRTP as the base class, and then have a routine that depends on the derived class having implemented the expected static function. Here's an example, and I have thunk_nums in the base class dependent on the derived class having nums, although they could have been named the same. Note that if a function is...
67,012,403
67,014,855
How to change the brightness for all three channels of the image?
I'm trying to change the brightness of an image by coverting it from BGR to LAB and changing the L parameter to L+brightness. It works to change the brightness but the output image is blue , why? void MainWindow::BrightnessSlider(cv::Mat image) { cv::Mat image2; cv::cvtColor(image,image2,cv::COLOR_BGR2Lab); ...
The main problem here is that 3-channel color images in OpenCV use BGR memory layout, while in Qt they use RGB memory layout. That's why your image shown in QLabel looks "blue". To fix the memory layout problem, you should change cv::COLOR_Lab2BGR to cv::COLOR_Lab2RGB in the second cv::cvtColor(): cv::cvtColor(image2, ...
67,012,782
67,050,439
Kotlin - Function that Writes to a Stream of Unspecified Type
in C++, there is a concept of an ostream. cout is an ostream, as is an ofstream. In this way you can define a function that takes an ostream and writes to it so that the caller can decide where he wants the function to write to. Is it possible to achieve the same effect in kotlin: defining a function that determines wh...
Kotlin (and Java) have two equivalents: OutputStream for byte streams, and Writer for character streams. These are both abstract classes, with many concrete subclasses writing to different places. To take the simpler case: If you want to write byte data to a file, you can create a FileOutputStream instance which write...
67,012,838
67,017,233
Is it possible to have each page of a Stacked Widget specified in a separate ui file
I am using the Stacked Widget in Qt Creator v4.14.2. Right now all of the items for each page reside in the mainwindow.ui file. I do not have a problem switching between pages. I am wanting to put the items for each Stacked Widget page in a separate ui file for clarity and file size reasons. I understand that there is ...
You can load as many UI files as you need using QUiLoader. Assuming the files are named page-1.ui, ... page-10.ui you could have something like (untested)... #include <QStackedWidget> #include <QUiLoader> #include <QWidget> . . . QStackedWidget stack; QUiLoader loader; for (int page_no = 1; page_no <= 10; +...
67,012,908
67,013,342
How to display the full error messages in VScode?
I've got a problem that's bothering me for a long time. I use VScode on macOS with standart clang compiller. Almost all error messages produced by the "gcc" are cut, and don't help me at all. I do not know is it a VScode thing or my compilling settings are wrong. Also, if someone could say why just using "usr/bin/clang...
The problem matcher of the task shows only the first line of error messages. GCC and Clang wrap error messages on multiple lines resulting truncated errors in the VSCode "Problems" panel and tooltips. Pass the option -fmessage-length=0 to the compiler to direct it to not wrap lines. Modify "args" in your config. "args"...
67,013,297
67,013,419
Why can't I create a temporary of this templated class with an lvalue constructor argument?
For the life of me I can't seem to create a temporary of this class, why isn't it allowing me to? template <typename T> struct Dog { Dog(T t) : tag(t) {} T tag; }; int main() { int tag = 6; Dog<int>(6); // Works fine Dog<int>(tag); // On Visual Studio I get no default constructor exists for class ...
Dog(6); and Dog<int>(6); declare temporary Dog<int>s, constructed with the value 6. Template argument deduction works fine in the first case, and the template parameter is explicit in the second. However, Dog(tag); is not creating a temporary. It's a declarator of a variable tag of type Dog<?>. In general, the parenthe...
67,013,412
67,013,753
Combine 2 functions (templated) in only one
I am trying to get a boost::hana::string by order as inserted in tuple looking by std::string_view name in an array (please check code, it is easier to understand there than in my words). I have got it, but the syntax really gets messy and lost its self-explanatory meaning, because it is necessary to call two functions...
You can pass boost::hana::string to combined() instead in order to invoke image() at compile-time with std::string_view: template <class CharT, CharT... s> constexpr auto combined(const boost::hana::string<s...>& name) { constexpr auto index = image(name.c_str()); return source<index>(); } And here's how to use ...
67,013,988
67,014,060
How can i send simple text to another computer in c++?
Basically all i want to do is have one exe file, on a main computer (windows), start listening over the net for another exe file on another computer (also windows) to send a simple string of text, in which the main computer will receive the text, display it, and then from there i'll be able to figure out what i want to...
When sending data over a network like so at a low level we use something called sockets to send a TCP message. On Windows the standard API for this is Winsock. On a Unix-based computer like MacOS or Linux you'd use Unix Sockets. I'm much more familiar with Unix sockets than Windows ones so I won't be much help to you o...
67,014,099
67,014,393
Why is the vector range constructer 10 times faster than the fill constructor?
I've tested the following two ways of filling a vector with 100'000 elements: #include <iostream> #include <vector> #include <chrono> using std::cout; using std::endl; using std::vector; using std::chrono::high_resolution_clock; using std::chrono::duration_cast; int main() { const int n = 100'000; cout << "R...
Here's the compiled code on godbolt, with gcc -O0. In the first test: the loop to fill the array (lines 49-57 of the assembly) is compiled as a simple loop, with a store to memory on each iteration. It's not well optimized (the index variable is kept on the stack instead of in a register, and redundantly moved back a...
67,014,181
67,014,254
How can I use element from deque::pop_front() safely?
I have two std::deque, I want to move elements from one to another like this: T* t = new T; q1.push_back(t); std::deque<T*> q2; q2.push_back(q1.front()); q1.pop_front(); my question is: 1: Does pop_front() release memory? if so, q2 can not visit the element. 2: Will push_back(q1.front()) do Copy co...
No standard container is aware of the data you put into it. Therefore it can't use, process or otherwise manipulate the data it stores, only store it. So if you store a pointer, the deque can't release the objects that the pointers are pointing to, since it doesn't know it's a pointer to an object. So to answer your qu...
67,014,375
67,014,861
Why does the creation of a vector storing base objects, but being initialized with derived objects fail with a deleted move constructor?
I am attempting to create a std::vector<SystemBase> class member that stores multiple systems that all derive from SystemBase. However this class has a reference and thus has no sensible default constructor: class SystemBase { public: SystemBase() = delete; explicit SystemBase(entt::registry &Registry) : Registry{R...
In C++, variables and objects of type X are actually objects of type X. They are never objects of a derived type. Pointers to base can point at derived. Derived objects have a base class subobject in them. But a vector of foo contains actual foos. In many C++ derived languages, variables of object type are actually ...
67,014,427
67,014,559
Question on C++ design pattern, pure virtual method called
I got a virtual method problem when trying code from https://en.wikipedia.org/wiki/Bridge_pattern. Error messages are: pure virtual method called terminate called without an active exception Aborted (core dumped) The code was compiled with g++ -o bridge bridge.cpp -std=c++11 Why drawing_api_.DrawCircle() called the ...
The posted code is buggy -- in particular, the Shape class is holding a reference-to-a-DrawingAPI-object: class Shape { [...] protected: const DrawingAPI& drawing_api_; }; ... but the object that it is referencing is a temporary that gets destroyed as soon as the CircleShape constructors inside main() return. One ...
67,014,470
67,014,528
How do I call derived functions from base variables in C++?
I am currently working with a a class, and three other classes that derive from that base class. The base class is supposed to be essentially abstract, so that I can call the virtual function of a base class, and have it do the expected function of the derived class. My end goal is to do something like this: class Car ...
There are multiple problems with the code you show. One is that you attempt to dereference the uninitialized instructionPointer variable. Another is that *instructionPointer = ins; leads to object slicing. Instead create the IType object dynamically and return a pointer to that object: Instruction *decode(string binary...
67,015,092
67,015,171
Perform shell command (ls) on other directroy using exec() in cpp
I want to cout the directories/files at the home directory using exec system call. What I am unable to understand is where can I specify on which directory ls should be applied. Here is what i have tried: cout<<execle("/bin/ls","bin/ls",NULL); It prints the files in the current directory. I treid passing path as envir...
Try using execvp() cout << execvp("ls", ["ls", "/home/username"]) execvp takes as its argument the command you are attempting to execute, and as its second a list including the command and a list of arguments given to the command being executed.
67,015,369
67,017,191
Is there a way to display cpp map in a specific way
I need to display the following seats to users and be able to reserve them and cancel the reservation. class luxaryBus { public: std::map<std::string, int> seats{ {"1A", 0}, {"1B", 0}, {"1C", 0}, {"1D", 0},{"1E", 0}, {"2A", 0}, {"2B", 0}, {"2C", 0}, {"2D", 0},{"2E...
std::map uses comparison operator< to compare keys in the map. However, the problem is that strings are being compared lexicographically, so both "1A" and "10A" are smaller than "1B". But you can use a more complicated map: std::map<std::pair<int, char>, int> in which key is number and character. Here number will be co...
67,015,497
67,015,539
Pass vector by reference, modify elements c++
In c++ I pass a vector of 'Node' objects by reference to a function—addUnique—which either increments the 'count' property of an element in the vector or appends to the vector. const char inputString[] = "aaccgtgacac"; int main(int argc, const char * argv[]) { std::vector <Node> nodes; for (char input: inputSt...
Your loop where you increment the count, is iterating the Nodes by value: for (Node used: list) { ... } This makes a copy of each node, then you modify the copy and throw it away. Instead, make the loop use references: for (Node& used: list) { ... } Now you will modify the values in the vector, instead of the copy.
67,015,530
67,015,764
Makefile cause fatal error: No such file or directory
I have problems with my makefile. Running it cause the error: make g++ -c -o vcd_converter.o vcd_converter.cpp In file included from vcd_converter.cpp:2: vcd_converter.h:16:10: fatal error: defs.h: No such file or directory 16 | #include "defs.h" | ^~~~~~~~ compilation terminated. make: *** [<built...
Well, let's look at the compile line make prints: g++ -c -o vcd_converter.o vcd_converter.cpp Now let's look at your rule: %.o: %.c $(DEPS) $(INCLUDE) $(CC) -c $(INCLUDE) $(CFLAGS) $^ -o $@ Given that we know the variable INCLUDE and CFLAGS are set, what can we understand from the fact that the compile ...
67,015,545
67,016,337
Decimal to binary, then convert to string matrix
Before you read ahead or try to help, this question is regarding my homework so the requirements to this question will be very specific. I am writing a code that takes a user input between 0 and 511 and converts it into a binary number. Then the program will replace all the 1's in the binary number with T and all the 0...
Regarding the formatting in three lines you can do something like: if (i%3 == 0 && i != 0) cout << std::endl; cout<<stringArr[i]<< " "; % is the modulus operator that return the reminder of the integer division, you want to add an end line every three (skipping, I am assuming, the first one) std::endl ...
67,015,877
67,015,957
Why calling the function isn't ambiguous in SFINAE?
I am using SFINAE to check whether some class has 'print()' function or not. The code works but why calling has_print() is not ambiguous? class cls { public: void print() { std::cout << "some text" << std::endl; } }; template<typename T> auto has_print(T tt) -> decltype(T().print(), std::true_type()) {...
It could match both of them. In overload resolution, the 1st overload wins the 2nd one which takes ellipsis parameter. A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsis conversion sequence.
67,016,050
67,016,348
"Error: Implicit function declaration" for one function but another in the same header file
I want to use two functions func1 and func2 from the following C++ header file in a xyz.c file. I included the C++ header file in xyz.c (C file). func1 appears before func2 in xyz.c, but/and the complier only complains about func2 by saying "Error: Implicit function declaration". Is there anything wrong with the C++ he...
If __cplusplus is defined, your header becomes: extern "C" { int func1(...); }; extern "C" int func2(...); So far so good. If it's not defined, it becomes: int func1(...); The minimal fix is: #ifdef __cplusplus extern "C" #endif int func2(...); The proper fix is to have following at the beginning of the header,...
67,016,076
67,121,619
How to create a single process mutex within C++?
So I'm reading about monitors vs mutexes and finding mentions that suggest that monitors are faster mutexes because they don't lock system wide but rather only across the threads of a given process. Is there some way in C++ to accomplish or simulate this? Edit: I'm curious now what the difference is between system wide...
The answer by @Alex Guteniev is as accurate as one can get (and should be considered the accepted answer). It states that the c++ standard doesn't define a system wide concept, and that mutexes for all practical purposes are per process i.e for synchronization between threads (execution agents) in a single process (an...
67,016,522
67,016,624
how to detect when mouse leaves the window win32
I am creating an application with the win32 api and I have a boolean isLeftClickPressed which is set to true when I receive a WM_LBUTTONDOWN message. when I receive a WM_LBUTTONUP message I set it to false. this works fine, however if I hold down the left mouse button and move my cursor out of the window and release my...
Call TrackMouseEvent and check for WM_MOUSELEAVE
67,016,991
67,030,619
How to set QOS in CycloneDDS C++?
I am using CycloneDDS C++ version, trying to set following QOS to the writer DDS_HISTORY_KEEP_ALL, DDS_DURABILITY_TRANSIENT_LOCAL, DDS_RELIABILITY_RELIABLE I am trying to set Qos to data writer, in dds publisher dds::domain::DomainParticipant local_participant(domain::default_id()); dds::pub::Publisher local_publisher(...
Check this out Error is because QoS is not set properly you can try below code, Creating a DataWriter with your own QoS dds::domain::DomainParticipant local_participant(domain::default_id()); dds::pub::Publisher local_publisher(local_participant); dds::topic::Topic<DDSData::myData> topicMyData(local_participant, "DDS")...
67,017,277
67,017,319
Trying to print first 10 even natural numbers in C++
#include <iostream> using namespace std; int main() { int n = 1; // initialising n with 1 int num = 2 * n; do { cout << "value =" << num << endl; n = n++; } while (n <= 10); // intents to print "value = 2n for all 'n' from 1 to 10 return 0; } It just keeps on displaying 2. n is getting incremente...
You print num but you increment n Incrementing n with n = n++ is fishy, it should be n++;, n = n + 1; or n += 1; So you actually want this: #include <iostream> using namespace std; int main() { int n = 1; //initialising n with 1 do { cout << "value =" << n * 2 << endl; n++; // or 'n = n + 1;' } whil...
67,018,395
67,018,812
How to preserve references in the return type of a templated function (c++)?
I have a struct called TypeHolder which is basically a thin wrapper around a type T: template <typename T> struct TypeHolder {}; Now, I want to create a function which takes an object of any type, and casts that object to T if the object is a TypeHolder (with T being the type of TypeHolder). If not, the function shoul...
If you just want to retrieve the type, you might use structure and (partial) specialization: template <typename T> struct UnderlyingTypeIfTypeHolder { using type = T; }; template <typename T> struct UnderlyingTypeIfTypeHolder<TypeHolder<T>> { using type = T; }; Demo If you want to dispatch code, I would go wi...
67,018,488
67,018,735
How to read string with spaces, until a '\r'?
I want to read a long string, and split it into smaller ones, where each new row of the big string is an entry for the smaller ones. However, I only want it to break at '\r', and not at spaces. This is a sample code of what I'm doing right now: std::vector<std::string> m_list; std::ifstream input("data.txt"); std::stri...
You where definitely on the right path, you actually just need to skip the direct string stream operation. This should work fine: std::vector<std::string> m_list; std::ifstream input("data.txt"); std::string str; while (std::getline(input, str, '\r')) { m_list.push_back(str); ...
67,018,650
67,018,874
Is passing a char or short by reference or pointer slower than passing by value?
I've always heard it said that passing by reference instead of value (copying) is more efficient for types larger than int or long long because it avoids copying. When an argument is passed by value the value is pushed onto the stack where the operations are done in the function, but the way I see it is that when you p...
First of all, in nearly all cases 'faster' and 'slower' cannot be determined by some reasoning. It just requires measuring time for different situations. Having said the above let's get to the chase. Here are a few important points: no matter what you do compiler is free to change anything as long as it is not changin...
67,018,666
67,019,049
cmake error libcurl not found, but libcurl4 is installed
I am trying to compile the Springlobby version 268 client from the open source game TA-Spring. However the newest version (271) compiles just fine. But when I try to compile version 268 I get the CMake-error: CMake Error at /usr/share/cmake-3.18/Modules/FindCURL.cmake:163 (message): CURL: Required feature libcurl is ...
Version 268 incorrectly calls find_package (src/CMakeLists.txt:127): FIND_PACKAGE( CURL REQUIRED libcurl ) The last parameter libcurl is interpreted (according to find_package documentation) as the element of COMPONENTS list, and in case of FindCURL.cmake it is treated as PROTOCOL/FEATURE specification. Obviously, lib...
67,018,767
67,019,298
Clang tidy doesn't work for StaticConstantCase
I'm trying to use clang-tidy (10.0.0) to check the formatting on my file: #include "blabla.h" static const int status = 1000; static const int STATUS_REPLY_TIMEOUT_MS = 100; namespace foo { The .clang-tidy file I'm using is: Checks: '-*,readability-identifier-naming' CheckOptions: - { key: readability-identifier-n...
StaticConstantCase only applies to static local variables. Use GlobalConstantCase for namespace-scope static variables.
67,019,075
67,019,340
Invalid operands to binary expression error (missing const) in std::sort: Why does specifying the compare operator solve it?
Considering: #include <algorithm> #include <vector> struct A { double dummy; bool operator<(const A& a) { ///Here I am missing a `const` return dummy < a.dummy; } }; int main() { std::vector<A> a; a.push_back({0.9}); a.push_back({0.4}); std::sort(a.begin(),a.end()); return...
Why does specifying the compare operator std::less<>() solve the error? Interestingly enough, it's only when you use std::less<void> (std::less<>) that it compiles. std::less<A> does not. std::less<A>::operator(): constexpr bool operator()( const T& lhs, const T& rhs ) const; The std::less<void>::operator() has a sl...
67,019,677
67,020,183
Can I use char variable without lock in the multi-threading case
As c/c++ standard said, the size of char must be 1. As my understanding, that means CPU guarantees that any read or write on a char must be done in one instruction. Let's say we have many threads, which share a char variable: char target = 1; // thread a target = 0; // thread b target = 1; // thread 1 while (target ...
TL;DR is it OK to not use neither mutex/lcok nor std::atomic No In general, it's not ok to assume things. If you need guarantees for something, then make sure you have them. This is closely related to a common logical fallacy. Just because you cannot imagine why something could be true, that does not mean that it's t...