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
67,186,376
67,186,456
Passing ‘const ...’ as ‘this’ argument discards qualifiers
I'm stuck. When trying to add a new element to the vector of strings inside a struct via the iterator I get this error about const qualifier: error: passing ‘const std::vector<std::__cxx11::basic_string<char> >’ as ‘this’ argument discards qualifiers [-fpermissive] 175 | p->children.push_back("New child"); The code...
You got the iterator p from an unordered_set; the contents of unordered_set are immutable (to avoid violating invariants), and the iterator returned is a const view of the elements to ensure that. You could mark children as mutable so it can be mutated even when the Concept_tree is const (since it's not part of equalit...
67,186,504
67,192,507
Lua - C++ object metatable returns nil
I have just started delving into Lua, and I learnt that C++ object properties could be accessible through metatables. I am trying to access such an object's functions in a game's script: "GameLib". It is available in Lua as a global variable, but getmetatable() returns nil: -- example usage elsewhere in the scripts: lo...
From the Lua 5.4 Reference Manual: 2.4 Metatables and Metamethods: Every value in Lua can have a metatable. By default, a value has no metatable, but the string library sets a metatable for the string type So there are cases where values, even userdata have no metatable. In fact that's default. 6.1 Basic Functions:...
67,186,627
67,186,672
Reference Reassignment
I have a general C++ question. Lets say I have this code: int& GetInt() { int* num = new int(); return *num; } int numCopy = GetInt(); In this situation, what happens to the returned reference? This example uses a simple data structure so it doesn't really matter, but in cases where the returned data is more ...
In this situation, what happens to the returned reference? It goes out of scope at the end of the full expression and you have now leaked the memory you acquired in GetInt. You've made a copy of the value the reference refers to, but the original object, and the memory it occupies are no longer accessible. If you ha...
67,186,844
67,186,858
syntax error: missing ')' before identifier 'a'
I am attempting to build a dll on Visual Studio 2019 (for using in Unity later) from a c++ sdk project that was previously compiled with gcc. I am getting some syntax errors while compiling and for the following function: static inline uint8_t MyFunction(const uint64_t *__restrict__ a, const uint64_t *__restrict__ b) ...
__restrict__ is specific to gcc and clang. The MSVC equivalent is __restrict. There is no 'general way' to resolve differences between compilers. You have to deal with them on a case-by-case basis.
67,188,195
67,192,773
Index retrieval as a function of the boost::multi_index::sequenced<> offset
I am in a situation where I am forced to use a std::vector container as my underlying data structure. I'm trying to exploit boost::multi_index::sequenced<> to shadow the vector offset, and provide a mechanism for richer data queries. I really don't want to unnecessarily copy all the data from one container to another. ...
This is extremely brittle and I wouldn't recommend going to production with such code, but since you asked for it: Live Coliru Demo #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/random_access_index.hpp> #include <iostream> #include <string> #includ...
67,188,649
67,188,740
Deduction of templated class member in templated class
I am taking advantage of C++17 new feature to deduce the class member type in a templated class. Specifically, I am doing this: #include <array> #include <iostream> template <std::size_t N = 0> class A { public: using Array = std::array<int, N>; A(const Array& arr) : myArr{arr} {} A() = default; void...
Deduction guides do not do partial matching. Synthesized or not. In the first case, the compiler synthesizes a deduction guide. template<std::size_t N> A(std::array<int,N>const&)->A<N>; Once you pass any template parameters, deduction guides are not used. No partial matching. See https://en.cppreference.com/w/cpp/lan...
67,188,716
67,188,894
How to write CPP template functions that is recursive on argument array length
Say I want to write a function arrfill<N> that fills an array of length N. Below is the template implementation I tried. template<typename T> bool arrfill(T arr[0], T v){;} template<size_t N, typename T> void arrfill(T arr[N], T v){ arr[0] = v; arrfill<N-1>(arr+1, v); } int main(int argc, char const *argv[]) ...
You are bitten by argument decay. Argument decay means that int arr[N] is fancy talk for int* arr. The N is utterly ignored. On top of that, arrfill<N-1> is a call to a template function whose first argument is a size_t (or compatible). Your T arr[0] is an overload that takes as its first template argument a type. S...
67,189,219
67,189,339
Why do I have to free 2D array twice to avoid memory leak?
I am running into a memory leak problem when allocating a 2D array. But I could not understand why the memory leaks. My reasoning is that at Note A, I have already freed allocated memory, since data_[0] == data_, why do I have to do the free at Note B? class Matrix { public: Matrix(int r, int c) { this->rows = r;...
What you post there isn't really a 2D array, it's a 1D array-of-pointers (data_), and then you allocate a separate array-of-ints for each element of the first array (so data_[0] is an array of c ints, data_[1] is an array of c ints, and so on). Given that, it's natural that you'll have to do one delete[] in your destru...
67,189,666
67,190,631
Using "System::Windows::Forms::DialogResult::OK" to go back to previous form
I have two separate forms list_of_students_page and testing. I have a button in list_of_students_page which on clicking opens testing form. I have created a button in testing form to move back to list_of_students_page. Upon running the button in testing form, it works when it is clicked twice. I am using C++/CLI Window...
You have: testing_f->ShowDialog(); if (testing_f->ShowDialog() == System::Windows::Forms::DialogResult::OK) Having the standalone ShowDialog call doesn't really make sense and does explain why you have to hit the button twice (it's actually different instances of the dialog, it just appears so quickly you can't see th...
67,190,153
67,191,223
SFML: Draw only once and render forever
I am trying to write an application in C++ to draw static 2D pieces of stuff on the screen. The guides on SFML say to do the following while (window.isOpen()) { sf::Event evnt; while (window.PollEvene(&evnt)) { /* Handle events */ } window.clear(); window.draw(/* 2D stuffs go here */); ...
You can use a sf::RenderTexture to draw your static objects. Then you create a sf::Sprite that uses that texture and use it to draw them at once. sf::RenderTexture bgTex; bgTex.create(windowWidth, windowHeight); bgTex.draw(your_object_1); bgTex.draw(your_object_2); // the rest of the static objects bgTex.display() // i...
67,190,671
67,190,740
Nested array of structs - how do i properly assign a value to struct members?
I have struct Voice { static byte mode; //Some other stuff }; byte Voice::mode{}; //Static member defined outside of struct declaration and struct DataPacket { DataPacket() : sequencer{}, voice{}, tempdata{} {}; Sequencer sequencer; Voice voice[4]; Tempdata tempdata; }; I want to assign on...
You have define mode as static byte mode;... So there's space allocated for exactly one of them in the entire program. Perhaps mode should not be marked as static?
67,190,709
67,192,250
Equivalent of .NET's MemoryMarshal in C++ (Arduino)?
I am new to Arduino and C++ development coming from C# so likely am missing so fundamental understanding. Kindly answer accordingly. Context I am writing an Arduino sketch whereby I form a Http GET request in order to receive data from a Web API. In receiving the response, I am able to read the stream into byte data[] ...
byte is not a native C++ type, the Arduino environment creates it using a typedef, it is actually a uint_8 (unsigned 8 bit integer) type. This is also the underlying type of a char, so you don't actually have to do anything. A byte array and char array are already the same data type, they're just labelled differently. ...
67,191,083
67,191,326
Creating a function template for double and std::complex that does not require specialization
As a learning exercise, I was trying to create a function that computes a Hermitian conjugate in-place. It should behave like a simple transpose when all entries are real, and hence should work with double. I know that I can specialize separately for double, and it's doable in this particular example. But, I imagine th...
You can use if-constexpr if you have c++17. This essentially creates different specializations, without the need to write separate functions. #include <complex> #include <type_traits> const size_t ZERO = 0ul; template <class value_type, class container_type = value_type*> auto hermitianConjugate(container_t...
67,191,133
67,193,836
Does dynamic dispatch come into play when I have a concrete type?
Lets say I have a class Interface which provides pure virtual functions. Now lets say I have two classes Concrete1 and Concrete2. I instantiate them like this: Interface* impl = createConcrete1orConcrete2(); // randomly select Concrete1 or Concrete2 Concrete1* concrete = new Concrete1(); impl->foo(); concrete->foo(); ...
Compiler has to do the dynamic dispatch, but following the as-if rule, it might devirtualize the call if it know the final dynamic type as optimization. Here indeed, with new Concrete1();, dynamic type is known. But for Concrete* ConcreteFactoryCreate(), it wouldn't (Concrete might still have derived classes) unless th...
67,191,275
67,191,444
QListView - how show child items
I have a very simple tree data structure: A, B and C are some vectors, whose elements are respectively A0-A3, B0-B1 and C0-C2. Now, I'm trying to show in a QListView (let's call it listview1) the elements A B and C, and in another QFileView (listview2) the child elements of the element selected in listview1. What I ha...
You must use the setRootIndex() method: void MainWindow::on_listView_activated(const QModelIndex &index) { ui->listView_2->setRootIndex(index); }
67,191,753
67,191,874
Cramming two objects in a single byte in C++
class A { char c; // c represents a value varying from 0 to 2^7-1 (I don't need a bigger range) bool b; // b is a boolean value } Class A uses 2 bytes. However, as c is never meant to get a value greater than 2^7-1 (as specified in comments), one of the bit of the byte of c could be used to represent the boolean...
You can use bitfields to give a specific bit size to a member. #include <iostream> struct A { unsigned char c : 7; bool b : 1; }; int main() { std::cout << sizeof(A); } Demo
67,191,933
67,224,700
Operations of the elements of arrays in a function' c++
Can I operate the elements of an array in a function(in the parameter)? float f(i, u, v) { if (i == 1) { return (u - v); //example of the returned value } if (i == 2) { return (u + v); } } int main() { int i; float x[3],y1,y2,h; x[1]=1;//value of the first element of x[m] ...
I would recommend you to try to compile your code, the compiler will give you some important hints as of what is wrong. Here is the code compiled online. To make it compile i changed it to this: #include <iostream> using namespace std; float f(int i, float u, float v) { if (i == 1) { return (u - v); // ex...
67,192,391
67,201,080
C/C++ vscode extension show error while there is none
I have this program which compiles with the C++ 20 standard. g++ -std=c++2a test.cpp #include <iostream> #include <variant> using namespace std; int main(int argc, char *argv[]) { variant<int, string> v{"hello"}; cout << get<string>(v) << endl; } I have the C/C++ extension installed, I changed the s...
As mentioned in the comment, the problem came from the cpp_properties.json. Even after changing the settings, I found multiple hidden .vscode folders in the project with cpp_properties.json inside them with the wrong standard specified. I manually changed the cpp_properties.json files and it was ok.
67,192,496
67,192,835
QuantLib Error: “QuantLib::Handle<QuantLib::TermStructure>” cannot convert to “const QuantLib::Handle<QuantLib::YieldTermStructure> &”
I'm working with QuantLib 1.19 in C++. When I try to pass a TermStructure Handle to create a new IborIndex, I get the error in the subject. My code looks like: #include <iostream> #include <ql/quantlib.hpp> #include <vector> int main() { using namespace std; using namespace QuantLib; Date today(21, Apr, 2...
The constructor parameter specifically requires you to pass a Handle<YieldTermStructure>. You however are passing a Handle<TermStructure> which is an incompatible type and that is why you get the error. I don't know the library but I expect you can correct it by declaring Handle<YieldTermStructure> crv_handle(crv); Th...
67,192,498
67,196,335
Why are floating point types and integer types are treated differently in C++
Recently I came across the fact that floating point types and integer types are treated quite differently in C++. Example 1 from: Why are floating point types invalid template parameter types for template functions? template <double x> double func() { return x; } is invalid, whereas with int it is valid. Example 2 f...
The underlying issue is that 1 and 2 always have different values, regardless of how those values are represented. 3.111111111115 and 3.111111111114 might or might not have different values on different systems, depending on how the values are represented, and might have different runtime values on the same system, dep...
67,192,530
67,192,682
How to let a C++ function return different types?
Look at this code: #include<iostream> enum class DataStructure{stack,queue}; template <typename T> T foo(DataStructure ds){ if(ds == DataStructure::stack){ return 1; } else if(ds == DataStructure::queue){ return 3.14F; } } int main(){ std::cout<<foo(DataStructure::stack); } Obviously it does not c...
If the passed in enum is a compile-time constant you can pass it as a template parameter and make the function return different types accordingly. #include<iostream> enum class DataStructure{stack,queue}; template <DataStructure T> auto foo(){ if constexpr (T == DataStructure::stack){ return 1; } else if co...
67,193,273
67,196,949
Is there a built-in function to calculate nCr in C++?
In python 3.8, there is a built-in function for calculating the number of combinations (nCr(n, k)): >>>from math import comb >>>comb(10,3) 120 Is there any such function in C++?
The beta function from the mathematical library can be used to express binomial coefficients (aka nCr). double binom(int n, int k) { return 1/((n+1)*std::beta(n-k+1,k+1)); } Source. This function is available either with C++17 or as part of an implementation of the mathematical special functions extensions for C++...
67,193,627
67,193,676
What is the best way to pass parameters to a callback function? (C/C++)
I'm learning SDL right now and I'm trying to use timer callback function. The function SDL_AddTimer() offer me only one argument to pass through but I want to pass different types of variables into it. (https://wiki.libsdl.org/SDL_AddTimer) I think of one solution is that I can declare a structure containing all of my ...
I think of one solution is that I can declare a structure containing all of my variables but I'm not sure if it is the best way to do so. Yes this is the correct and best way to pass parameters whenever you are presented with a callback that accepts void*. Then cast back to the struct type from inside the callback. S...
67,193,705
67,193,772
Initialize stdarray with size depending on const class member
Can somebody explain to me why the following results in the error "non-type template argument is not a constant expression" and how to deal with it? #include <array> class Test { public: Test(int n) : num_requests(n/2){}; const int num_requests; void func() { std::array <int,num_reques...
Use a template "argument" like this: #include <array> template <int n> struct Test { void func() { std::array <int,n/2> test_array; }; }; int main() { auto t = Test<10>{}; t.func(); }
67,194,360
67,200,695
MFC WaitForSingleObject and CCriticalSection - how to use?
I'm currently diving into a legacy code base that makes heavy use of MFC classes. It uses CCriticalSection as mutex, and WaitForSingleObject to 'lock' that mutex. The code roughly looks like this: struct Foo { static CCriticalSection mutex; void doSomeWriting() { mutex.Lock(); … mutex.Unlock(); } ...
Application Verifier [...] flags the WaitForSingleObject() call and complains about a handle inside mutex being NULL. Application Verifier is correct. That's exactly what's happening. It's pretty obvious, too, why this is happening. It's far less obvious, why Microsoft decided that it were a good idea to force CCriti...
67,194,417
67,194,748
sorting index of vector of vector based on size
I have a vector of vectors and I want to sort it by the size of each vector. I want to put the index of the sorting vector in another vector and I don't want to change the main vector. how could I do that? I want to use the sort function but I can't find any parameter in the sort function that determines I want to sort...
Building a sort table based on the content of another container requires either a custom functor or a capturing lambda. The latter is shown below. #include <iostream> #include <algorithm> #include <vector> #include <numeric> int main() { std::vector<std::vector<int>> tree; // fill tree with whatever // b...
67,194,419
67,194,642
Is the std::function object itself thread safe? If no, what ways can I make it thread safe?
I have an std::function object that many threads access. Threads can can change the function it points to (through its copy constructor) and can call the function it points to. So, my question is, that in what ways is the std::function object itself thread safe? I'm not talking about the function it points to/calls, I'...
A function object is like all other objects. Just data, and there is no built in mutexes in std::function. If you want to protect the function with a mutex you yourself would need to create a mutex and use when interacting with function (pointing it to something else or calling it). #include <functional> #include <mute...
67,194,531
67,194,611
Compilation error declaring a unique_ptr member in a class
It is some kind of factory lambda. The class to be instantiated by the lambda receives a reference to another class in its constructor. If the latter declares a unique_ptr member, a really long error is thrown: #include <memory> #include <string> struct A { std::unique_ptr<int> foo; }; struct B { B(const std:...
You can't copy a unique_ptr. But you can move it: #include <utility> // ... registerType<B>("lala", "p1", std::move(a))(); or prevent the std::decay when using make_tuple from happening: return [args = std::tuple<Args...>(std::forward<Args>(args) ...)]() mutable -> auto
67,194,689
67,196,523
Why can views::reverse transform a non-sized_range into a size_range?
In [range.sized#1]: The sized_­range concept refines range with the requirement that the number of elements in the range can be determined in amortized constant time using ranges​::​size. template<class T> concept sized_­range = range<T> && requires(T& t) { ranges::size(t); }; The standard states that obt...
The requirement is amortized constant, not always constant. take_view<...> produces counted_iterators. So reverse_view<take_view<...>> produces reverse_iterator<counted_iterator<...>> counted_iterators can always be subtracted: you just subtract the count. So reverse_iterator<counted_iterator<...>> can always be subtr...
67,194,927
67,195,253
Vector of pointers vs Vector of objects vs Vector on the heap
What is the use case of the following examples:- vector<Object> collection; vector<Object> *collection = new vector<Object> vector<Object*> collection;(creating the object on the heap) When do I need to create a vector of pointers over a vector of objects and doesn't the vector (or any STL container) allocate the ...
Typically, std::vector<Object> collection; // Always use this if possible You should always look to storing your objects directly as values in a std::vector. The vector stores its contents dynamically on the heap. This, std::vector<Object>* collection = new vector<Object>; // NEVER use this I can't think of any reaso...
67,195,147
67,205,049
Directly accessing entries of armadillo-matrix by memory-pointer (memptr) does not work after matrix is modified
I have a problem where I want to access certain entries of an armadillo-matrix "M" by a pointer in a struct (or class). After initializing M I set the pointer in the struct. By dereferencing the pointer I can see it has the right value (the first entry of M - or M(0,0)). Then I change M to M * M. But now dereferencing ...
The operation M = M * M in Armadillo is a matrix multiply (not an element by element multiply). So storing the intermediate calculations of M * M directly into M would be problematic. It would overwrite existing data in M that is still needed to complete the M * M operation. It's probably safe to assume that Armadillo ...
67,195,357
67,195,806
What is a better way to code in C++, a public variable or a variable whose scope is limited to a function?
I have a std::vector object in my class, vector<float> foo, this gets modified by two different class functions function1 and function2. Currently, I have made the variable public, and both the functions have direct access to the variable without me explicitly passing. But it occurred to me that I can write the code li...
Programs get complex. In order to modify a piece of code without introducing bugs, you need to either get lucky, understand the code, have every bug be tested and eliminated, or a combination of the 3. Programs act on some set of "state"; variables, threads, OS and computer state. If you do not know what state a progr...
67,195,625
67,198,433
BNF (with custom modification) Parser using Spirit
Using the bnf parser from here, I am trying add a field to be read as an attribute of List. So what I have done is to change: using List = std::list<Term>; to struct List : public std::list<Term>{ int number; } For example: <code> ::= <letter><digit> 34 | <letter><digit><code> 23 So those numbers are read as attr...
I would favour composition over inheritance (for many reasons). So struct List { std::list<Term> terms; int number; }; With BOOST_FUSION_ADAPT_STRUCT(Ast::List, terms, number) Then modifying the rule from _list = +_term; to be _list = +_term >> qi::uint_; Is enough to get what you described: Liv...
67,196,456
67,196,608
how to pushback a 2D vector
let's say I have a vector storing vectors of strings. std::vector<std::vector<std::string>> MyVec = { {}, {} } I want to use anything equivalent to .push_back(X) such that the vector will now look as following: { {X}, {} }. Does anyone have an idea for a way to solve this?
MyVec[0].push_back(x) by @MikeCAT worked.
67,196,467
67,196,483
How to create a struct constructor which assigns values to constant struct parameters?
I'm trying to create a structure (or class, doesn't matter) whose constructor assigns values to the struct's constant parameters. I.e I don't want to change any variables of a Point object after its creation. Following code obviously doesn't work, because the constructor tries to change the value of a constant. struct ...
Use member initializer list: struct point { const int x; const int y; point(int _x = 0, int _y = 0) : x(_x), y(_y) {} };
67,196,501
67,197,037
Add subdirectory as a library to CMakeLists.txt
TLDR: I have two projects(Project A & B) using CMakeLists.txt, both build executables and they work separately. Now, I want to use Project A as a library in Project B, let's call this Project AB. How do I do it? Current Directory Structures : Project A rootA |- bin | |- |- build | |- |- external-includes |- C...
As done in this example, modify rootAB/rootA/libraryA/CMakelists.txt, replacing add_executable (library_A main.cpp library_A.cpp ....) with add_library (library_A library_A.cpp ....) and in rootAB/libraryB/CMakelists.txt, add target_link_libraries(library_B library_A)
67,196,958
67,197,199
How to accept user input in a class when using private variables?
I have created a class called User: has 4 private variables a get_input() and print_output() function a main function where I am accepting user input, where I have to initialize a new set of variables to pass the user input to the get_input() function My question is: Do I have to define a new set of variables? Or is ...
Followed the advice of Sam Varshachik and changed my program accordingly: You should input the variables first, then pass them to the class's constructor, when creating an instance of the class, which will use them to construct its private members #include <iostream> #include <vector> #include <string> class User { pri...
67,197,033
67,197,540
Mifare 1K writing data in two blocks
hello i'm working with APDU command for writting and reading a RFID card . I can read from the block num 2 and write a data of 16 bytes . but i have a problem in writting a longer data so how can i mange i have tried to write in two blocks but it doesnt work. this the way that i have implemented my code in the operatio...
You need to send each block separately. The Mifare Classic Write command will only write one block at once. See Section 12.3 of the Card's Data sheet So RFTransmit the write command for the first 16 bytes to the first block and RFTransmit the write command for the second 16 bytes to the next block.
67,197,152
67,197,295
Should the deallocate function be called when an error occurs in the STL allocator allocate?
try { node = allocator.allocate(LIST_BASIC_UNIT); } catch (...) { allocator.deallocate(node); throw; } Should I call deallocator when an exception occurs in the STL allocator allocate?
You cannot deallocate anything, because there is nothing to deallocate. If allocate() throws, then it stops before it could return a pointer and before node could have any value assigned. So assuming that node is invalid before try block (it should be), you have no valid pointer to pass to deallocate(). If given implem...
67,197,633
67,215,894
Is there a way to suppress the fmt range formatter for a user defined class?
I have a simple class that has a tostring() method: class MyClass { public: std::string tostring() const; static iterator begin(); static iterator end(); }; Although I'm using the fmt library now, this code is ported from code that did not, so many of the legacy classes implement a tostring() method, a...
Here are the options (which you've already discovered): Don't include fmt/ranges.h. Provide a full specialization of formatter. Note that if you have implemented a generic formatter for all types that have tostring you can do (2) in just one line (https://godbolt.org/z/cW3WzaP6f): template <> struct fmt::formatter<My...
67,197,965
67,198,016
C++ checking if a part of string is consistent with another part of string
I am creating a program which can decide if user's direction of movement is in a clockwise direction (N E S W). For example I have variables: string correctDirection = "NESW"; string UsersDirection = "WS" //User's direction: west, south UsersDirection isn't in the clockwise direction, because it would has to be "SW", ...
Assuming string here means std::string, you can use find() to check if one string is contained in another string. if (correctDirection.find(UsersDirection) != std::string::npos) { // UsersDirection is contained in correctDirection }
67,198,027
67,626,834
Multi touch rotation QT issue
I'm currently trying the capture the orientation Azimuth (rotation of finger) of multi touch inputs in Windows when a user touches a specific dialog. I'm using the QT C++ framework. I'm testing everything with the surface laptop 3. The issue is that I'm always getting a value of 0 when I try using QT: According to QT d...
The Issue is actually caused by 2 bugs in the current Windows Version. 1.Windows generates wrong vallues: std::cout << "Orientation" << touchInfo.orientation<<std::endl; //is 0 or 1 because of Windows internal driver issues. 2.QT for (auto const& elem : touch.touchPoints()) { std::cout <<"Rotation:" <<elem.rot...
67,198,044
67,198,136
Converting Vector Arrays to Numbers
I created a function that converts numbers to arrays in C++. Due to this creation, I also created the opposite which converts arrays back to numbers: int convertToNumber(vector<int> nums) { int length{ nums.size() }; int Pow{ length - 1 }; int factor{ pow(10, Pow) }; int tempNum{}; int result_num{}...
With every iteration of your loop, you are updating Pow - but not factor; and it is factor that's used in your loop, not Pow. Remember that when you assign an expression to a variable, that expression is only evaluated once, and the result of this single evaluation is what the variable is set to. In other words, the po...
67,198,506
67,199,259
How to declare a variable whose type is the generics of another object?
Consider the following piece of C++ code: int main(){ MyObject<int> obj; foo(obj); } template <typename T> void foo(T& objct){ ... } In foo, the type of objct will be MyObject<int>. I would like to create a variable in foo() whose type is the objct's generics, in this case, int. Is there a way to do that? Thank yo...
What about defining foo() using a template-template parameter? template <template <typename...> class C, typename T> void foo (C<T> & objct) { /... } or also template <template <typename...> class C, typename T, typename ... Ts> void foo (C<T, Ts...> & objct) { /... } to be more flexible and accept also type with...
67,198,685
67,199,121
What is the correct way to get the binary representation of long double?
Here's my attempt: #include <iostream> union newType { long double firstPart; unsigned char secondPart[sizeof(firstPart)]; } lDouble; int main() { lDouble.firstPart = -16.5; for (int_fast16_t i { sizeof(lDouble) - 1 }; i >= 0; --i) std::cout << (int)lDouble.secondPart[i] << " "; ...
What is the correct way to get the binary representation of long double? Same as the way of getting the binary representation of any trivial type. Reinterpreting as an array of unsigned char, and iterating each byte is typical and well defined solution. std::bitset helps with the binary representation: long double ld...
67,199,196
67,199,462
If unary operators have near the highest priority, then why the order of evaluation of # and ## operators is unspecified?
Simple question: if unary operators have near the highest priority, then why the order of evaluation of # and ## operators is unspecified? Relevant to both C and C++. C11 (6.10.3.2 The # operator): The order of evaluation of # and ## operators is unspecified. C++, N4713 (19.3.2 The # operator): The order of evaluati...
Chapter 19 in the C++17 standard is titled "Preprocessing directives". It explains how the preprocessor works. As the name suggests, the preprocessor is processed before the rest of C or C++'s rules. So operator precedence does not apply; these are not operators resulting in expressions. The preprocessing "operators" #...
67,199,413
67,199,843
Embeded spv shaders throws error while running program
I'm trying to include the spv shaders of my hello triangle program in the executable by adding like there. When I run the program I get the following assertion, throwed from debug_heap.cpp: Expression: is_block_type_valid(header->block_use) So there's my code: Shaders.h: #pragma once const unsigned char triangle_fra...
You are delete[]ing static variables. That is invalid thing to do. Passing an arr[] is something like passing a pointer. If you are confused about C arrays (which is understandable), then try using std::arrays instead.
67,199,573
67,199,652
Getting error while printing a link list in C++?
I have written the following link list append, prepend and print methods for LinkedList: class Node { public: int data; Node *next; Node(int data) { this->data = data; } }; class LinkedList { private: Node *header; Node *tail; int size; public: LinkedList() { ...
append() is not initializing the n->next member to NULL. You should do that initialization in Node's constructor, eg: class Node { public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; // <-- add this! } }; Alternatively: class Node { public: int ...
67,200,087
67,200,171
how to set a int32 value at some index within an m128i with only SSE2?
Is there a SSE2 intrinsics that can set a single int32 value within m128i? Such as set value 1000 at index 1 on a m128i that already contains 1,2,3,4? (which result in 1,1000,3,4)
If SSE4 available, use __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8) If you are limited to SSE2, you need to split it to two calls of __m128i _mm_insert_epi16 (__m128i a, int i, const int imm8) return _mm_insert_epi16(_mm_insert_epi16(a, 1000, 2), 0, 3); to set 1000 on lane 1 of a interpreted as vector o...
67,200,435
67,200,565
C++ object of abstract class type "mazeGenerator" is not allowed: pure virtual function "olcGameEngine::OnUserUpdate" has no overrider
So since im trying to learn c++ i have been followin onelonecoders tutorial, however i am stuck. The class that i made "mazeGenerator" will not be instantiated. other questions like mine have as solution using const on the onUserUpdate function however, this has not worked, I've had other problems that i was able to fi...
I think that the problem is that the function you wrote in the derived class, onUserUpdate, should be OnUserUpdate - with a capital O. In addition, add the override keyword before the function implementation. Change virtual bool onUserUpdate(float fElppasedTime) { ^^^^^^^ into this bool onUserUpdate(float fElppasedTim...
67,200,709
67,200,961
Guard clause causes arduino program to hang
I have a program on the Controllino Automation Maxi (Arduino Mega) that uses a guard clause in an if statement. The only thing is that, if the clause evaluates to true, and the return is executed, the Controllino restarts. I'm not sure why. #define CHILLER_TEMP_UPPER_THRESH 16.0 #define CHILLER_NOMINAL 8.0 if (c...
return returns from the calling function or method. break breaks out if a while, do, or for block. An if or else block ends at the closing brace, if there's an opening one. the return actually exits the loop() function Correct. Be happy you got the warning. And your Arduino doesn't hang. The end of loop is just the s...
67,201,027
67,201,257
what happens if you create a variable length array and compile using g++
Following code compiles fine since g++ allows it , but will it cause undefined behavior ? Or my code will work fine ? what does it mean that c++ standard disallows variable length array if no error is generated on using it ? #include <iostream> using namespace std; int main() { int x; cin >> x; char abc[x];...
GCC documents its support of VLAs here (emphasis mine) Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. CLANG documentation too follows suit but mentions clearly that the standard doesn't accept (emphasis mine) GCC and C99 allow an array's size to ...
67,201,375
67,201,415
Why does the value of this static variable not change?
obj.num has 2 different values but the value of y doesn't change. Does this have to do with initialization vs. assignment? It's something I can't quite wrap my head around. class A { public: int num; A(int num): num(num) {} }; int get_number(int x) { A obj = A(x); static int y = obj.num; return y; ...
Static local variables are defined once and only once for a function, when the function is first called. Once it's defined and initialized it will never be redefined or reinitialized. To modify the value of any variable, static or not, one must assign to it.
67,202,331
67,214,883
Why do I have to define a hash function for each namespace as the unordered_set?
I wanted to make a hash function for a class I am writing and I wanted to make the hash function a friend of the class so that I didn't have to write an unnecessary getter method. To do that I followed the accepted answer in this SO post. But I wanted to be able to insert the objects into either std::unordered_set or b...
You can reduce the clutter a long way, by using Boost's ADL-enabled customization point hash_value: class Vec { private: std::vector<int> v; friend size_t hash_value(const Vec& v) { return boost::hash_range(begin(v.v), end(v.v)); } friend bool operator==(const Vec& lhs, const Vec& rhs) { ...
67,202,534
67,203,764
C++ why int rvalue reference changed in this example?
#include <iostream> using namespace std; int&& a(int&& b) { cout << b << endl; //output 5 return std::move(b); } string&& d(string&& e) { cout << e << endl; //output abc return std::move(e); } int main() { // your code goes here int&& b = a(5); cout << b<< endl; // output 0 string&& f ...
Quoting Remy's answer from https://en.cppreference.com/w/cpp/language/reference_initialization#Lifetime_of_a_temporary. "- a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full...
67,202,744
67,212,666
Why does copying to portaudio input buffer with memcpy is creating noise?
I'm just trying to copy the input buffer of portaudio in a callback function. Thats my callback: static int recordCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, ...
The approach is true but I couldn`t specify the frame size correctly Instead of this: memcpy(&circularBuffer[data->write], inputBuffer, 1024); // 1024 = FRAME_SIZE This will be better: memcpy(&circularBuffer[data->write], inputBuffer, 1024*sizeof(float)); // Assuming 1024 = FRAME_SIZE because of: typedef float SAMPLE...
67,202,936
67,203,022
Why doesn't CreateWindowW accept an ATOM as the lpClassName?
In the MSDN description of CreateWindowW(), the window class name (lpClassName) can either be a text string or an ATOM type. I intend to use the predefined COMBOBOX several times, so the specific ATOM seems to be the better solution. ATOM MyRegisterConnectClass(HINSTANCE hInstance) { WNDCLASSEXW wcon; wcon.cbS...
The 1st parameter of CreateWindowW() takes an LPWSTR (wchar_t*) pointer, but RegisterClassExW() returns an ATOM (unsigned short) handle instead. lpClassName Type: LPCTSTR A null-terminated string or a class atom created by a previous call to the RegisterClass or RegisterClassEx function. The atom must be in the low-or...
67,203,349
67,203,449
Why does inheritence force inflation of otherwise zero sized structs?
Why does a zero-sized array force a struct to be zero sized when an otherwise empty struct has a size of 1, and why does inheriting from a non-zero-sized struct cause the struct to be inflated to the size of the base type? Compiling via GCC 5.3.0, in case any answer depends on the c++ spec. #include <iostream> struct ...
The ISO C++ standard does not recognize the possibility of a "zero-sized array". That should give you a compile error on a strictly-conforming implementation. While yes, there are a lot of permissive implementations that allow it, their behavior is not governed by the C++ standard. Similarly, the ISO C++ standard does ...
67,203,446
67,203,851
How do I implement this code into a dialog type resource file?
// Epvolume.rc -- Resource script #include "resource.h" #include "windows.h" #include "commctrl.h" // // Dialog box // VOLUMECONTROL DIALOGEX 0, 0, 160, 60 STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU | DS_SETFONT CAPTION "Audio Endpoint Volume" FONT 8, "Arial Rounded MT Bold", 400, 0, 0x0 BEGIN LTEXT "Min"...
You need to open the resource file as text rather than with the designer. In solution explorer select the resource script file and hit ctrl+alt+0. You can then cut-and-paste text as usual. Most of the time when simply laying out a new dialog it is easier to use the designer but editting it as text is much easier when ...
67,203,572
67,203,676
How to pass other variables as args along with std::ostream in a function in C++?
I was working on a function which looks like so: inline std::ostream& mvUp(int n,std::ostream& ss){ char u[8]; sprintf(u,"\033[%dA",n); ss<<u; return ss; } and using it like so: std::cout<<mvUp(1); however it shows error: std::cout<<mvUp(1); | ^_____too few args in function call ^___...
Modern C++ code uses std::string, and other classes. This makes implementing this kind of an overload trivial. #include <string> #include <sstream> inline std::string mvUp(int n) { std::ostringstream o; o << "\033[" << n << "A"; return o.str(); } Then, everything will work automatically: std::cout<<mvUp(...
67,203,968
67,204,041
Initializing list in sub class
I'm trying to use the constructor of an abstract class. I have to store a reference to a class Swiat in abstract class Organizmy. Organizmy has sub class Zwierze (which is an abstract class, too), then another sub class of Zwierze, Czlowiek. (Organizmy (abstract) >>> Zwierze (abstract) >>> Czlowiek). I'm trying to init...
You need to initialize the member reference Czlowiek::s in the member initializer list of the constructor like this: Czlowiek::Czlowiek(Swiat& swiat) :s(swiat), Zwierze(swiat, 'A', 5, 4, polozenie) {}
67,204,239
67,204,291
C++ waiting for process to finish multiple times?
Help me correct my confusion, I have a job running in bg with pid = 3 I want to check if it has finished every 10 sec (non blocking) and print hello once and stop; But someone claimed the following: this won't work as status can be consumed only once. Even if you stopped after first run, your check isn't right. you s...
I think your code should work. You're not using the status argument, so that doesn't matter. You only have to check status if you need to distinguish different ways of the process ending, such as by a signal versus normal exit. For instance you can use WIFSIGNALED(status) to tell if it exited due to a signal, and you ...
67,204,323
67,214,609
How to adapt a custom polygon type in boost geometry
I am trying to use boost geometry algorithms with my own custom polygon type. But I getting compiler errors (in Visual Studio 2019 Windows 10). I have simplified what I am trying to do into the following code. In my_custom_polygon.hpp #include <boost/geometry.hpp> #include <boost/geometry/geometries/geometries.hpp> us...
First thought reading the title... Oh boy: here we go again :) Fiddling with it for a while (and cleaning up a little), I found that the cause is that ring_{mutable,const}_type::type needs to be references for this algorithm. This is making me think that earlier adaptations I made were less-than-optimal and leading to...
67,204,412
67,204,436
Convert char aray to a floting point value
so I have some code that looks a little like this where the file "float" is a file with a float value FILE* f; float a; f = fopen("float", "rb"); char buffer[sizeof(float)]; if (fgets(buffer, sizeof buffer, f) == NULL) break; so how would i convert the information from buffer to a?
You can use strtof() from the header cstdlib. char* end; a = strtof(buffer, &end); if (*end != '\0' && *end != '\n') { /* handle error : invalid character exists */ }
67,204,633
67,213,806
Serialize multiple text files using boost C++
Is it possible to serialize multiple text files using boost? As of now, I have a system in place to read a text file in normally as seen below: std::ifstream readFile(afile); while (afile) // While reading file { getline(afile, input); // Reads file, stores it in input. vecTest.push_back(input); // Gets words...
Archives are structured streams. They already organize different objects serialized to the same archive. So here you could easily just: using File = std::vector<std::string>; File f1{100, "file 1 line"}, f2{200, "file 2 line"}, f3{300, "file 3 line"}; { std::ofstream ofs("ondisk.txt"); boost::archive...
67,205,312
67,213,528
Serialization of Boost c++
To serialize files, how would I do this? Would I need to create a function to loop through file names and serialize that to one file?
The clean answer for Boost Serialization would be std::ofstream readFile("Categories.txt"); { boost::archive::text_oarchive ar(readFile); ar << vec; ar << another_object; ar << yet_another_object; } // note destructs `ar` readFile.close(); Note that you should make sure the archive is complete before ...
67,205,644
67,205,688
How to Delete Dynamic Memory allocated in Class Constructor using destructor
I'm trying to deallocate the memory of an object using destructor. this memory was allocated on the declaration of the object. the code snippet below is a comprehensive version of the program I'm making, but it explains my problem. I know that the problem is coming in deallocation via destructor but I have no clues wha...
Your problem is in these lines: firstname = new char[10]; lastname = new char[10]; firstname = "HelloMaria"; lastname = "SomethingVe"; First you set both firstname and lastname to point to newly allocated char arrays, which is fine... but then you immediately change them to point to statically-allocate...
67,205,703
67,206,786
How to optimize variadic template specializations?
Suppose you have the following struct to concatenate two templated structs: /// concat.hpp template<typename...> struct concat_struct; // concat_specialization.hpp template<std::size_t... m, std::size_t... n> struct concat_struct<$CLASSNAME<m...>, $CLASSNAME<n...>> { using type = $CLASSNAME<m..., n...>; }; templa...
You don't need to explicitly write out a specialization for each $CLASSNAME. You can just add a template template parameter to the specialization, and this will get deduced automatically: template<template<std::size_t...> typename C, std::size_t... m, std::size_t... n> struct concat_struct<C<m...>, C<n...>> { using...
67,205,789
67,205,806
what is this dynamic object creation * []
What does this mean? The following is a snippet from here class HashTableEntry { public: int k; int v; HashTableEntry(int k, int v) { this->k= k; this->v = v; } }; class HashMapTable { private: HashTableEntry **t; public: HashMapTable() { t = new H...
t = new HashTableEntry * [T_S] This creates an array of pointers to HashTableEntry. It creates T_S counts of them. Perhaps it is clearer if written like this: using HTEntry = HashTableEntry*; t = new HTEntry [T_S];
67,205,906
67,206,992
(C++) How do I use libraries when compiling for windows on linux?
I can already cross-compile some simple applications using x86_64-w64-mingw32-g++. However, I cannot find out how to find libraries for my project (in my case I need to use SDL2 and SDL2_image). I know how to install these libraries already (sudo apt install libsdl2-dev libsdl2-image-dev), but apt search does not show ...
What you are looking for is the M Cross Environnement: https://mxe.cc/ It is a set of makefiles able to download and cross compile a selection of popular libraries for windows on linux. By default it builds static libraries, such that you ends up with .a libraries that get merged into the final .exe, meaning you don't ...
67,206,003
67,206,462
Backtracking problem similar to Knight-Tour-Problem
I am trying to solve a similar problem to the Knight-Tour-Problem. The problem: A knight is placed on the upper-left square of a chess board. You are given a vector of numbers(the numbers represent the squares of the chess board, as numbered from left to right, from 1 to 64). The knight has to get to those squares in ...
If the squares are visited in order, this is easy; work out how to get from a to b. Basic pathfinding. Then concatinate. If the number of squares is smallish, just do the above for every permutation. Sort cost of a to b for all pairs (b to a is identical). Then solve travelling salesman to find shortest route. Assu...
67,206,472
67,206,867
Linux API C++ Programming
I'm pretty green when it comes to the world of C++ programming, but I've recently dove headlong into it and am enjoying the learning process. I've been curious about the Linux side of things though. Throughout my career, I've mainly used Windows environments, but Linux exposure was still there to some degree. My quest...
Linux is the kernel, a linux based operating system is much more than that. To interact with linux itself you use system calls, then, on top of that you have the GUI, which can be either X server (the historical choice) or Wayland (the new standard). Both works slightly differently and have different APIs. It is usuall...
67,207,255
67,207,598
Is there a way to copy and paste data while simultaneously increasing a number in that data each time?
Basically I have in my program - team[0].game[2] = loadvar[1]; team[0].game[3] = loadvar[2]; team[0].game[4] = loadvar[3]; team[0].game[5] = loadvar[4]; team[0].game[6] = loadvar[5]; team[0].game[7] = loadvar[6]; team[0].game[8] = loadvar[7]; team[0].game[9] = loadvar[8]; team[0].gam...
Simply don't copy + paste, rather use loops to do the incrementing numbers, e.g. for int v = 1; for (int t = 0; t < 5; ++t) { for (int g = 1; g <= 12; ++g) { team[t].game[g] = loadvar[v++]; } } I've kept game indexed from 1-12 as in your question, but I suspect you might mean to index from 0-11. ...
67,207,362
67,207,854
loop or code for user wrong input until correct input c++
I am new to c++, and I was assigned to create a calculator and ask for the user input and calculate the numbers. I also have to create a code for when the user inputs the wrong number, the program will ask the user to input the right number. How do I create a code for when the user enters the wrong input, it repeats th...
A very simple approach is to set a flag: bool done = false; while (!done) { done = true; int choice = UI(); if (choice == 1) { // etc ... } else { cout << "Entered wrong input, please select option 1 - 4\n"; done = false; } } Another option is to offload that logic in...
67,207,827
67,223,428
Thread pool in C++ not using references from args
I am trying to get a thread pool to run a method were the arguments are passed by reference. The method I want to run is: void Foo(const std::vector<std::string> &arg1, std::vector<int> &arg2, int size) {//modify elements of arg2} I am submitting this function to a thread pool: Pool.submit(Foo, arg1,arg2,size); ... te...
According to std::bind documentation: The return type of std::bind holds a member object of type std::decay<F>::type constructed from std::forward<F>(f), and one object per each of args..., of type std::decay<Arg_i>::type, similarly constructed from std::forward<Arg_i>(arg_i). Thanks to decay, the arguments are "stor...
67,207,837
67,207,921
C++: Recursive Bisection Algorithm Keeps Returning 0
I am trying to implement a Bisection Root Finding Algorithm from scratch, and the equation I am passing it is x^2 - 42 = 0. My code keeps giving the output "The root of 42 is 0 within an error of 1e-05. ", meaning that the recursion stack of my bisection algo keeps returning 0 for some reason. The code is below: #incl...
Other problems with the code aside, you need to actually do something with the result of solve. Usually this means returning the result from solve directly until you reach the base case and return that: double solve(double a, double b, double epsilon) { c = (a+b)/2.0; if(abs(f(c)) < epsilon) { return ...
67,208,232
67,208,266
How does dereferencing the pointer is changing the value in this code snippet?
Can someone explain what is happening here? #include "iostream" int main(int argc, char const *argv[]) { unsigned long var = 0x04030201; unsigned char* ptr = NULL; ptr = (unsigned char*) &var; ptr[2] = 0x05; std::cout << std::hex << var << '\n'; return 0; } Output: 0x4050201
You're not only dereferencing the pointer, you're updating the value as well. ptr[2] = 0x05; updates the value at 3rd octet. So, for a starting value of (0x) 04 03 02 01 it gets modified like (0x) 04 05 02 01 ^--------- ptr[2] To add, from C11, chapter 6.3.2.3, [...] When a pointer to an object is c...
67,209,168
67,209,235
Executing C++ function not working when using integer value from variable but works by directly giving integer
I seem to be having a issue where I have a function that is not working when giving an integer through a variable but the function works perfectly by directly giving integer when executing function. I've done a similar thing in C++ a few times now and have had no such issue before. Sorry if I did not explain too well. ...
Board(n) is read as Board n; -> definition of n of type Board (which hides previous int n;). it doesn't create a temporary. You probably want: Board board(n); To keep temporary, you might do Board{n};
67,209,211
67,209,399
How do you use std::jthread::get_stop_token()?
I'm confused how std::jthread::get_stop_token is designed to work, because it seems to have an inherent race condition. Namely, the executing thread can't simply call std::jthread on itself (as in this example) because it has no guarantee that the std::jthread object is actually constructed by the time that it begins e...
It appears from the example from here that get_stop_token is actually not meant to be used by the client code. It is called behind the scenes by the std::jthread and passed to the function called by std::jthread. It appears it is the way it's got to be done #include <thread> #include <iostream> void f(std::stop_token...
67,209,255
67,210,241
Cast to derived class without unique_ptr
Background I am creating a Cpp parser using Bison and Flex and I stumbled upon a problem: In my parser, I require a vector of base class objects, let's say shapes. Depending on which derived class an object has, I need to access different members. Thus, my intend was to store unique_ptr in the vector. Then upon access,...
The polymorphic way would be (replacing non-copiable std::unique_ptr by std::shared_ptr): class Shape{ public: virtual ~Shape() = default; virtual void draw() const = 0; }; class Circle: public Shape { int r; public: explicit Circle(int r): r(r) {} int get_r() const { return r; } void draw() c...
67,209,686
67,209,935
What is wrong with my binary search code?
#include<iostream> using namespace std; void bi(int k,int l,int r,int arr[]){ int m=r-l/2; if(arr[m]==k) { cout<<"found at"<<m; } if(arr[m]<k) { bi(k,m+1,r,arr); } if(arr[m]>k) { bi(k,l,m-1,arr); } } int main(){ int n; cout<<"enter size of array"...
The "bi" in "binary" comes from splitting the interval in two equally large intervals. Your code isnt doing that. To make it work it is not stricly necessary to have both same size, but it affects the resulting complexity depending on which side the result is. Also I am not sure if your intervals actually converge. Thi...
67,209,981
67,417,400
Weird error from Visual C++: No default constructor for promise type
Suppose I want to use coroutines with C++20 and restrict the promise type to accept only functions getting one argument of type int &. I write the following code: #include <coroutine> struct task { struct promise_type { promise_type(int &) {} task get_return_object() { return {}; } std::suspend_never ini...
This seems to be a problem of IntelliSense and should work fine. To resolve the intellisense error, a constructor can be added just for IntelliSense: #ifdef __INTELLISENSE__ promise_type(); #endif
67,210,102
67,212,602
OR-Tools C++ VRP solving from assignment with parameters problem
I'm trying to solve a vehicle routing problem with an initial assignment, and it seems that either I'm doing something wrong with setting the search parameters, or the model reaches a local minimum and returns a solution before reaching my desired time limit. I suspect the former of the two options, but I don't see wha...
Known bug. You need to close the model with the parameters before solving. And you should use search_parameters = DefaultRoutingSearchParameters();
67,210,116
67,210,614
how to calculate 2 ** 128 with c++?
I'm trying to calculate 2 ** 128 with c++, but it overflows, and I get a value of 0. any ideas on how to calculate this?? I also need to get it on a terminal, but iostream and stdio.h do not support one I tried called __int128. #include <cstring> int main(){ unsigned __int128 a = 2; for(int i; i < 129; i++...
For calculating big numbers it is recommended to use Boost multiprecision library #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::cpp_int; using boost::multiprecision::pow; int main() { cpp_int num = boost::multiprecision::pow(cpp_int(2),100); std::cout << "This is a big number: " << n...
67,210,278
67,223,469
How do I make a class method a coroutine?
How do I make a class method a coroutine? Here's a small example. Here I am trying to create a coroutine from a class method, but the compiler throws the following error: error: unable to find the promise type for this coroutine 52 | std::vector vec = co_await awaitable_func1(); How do I properly set up coroutine_tra...
Putting aside the ethics of returning void, the following changes are needed to make GCC compile this: You're passing the wrong Coroutine type as the *this parameter. It needs to be a reference: struct std::coroutine_traits<void, Coroutine&, int> { final_suspend must be noexcept: std::suspend_never final_suspend() n...
67,210,597
67,254,709
How to compile/use header unit modules under CLang C++?
It is said in docs that modules support in CLang is partial. I'm using CLang under Windows 64-bit from recent release of LLVM 12.0. I successfully managed to use regular modules, (that you import through import modulename;). But I haven't managed to create and use header unit modules, those that you import through impo...
Finally I managed to solve almost task above. Instructions below are for Windows 64-bit, most recent CLang from LLVM 12.0 release (which you can get here) and most recent MSVC Community Build Tools 2019 v16.9.4 (which you can get from here). Note. This answer is for CLang only, I also wrote similar answer for MSVC. I s...
67,210,802
67,436,390
libcurl FTP-Download incomplete in the Unreal Engine
I am currently trying to download a File from a public git-Repository using curl in my Unreal C++ Project. Here is the code I'm trying to execute that I derived from the FTP-Example: // This is in the .h file struct FFtpFile { FILE* File; const char* Filename; }; void FtpFetch(const std::string URL, const char...
I didn't manage to get it working in the end (I suspect it's an Unreal-Related Bug), but I found another way using the included Unreal HTTP Module: FString Path = ... // Create the Callback when the HTTP-Request has finished auto OnRequestComplete = [Path](FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasS...
67,210,928
67,211,221
parallel programming in OpenMP
I have the following piece of code. for (i = 0; i < n; ++i) { ++cnt[offset[i]]; } where offset is an array of size n containing values in the range [0, m) and cnt is an array of size m initialized to 0. I use OpenMP to parallelize it as follows. #pragma omp parallel for shared(cnt, offset) private(i) for (i = 0; i <...
This code: #pragma omp parallel for shared(cnt, offset) private(i) for (i = 0; i < n; ++i) { ++cnt[offset[i]]; } contains a race-condition during the updates of the array cnt, to solve it you need to guarantee mutual exclusion of those updates. That can be achieved with (for instance) #pragma omp atomic update but a...
67,211,182
67,211,535
std::nested_exception and polymorphism - Is this the best that can be done?
std::nested_exceptions are nice when all you want to do is calling what(), but accessing the interface of other exception types gets ugly. Let us suppose I have two exception classes which store some additional information: /* CODE BLOCK 1 */ class ErrorI : public std::runtime_error { public: ErrorI(int a_integer) ...
With the help of std::exception_ptr, you might do something like: void print_exception(const std::exception_ptr& eptr, int level = 0) { try { std::rethrow_exception(eptr); } catch (const ErrorI& e) { std::cerr << std::string(level, ' ') << "exception: " << e.what() << ": " << e.inte...
67,211,341
67,212,619
How to return a value from a coroutine using co_return?
In the code below, I am trying to return from a coroutine std :: vector . The problem is that only the result of the std::vector<int> get_return_object() is returned from the coroutine. When the co_return statement is executed, method void return_value(std::vector<int>&& value) is called, which fills the vector return...
std::vector<int> is not an awaitable type, so it can't usefully be the return object of a coroutine. If you add some tracing, you can see the order of operations going wrong. get_return_object needs to return something that can be given a std::vector<int> later. E.g. if all users of Promise never suspend: struct Promis...
67,211,855
67,245,222
Is tbb::concurrent_bounded_queue::size thread unsafe?
Source has following comment: // Return the number of items in the queue; thread unsafe std::ptrdiff_t size() const { return my_queue_representation->size(); } But then I looked at internal impl, and it all seems to be thread safe(operations are loads of std::atomic and then some substraction). std::ptrdiff_t size...
It is thread-safe in the sense that the behavior is well-defined by the C++ standard, i.e. has no race conditions as defined in the standard. It is not thread-safe in the sense that the result is an atomic snapshot of the queue, i.e. is not a sequentially consistent implementation. Allowing a negative size was a delibe...
67,212,389
67,227,789
OpenCV VideoWriter issue crashing on iOS - info.backendFactory.empty() in function 'open'
I'm using cv::VideoWriter from OpenCV 3.5.2 class to read a file and write it into another file, with a lower FPS rate. However, when calling cv::VideoWriter videoWriter = cv::VideoWriter(); videoWriter.open( outputFilePath.UTF8String, cv::VideoWriter::fourcc('I', 'Y', 'U', 'V'), 15, cv::Size(1920,...
I figured it out. For iOS, looks like you need force the Backend used for video writing. Therefore, using videoWriter.open( outputFilePath.UTF8String, cv::CAP_AVFOUNDATION, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 15, cv::Size(1920, 1080) ); Worked for me. Relevant here is the cv::CAP_AVFOUNDATION api at...
67,212,696
67,215,340
glutpostredisplay() equivalent in winapi
I am following this article to render a video onto a texture using OpenGL and winforms using C++. I have changed the code in the renderer as follows. But the glutPostRedisplay(); is not working. The same logic works well when I am creating a OpenGL window and rendering over there. But does not seem to work well in winf...
glutPostRedisplay only works with a "glut"-window. (glutCreateWindow). You have to use a Win-API function to invalidate the client area of the window (e.g. InvalidateRect): InvalidateRect(HWND, NULL, TRUE);
67,213,026
67,213,075
Is there a function to remove an element from a vector without shifting it in the c++ stdlib?
If I use vector.erase() such as std::vector<int> n = { 3, 5, 6, 7 }; n.erase(n.begin() + 1); vector will shift all the elements after the element removed down. Is there a function in the C++ standard library that will not shift the elements? Like putting the back element at the removed element and pop back?
There isn't anything built in, but it's trivial to do yourself. std::vector<int> n = { 3, 5, 6, 7 }; // create vector n[1] = std::move(n.back()); // move last element to removal location n.pop_back(); // remove unneeded element.
67,213,194
67,220,440
GCC Devirtualization and Inlining only first Interface
i found a problem in the following code: It looks like GCC can only devirtualize the first Interface I_Udc. The Interface GCC is not able to devirtualize the second interface I_Uac. If I write I_Uac first, the I_Uac call will be inlined. Here is the code at compiler explorer: https://godbolt.org/z/z6WEoznfW class I_Uac...
The best/only way I know to guarantee devirtualization is to not virtualize in the first place. A slight change to your classes allows for a CRTP approach, though it's a tad uglier, especially when referring to the base class types, it's entirely doable. #include <cstdio> template <typename DerivedT> class I_Uac { pu...
67,213,877
67,214,160
c++: private inheritance ambiguous call
In the code below the public method Base2::f() is expected to become a private member of the Derived class however the compiler complains about ambiguity. The question is on the basic understanding of inheritance. I appreciate if someone can help to shed some light on it. #include <iostream> template <typename TDerive...
Jarod42 rightfully posted the comment The check of visibility (public/private) is done after the selection, and so it is ambiguous Here is a relevant section from cppreference Member access does not affect visibility: names of private and privately-inherited members are visible and considered by overload resolution,...
67,213,880
67,214,278
An analog for Qt resource files?
I need something similar to the resource system that Qt has. Instead of writing the full path to the files and dragging them with the program, I would like to create a single file like Qt does and enter relative file paths. I can't use Qt in my project, and using the. rc files that Visual Studio provides is very comple...
You might need the .resx Resource Files. A way to create this is to open Visual Studio: Right-click your project Select Add | New Item Select Resources File Give it a name (e.g. Resources) Click Add You will now have a Resources file in your project with the name you provided, and it should auto-open the resources ed...
67,213,961
67,214,029
How can I make this structure non-repetitive?
I need to make the following structure in a non-repetitive structure. Like the statement to run just one time. I tried to put "if" but that shows me the result 0. I need to change this: #include <iostream> using namespace std; int main() { int n, i, s, x; cin >> n; s=0; x=2; for (i=1;i<=n;...
The value to add (x) will be 2, 4, 6, 8, .... This is an arithmetic progression and there is a formula to calculate the sum of specified number of elements. Using the formula S_n = n/2 [2a_1 + (n-1)d] with a_1 = 2 and d = 2, the answer is: #include <iostream> using namespace std; int main() { int n, s; ci...
67,214,114
67,214,149
Why does an enum's variable name have to after the enumerated values in a C++ class?
If I use the first option, defining an enum normally, line 4 throws an error saying expected unqualified-id. Why is it that the enum variable name have to come after for this to work? class Machine { enum state {ON, OFF}; // need to use "enum {ON, OFF} state;" public: Machine() {state = ON;} // error here }
enum state {ON, OFF}; defines an enum named state. state is a name of the type and no variable is declared here. enum {ON, OFF} state; defines a variable state whose type is the anonymous enum.
67,214,241
67,214,282
Pointer as a structure members
struct student{ string name; int sNumber,*examGrade; }; int main(){ int i,k,l; cout<< "number of student in program:"; cin >>l; cout<< "number of exam in program:"; cin >>k; student stName[100], examNum[100]; for(int i=1;i<=l;i++){ student stdnt; cout<<i<<".student name: "; cin>>stdnt.name; cout<<i...
You used test->examGrade without initializing that. Assign valid pointer to that before dereferencing that. for(int j=1 ; j<=k; j++){ student * test = new student(); cout<<i<<". student"<<j<<".grade: "; test->examGrade = new int; // add this, for example cin>>*test->examGrade; ...