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
71,003,865
71,004,279
Function as template argument that has a different structure depending on method
I am writing a routine to find the numerical roots of a function in C++. Depending on the algorithm, I can supply either the function or both the function and derivative. For example, I have two separate routines template <typename T, typename Func> T Bisection(Func func, T x) { // algorithm details... auto f = fu...
The problem is that in your case you are instantiating both functions for the types that doesn't fit the implementation. You may try if constexpr, but for this case you need to move the method parameter the template parameters: enum class Method { Bisection, Newton }; template <Method method, typename T, typename ...
71,004,156
71,004,219
How to pass struct array arguments to a function the right way?
Source Code: #include <iostream> using namespace std; struct Employee { string name; int age; float salary; }; void displayData(Employee); int main() { Employee employee[3]; int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]); for(int i = 0; i < sizeOfEmployee; i++) { cout << "E...
You are reading data into a pointer to the first element of the array. To read into n-th element your code should be using indexing, like cin >> employee[i].name;. However... "Naked" arrays are a source of many errors, subtle bugs, and generally unsafe code. Consider using std::array instead - this will eliminate the n...
71,004,340
71,004,714
How to optimize mesh normals calculation?
I am making an application for real time mesh deformation and I need to calculate normals a huge number of times. Now the problem is I found with some profiling this bit of code is taking largest cpu time so how can I possibly optimize this? void Mesh::RecalculateNormals() { for (int i = 0; i < indexCount; i +=...
There is three main ways to optimize this code: using SIMD instructions, using multiple threads and working on the memory access pattern. None of them is a silver-bullet. Using SIMD instructions is not trivial in your case due to the indices-based indirect data-dependent read in memory in the first loop. That being sai...
71,004,636
71,004,658
how to complement the values of std::vector<bool> using range for loop taking element by reference
I need to complement the values of std::vector<bool>. So I thought of using range for loop taking elements by reference. But the compiler is giving me the below error error: cannot bind non-const lvalue reference of type 'std::_Bit_reference&' to an rvalue of type 'std::_Bit_iterator::reference' 13 | for (auto& ...
you can bind them (the returned proxy object) to rvalue reference for (auto&& bit : rep) bit = !bit; godbolt
71,004,642
71,005,010
I want to change the location of .sln and .vcxproj
below one is the current project structure. - project - bin - obj - include - src * a.cpp * project.sln * project.vcxproj But I want to create new directory "project". And move .sln and .vcxproj file into "project" directory. - project - bin - obj - include - project * project.sln * pro...
Visual Studio just allows to save the solution file .sln at another location. Just select the Solution in the Solution Explorer, go to menu item File -> Save >MySolution.sln> As... and save it under another name and/or location. The project file .vcxproj itself cannot be relocated by a Visual Studio option/menu item....
71,004,667
71,005,153
Short way to constrain template parameter without boiler plate code for a struct
consider this example: #include <iostream> template <typename T, std::size_t I> struct Foo { }; template <typename T> struct specializes_foo : std::false_type {}; template <typename T, std::size_t I> struct specializes_foo<Foo<T, I>> : std::true_type {}; template <typename T> concept foo = specializes_foo<T>::v...
Nope. There's no way to write a generic is_specialization_of that works for both templates with all type parameters and stuff like std::array (i.e. your Foo), because there's no way to write a template that takes a parameter of any kind. There's a proposal for a language feature that would allow that (P1985), but it's...
71,004,750
71,088,878
Arduino IR Transmittor not working with my TV
I try to do my DIY project with Arduino and IR transmitter. I connected and written code as per mentioned in web. but it is not working properly. connections: first IR pin connected to Ground second IR pin connected to TX #include <IRremote.h> IRsend irsend; void setup() {} void loop() { irsend.sendRC5(0x1FC1, 32);...
I got answer, even it shows warning, I can control my TV and other by below code. instead of RC5 I used NEC #include <IRremote.h> IRsend irsend; void setup() {} void loop() { irsend.sendNEC(0x1FC1, 32); delay(5000); }
71,005,029
71,005,071
Program works on GCC 7.5 on PC but not on online compiler
I have the following program that compiles successfully on my machine using GCC 7.5.0 but when i try out the program here the program doesn't work. class Foo { friend void ::error() { } }; int main() { return 0; } The error here says: Compilation failed due to following error(s). 3 | friend voi...
The problem is that a qualified friend declaration cannot be a definition. In your example, since the name error is qualified(because it has ::) so the corresponding friend declaration cannot be a definition. This seems to be a bug in GCC 7.5.0. For example, for gcc 7.5.0 the program works but for gcc 8.4.0 and higher ...
71,005,607
71,005,680
how to index a numeric value to return a string
I have this enum enum CombatType_t { COMBAT_ICEDAMAGE = 1 << 9, // 512 COMBAT_HOLYDAMAGE = 1 << 10, // 1024 COMBAT_DEATHDAMAGE = 1 << 11, // 2048 }; Basically, im trying to make a new array/list to be able to index an string by using a specific number to index CombatType_t Something as the following:...
In C++, the standard way to make an associative table is std::map: #include<iostream> #include<map> #include<string> ... std::map<unsigned, std::string> absorbType = { {512, "elementIce"}, {1024, "elementHoly"}, {2048, "elementDeath"} }; // Access by index std::cout << "512->" << absorbT...
71,005,801
71,014,967
Simplify chained expression in ANTLR listener
I have an ANTLR listener for C++ where I want to get the name of a member declarator. Currently, I'm using this approach: def enterMemberDeclarator(self, ctx: CPP14Parser.MemberDeclaratorContext): id = ctx.declarator().pointerDeclarator().noPointerDeclarator().noPointerDeclarator().declaratorid().idExpression().unq...
ANTLR4 supports XPath expressions to find specific nodes (see the documentation). That's somewhat easier to read than your expression, especially when you have to check for null: ids = XPath.findAll(ctx, "/declarator/pointerDeclarator/noPointerDeclarator/noPointerDeclarator/declaratorid/idExpression/unqualifiedId") (t...
71,005,923
71,011,823
SIMD code for mesh normals calculation not working (Trying to convert C++ to SIMD)
C++ Code void Mesh::RecalculateNormals() { for (int i = 0; i < indexCount; i += 3) { const int ia = indices[i]; const int ib = indices[i + 1]; const int ic = indices[i + 2]; const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);...
Your correctness problem is probably caused by Intel screwing up the order of their _mm_set_ps and similar intrinsics. To create a vector with x, y, z floats in the first 3 lanes, write either _mm_set_ps( 0, z, y, x ) or _mm_setr_ps( x, y, z, 0 ). Here’s better primitive functions you gonna need for that. That code ass...
71,006,057
71,006,413
C++ wprintf format specifier for char16_t for printing unicode string
I have the following code successfully compiled: #include <io.h> #include <fcntl.h> #include <iostream> #include <cstddef> #include <cstdio> int main() { _setmode(_fileno(stdout), _O_U16TEXT); char16_t chinese[] = u"\u4e66\u4e2d\u81ea\u6709\u9ec4\u91d1\u5c4b"; wprintf(L"String written with unicode code...
wchar_t is not the same as char16_t. wchar_t are 2 byte characters on windows, but (usually) 4 byte characters on linux. This is like the int vs. int16_t problem. The standard does not define wchar_t. So the question is not what format specifier to use with wprintf. It's rather how to convert a char16_t string to a wch...
71,006,098
71,006,331
Why does this OpenGL + WIN32 code produce Vertical lines?
To be clear, I've extensively tested this code and found the issue is somewhere with the code written prior to the WGL code. It's precisely in the WIN32 code. Now I think it could partially be caused by calling gluOrth2D but even then, that shouldn't be the primary cause as far I as I understand. I may figure this out ...
Don't use GL_POINTS for drawing an image pixel-by-pixel. For one, it's probably the most inefficient way (on any system, in any configuration) to go about, due to the way OpenGL, its implementations, and modern GPU do work. Instead – if using OpenGL – create a 2D array of the desired size, fill in the pixel values to y...
71,006,368
71,006,458
Why does gcc throw warning about conditionally-supported offsetof?
I have two structures in c++ struct Vertex { float x,y,z; float nx, ny, nz; }; struct SkinnedVertex : public Vertex { uint32_t j0, j1, j2, j3; float w0, w1, w2, w3; } Now, when I use offsetof to get offset of Vertex, everything is fine but if I use offsetof in SkinnedVertex, I get the following warning when c...
https://en.cppreference.com/w/cpp/named_req/StandardLayoutType A standard layout type requires all data members be in the same type. Standard layout is conservative in definition. Additional types could be made standard layout. The fact that a type is not standard layout doesn't mean there is a good reason that it isn'...
71,006,407
71,010,303
Generically wrap member function of object to modify return type
Version restriction: C++17. I'm trying to create a type capable of accepting a callable object of any type and wrapping one of its member functions (in this case, operator()) to take the same arguments, but modify (cast) the return type. An example follows: template <typename Ret, typename Callable> struct ReturnConver...
I don't see a way to respond to your exact answer but... considering the "Motivation" of the question... I propose a wrapper for overload (a class that inherit from a class with one or more operator(), call the appropriate operator() from the base class and cast the return value to type Ret) template <typename Ret, typ...
71,007,105
71,185,220
CMake undefined reference when using fmt from vcpkg
I'm pretty new at VSCode CMake and vcpkg, but I get in trouble when setting up environment. Here's CMakeList.txt cmake_minimum_required(VERSION 3.0.0) project(temp VERSION 0.1.0) set(CMAKE_TOOLCHAIN_FILE "C:/vcpkg/scripts/buildsystems/vcpkg.cmake") set(VCPKG_TARGET_TRIPLET "x64-windows") #include("C:/Users/dell/vcpkg...
The main reason of this is that I should use "fmt-header-only" instead of "fmt"
71,007,434
71,007,466
What does "operator MyType () {}" mean in C++
I see a function member in a c++ class: class bar{ //.. } class foo{ public: foo(){}; //... operator bar(){ return bar(); } } it's not an operator overloading, can anyone explain it to me ?
It is a user-defined conversion operator which constructs a bar object from the foo object. The purpose is to enable type casting from foo to bar.
71,007,972
71,008,040
process exited due to signal 6/11 c++
I didn't have any problems with compiling my program, but I have a big one when I try to use a bot to check output data. It says: "process exited due to signal 6" or "process exited due to signal 11". I thought it was a matter of dynamic arrays (i have two in this program) but both are deleted at the end. I would be ve...
I think the main issue is that you are doing int *used = new int(p_n);, this will create a pointer to an integer that has initial value equal to p_n. But, the problem comes here: used[i_used]=p_arr[i][1]; -- this may lead to a segmentation fault, as you may end up using memory outside the valid bounds. I'm not sure abo...
71,009,055
71,018,413
Extract all icons of a file
First of all, I want to access all icons (16x16...256x256 and larger) in a ".exe" file. As a result of my research, I found such code: #ifndef __ICON_LIST_H__ #define __ICON_LIST_H__ #include <windows.h> #include <vector> class IconFile: public std::vector<HICON>{ public: IconFile(){}; IconFile(std::string i_fi...
Use LoadLibraryEx to load the file, EnumResourceNames to enumerate icons, and CreateIconFromResourceEx to lead each icon. Note that driving a class from std::vector and other C++ Standard Library containers is not recommended. The example below uses LR_SHARED, you might want to change that. #include <windows.h> #includ...
71,009,740
71,009,867
Initializing from a pair in constructur intializer list
I have a function f returning a pair of objects of classes A and B: auto f() -> std::pair<A,B>; Furthermore, I have a class C that has A and B as members: class C { public: C(); private: A a; B b; }; In the constructor of C, I want to use the member initalizer list and initialize with the output of f:...
Improving on the idea from AnkitKumar's answer: class C { A a; B b; C(std::pair<A,B> &&pair) : a(std::move(pair.first)), b(std::move(pair.second)) {} public: C() : C(f()) {} };
71,009,831
71,009,896
Can I test deadlock in googletest?
I have a small class that creates multiple threads. When I call stop() method, it sets a flag for stopping threads and joins on the thread until they are stopped. Here is the code of stop() method: void stop() { running_flag_ = false; for (auto& th : threads_) { if (th.joinable()) th.join();...
When you have a deadlock some threads are waiting on locks until they are released. There is no way to recover process form such state, without adding extra code. The only way to overcome this problem is to detect timeout and crash unit test application when timeout accrues. Some times ago I used this code to detect is...
71,010,116
71,010,265
Index-based assignment in the loop for Pair, C++
I am new to C++. I want to assign the values to my tuple inside the loop. The following does not work. #include<utility> std::pair<int, int> myPair; int main() { for(int i=0; i<2; i++) { std::get<i>(myPair) = i; } } How could I do it correctly?
Do you have a reason to insist on doing this in a loop? If not, you can just assign to mypair.first and mypair.second. #include<utility> std::pair<int, int> myPair; int main() { myPair.first = 1; myPair.second = 2; } A very useful website to check what's available for standard library types is cppreference.c...
71,010,149
71,011,980
I can't figure out why hash[0] is being assigned the value 1 in the output . Any help would be appreciated
This is my code:- #include<iostream> #include<string> using namespace std; int main() { string magazine="aab"; string ransomNote="aa"; int hash[123]={}; int i; for(i=0;i<=magazine.length();i++) { hash[magazine[i]]++; } for(i=0;i<123;i++) { ...
In c++ chars are almost the same thing as integers and they are stored as integers. So when you are performing hash[magazine[i]]++; what really happens is that the magazine[3] (which is the NULL character) will be promoted to an int (Source: cpp reference: Implicit Conversions, the equivalent of which is 0 based on the...
71,010,294
71,010,787
Different results between clang/gcc and MSVC for templated constructor in base class
I stumbled over the following piece of code. The "DerivedFoo" case produces different results on MSVC than on clang or gcc. Namely, clang 13 and gcc 11.2 call the copy constructor of Foo while MSVC v19.29 calls the templated constructor. I am using C++17. Considering the non-derived case ("Foo") where all compilers agr...
It is correct that the constructor template is generally a better match for the constructor call with argument of type DerivedFoo& or Foo& than the copy constructors are, since it doesn't require a const conversion. However, [over.match.funcs.general]/8 essentially (almost) says, in more general wording, that an inheri...
71,010,520
71,012,791
Rcpp wrapper for algorithm to generate r x c contingency tables
I'm trying to use this C++ implementation of an algorithm for efficiently generating r x c contingency tables with fixed margins: https://people.sc.fsu.edu/%7Ejburkardt/cpp_src/asa159/asa159.html I'm working in Rcpp and am trying to create a function that I can utilize in R. I'm aware that there's a C implementation o...
This is actually an excellent question, and I too have had good luck with the nice and very comprehensive site full of routines by John Burkardt at FSU. But nothing is life is entirely free, and one needs to know a little bit about how C and C++ work to integrate such routines into R via Rcpp. My version of the final ...
71,010,802
71,010,871
Will destructor delete built-in types and pointer objects?
I'm a c++ beginner and now reading the C++ Primer. I have some problem about the destrucor: in chapter 13.1.3: "In a destructor, there is nothing akin to the constructor initializer list to control how members are destroyed; the destruction part is implicit. What happens when a member is destroyed depends on the type ...
What the spec means is that no code is run to clean up int i. It simply ceases to exist. Its memory is part of Foo and whenever a Foo instance is released, then i goes with it. For pointers the same is true, the pointer itself will simply disappear (it's really just another number), but the pointer might point at somet...
71,010,829
71,010,912
How to delete the extra spacing in code after it is printed?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue? please help! Here's an example picture of the output. **UPDATE: Thanks Drew for...
Change every (day > 9) to (day >= 9 ). You are using that condition to decide how much whitespace should appear after the number. Demo
71,010,919
71,011,103
Pointer to base virtual function vs direct call of base virtual function
Why do these two behave differently? (obj.*lpfn)(); vs obj.Base::fn(); I know when we directly call virtual member function (obj.fn()) it will do a virtual dispatch(find correct 'fn' implementation for type of obj, and call it). But why does a pointer to member function call that is set to Base implementation((obj.*l...
From the C++ standard: [expr.call]/1 For a call to a non-static member function, the postfix expression shall be an implicit (12.2.2, 12.2.3) or explicit class member access (8.2.5) whose id-expression is a function member name, or a pointer-to-member expression (8.5) selecting a function member; the call is as a memb...
71,011,343
71,011,579
Maximum number of codepoints in a grapheme cluster
I am using the C++ ICU library. I wish to split a utf-8 string into approximately equal chunks. However, I want the chunks to be demarcated at grapheme cluster boundaries. I do not wish to convert my entire string into utf-16 to do this for both memory and speed efficiency. Instead, I want to translate a small number o...
Is there a hard upper limit of the number of codepoints that can make up a grapheme cluster? No. There is no hard upper limit for how many code points a grapheme clusters - i.e. a user-perceived character - consists of. You could for example repeatedly add ZERO WIDTH JOINER with a joined character.
71,011,550
71,011,953
How to write statement that deletes extra space in C++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. I am building a project, but I am noticing an extra space after the last number when the calendar is finished. How do I fix this extra spacing issue? //extracted... if (day >= 9) { ...
In the section else { if (day >= 9) { std::cout << day; } else std::cout << day << " "; std::cout << " "; } You seem to have accidentally omitted the braces around the final else clause. It probably should read: else { ...
71,011,580
71,011,622
Check distance between labels when importing binary file gnu-assembler
I have the following macro to embed binary data from filename: #define INCBIN(identifier, filename) \ asm(".pushsection .rodata\n" \ "\t.local " #identifier "_begin\n" ...
If you just .p2align 2 after the file, it will round the total size up to a multiple of 4 bytes, regardless of how many bytes .incbin assembled to. (Since the file started at an aligned position). If you want to check instead of pad, that's possible at assemble time, using assembler directives. Obviously not at comp...
71,011,881
71,020,477
Why does pthread_join not take a thread pointer?
Pretty self explanatory question. For example, the header for pthread_create shows it takes a pointer to a thread: int WINPTHREAD_API pthread_create(pthread_t *th, const pthread_attr_t *attr, void *(* func)(void *), void *arg); OK, makes sense, you allocate a pthread in memory then pass a pointer to pthread_create so ...
It takes a copy of the pthread_t. Yes. I just don't get why it doesn't take a pointer to that already existing thread, pthread_t is a thread identifier. The specs consistently refer to it that way. Copying it does not duplicate the thread itself, nor consume more memory than one pthread_t occupies. rather than c...
71,011,962
71,011,994
Create STATIC and SHARED libraries with Clang
What is the minimal commmand line way to create an static and a dynamic library with Clang under Linux and Windows, and then, link it against an executable? Suppose the project contains a main.cpp file with the main function, an lib_header.h file under /include/project_name and a lib_source.c or lib_source.cpp under /s...
For both static and dynamic libraries, you first compile the source files individually: clang -c -o lib_source.o lib_source.c -fPIC For the static library on Linux, archive all .o files together: ar r library.a lib_source.o For the shared library, link with the -shared flag: clang -shared -o library.so lib_source.o
71,012,034
71,012,042
Pointer still able to call member function, after it was set to NULL and delete being called on it
#include<stdio.h> class test2 { public: void testFunc() { printf("test"); } test2(){} ~test2(){} }; class test1 : test2 { public: test1(){ link = new test2();} ~test1(){ delete link; link = NULL; } test2* link = NULL; private: ...
If a program accesses an object outside of its lifetime, then the behaviour of the program is undefined. Your program accesses an object outside of its lifetime. The behaviour of your program is undefined. The behaviour that you observed is because the behaviour is undefined. You could have observed any other behaviour...
71,012,139
71,012,201
How to delete spacing after row is complete in c++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. So far my project works, but I am noticing an extra space after the last row is completed. How do I fix this extra spacing issue? please help! There's a space at the bottom... and this only seems to h...
I think this will fix it: That's the block dealing with the last day of the week (Saturday). Print it always. If it is the last day of the month, don't do anything else. Otherwise: 1) print a newline, and 2) if the next day has 1 digit (current day < 9), print a space. [Demo] if (++count > 6) { c...
71,012,424
71,012,468
Finding Max element of the list of lists in c++ (conversion of python function)
I wanted to convert the following function python to c++: def find_max_value(list): max_value_list = [] for i in list: max_value_list.append(i[0]) return max(max_value_list) The inputs are the : [[90.272948, 210.999601, 90.31622, 349.000214, 4.042645], [520.293431, 349.000041, 520.285479, 211.000041, 2.007837], [2...
I'm going to guess you are looking for something like this: double find_max_value(const std::list<std::list<double>>& a){ return std::max_element(a.begin(), a.end(), [](const std::list<double>& lhs, const std::list<double>& rhs) { return lhs.front() < rhs.front(); } )->front(); } This assumes none of...
71,012,708
71,012,821
How to print the multiples correctly?
I am trying to display the multiples of a user-inputted number given 6 user-inputted numbers. I think I am sort of close, but I am stuck. For example, if someone enters "4" and then their 6-number sequence is "23 45 12 16 51 8", it should return 12 16 8 because those are the multiples of the first inputted "4". So far ...
You print userNum and seq1 to seq6 before you've assigned values to them. That makes the program have undefined behavior. Your for loop has invalid syntax and you also return instead of printing the matching values. A fix could look like this: for (int i = 0; i < 6; i++) { if (sequence[i] % userNum == 0) { ...
71,012,740
71,012,798
passing std::plus as an argument
How do I pass std::plus as an argument across functions? #include<functional> #include<iostream> template < class T, typename F > T fn(T a, T b, F f) { return f<T>()(a,b); } template<class T> struct X { template < typename F> T foo(T a, T b, F f) { return fn<T, F>(a,b,f); } }; int mai...
If you want to pass std::plus as a runtime argument you have to actually construct one. You can't pass a type as an argument. Trying to pass a naked std::plus<int> is akin to writing a class name or type name there i.e. you would not expect foo(a,b, int) to compile if it expects the third argument to be an int value. #...
71,013,366
71,013,537
Equivalent in C++ to the pack function in PHP pack('H*', $tagIdAsHex);
I have this PHP code: $tagId = 1; // the original value of tag $tagIdAsHex = sprintf("%02X", $tagId); // the tag value in hex format $tagAsHexBytes = pack('H*', $tagIdAsHex); // the packed hex value of tag packed into string as a conversion How can I translate that to C++? byte tagId = 1; auto hexedTag = IntTo...
The PHP code shown is simply converting the integer 1 into a hex-encoded string containing "01", and is then parsing that hex string into a binary string holding a single byte 0x01. In C, you can use sscanf() in a loop to parse a hex string. In standard C++, you can use std::hex and std::setw() to parse a hex string fr...
71,013,555
71,013,589
Default and Parameterized constructors and object declaration
I've written this code: #include<iostream> using namespace std; class Student { public: string name; int age; Student() { cout<<"Default constructor"<<endl; } Student(string name, int age) { this->name=name; this->age=age; cout<<"Parameterized const...
For the 1st case, Student has user-declared constructors, Student s1={"abc", 20}; performs list-initialization, as the effect, the appropriate constructor Student::Student(string, int) is selected to construct s1. If the previous stage does not produce a match, all constructors of T participate in overload resolution ...
71,013,605
71,013,852
How can I initialize an std::array of a class without a default constructor?
Let's say I have a class without a default constructor called Foo. If I were using an std::vector, I could do this: std::vector<Foo> vec(100, Foo(5)); This would create a vector of 100 elements, each with value Foo(5). How do I do the same with std::array<Foo, 100>? I obviously do not want to list out Foo(5) explicitl...
With copy constructor, something along these lines: template <typename T, size_t... Is> std::array<T, sizeof...(Is)> MakeArrayHelper( const T& val, std::index_sequence<Is...>) { return {(static_cast<void>(Is), val) ...}; } template <typename T, size_t N> std::array<T, N> MakeArray(const T& val) { return MakeAr...
71,013,618
71,013,778
Understanding the Sub-expression overflow reasoning
I am trying to understand the reasoning behind this particular suggestion in Visual Studio 2022, as it doesn't seem to make sense to me. Here's the simple code: static constexpr uint32_t MAX_ELEMENTS = 100000; const std::vector<int> A{ some random ints }; std::vector<bool> found(MAX_ELEMENTS); for (int value : A) { ...
In this case, it is a false positive, as you suspected. This is a rule that sometimes gets used in stricter code bases. (This particular warning is an error in MISRA, for example.) A lot of warnings are like this... the compiler writers are trying to detect a situation where the behavior of the program is unexpected or...
71,013,640
71,013,722
WinAPI equivalent for Linux/POSIX pthread_wait/pthread_post
I have an application which takes care of some syncronization problems, it relies heavily on the POSIX functions, sem_wait, pthread_join and sem_post, I'd like to know what are the winapi equivalents for these?
sem_wait() -> WaitForSingleObject() on a Semaphore object pthread_join() -> WaitForSingleObject() on a Thread object sem_post()-> ReleaseSemaphore() on a Semaphore object See Using Semaphore Objects in MSDN's documentation.
71,014,380
71,014,489
What I need write this second SFINAE constructor?
I wanted to activate a class with parameter packs when all types in the parameter pack is distinct. I wrote a small helper function like this that works with no problem: template<typename T, typename... Ts> constexpr bool has_duplicate_types() { if constexpr (sizeof...(Ts) == 0) return false; else ...
If I write another SFINAE constructor like this: ... It will work, but I have no idea why I need to write 2nd one and it does not pick defaulted one without it automatically. The compiler doesn't generate the default constructor if you define any custom constructor, even if that constructor is disabled by SFINAE. And...
71,015,806
71,020,162
Firestore authentication for multiple devices
I'm developing linux c++ desktop application that connects to Firebase. The app will be deployed on multiple devices. Is it possible to perform REST authentication (Sign in with email / password) for all of these devices using one common e-mail address or will it trigger a security alert when more than one sign in oper...
A user can sign in to Firebase Authentication from multiple devices. There is no inherent limit to the number of devices a single user can sign in from.
71,015,864
71,016,004
Can we add a const to an inherited virtual member function
I am learning inheritance in C++. So for clearing my doubts i am trying out different examples. One such example which i don't understand is given below: struct Base { virtual void func(int a) { std::cout<<"base version called"<<std::endl; } }; struct Derived: Base { void func(int a) const //note the c...
The member function func inside Derived is a separate/different non-virtual member function from the virtual func inside Base, as explained below. Explanation You can confirm this: by adding the specifier override after const of func in Derived as shown here you will see the error saying marked override, but does not...
71,015,912
71,032,215
HID USB ReadFile() missing packets during large downloads
I implemented a HID USB PC application which seems to work fine for connecting, readin and writing to an external USB device. The problem is when attemping to read large data files, some packets get lost. Here is the code im using: DWORD result; uint8_t u8_dataBuffer[size] = { 0 }; DWORD bytesRead; ReadFile(Handle,...
HID reports are saved in a ring buffer. So if you don't fast enough to read all pending input reports - they could be lost. Size of this buffer could be changed via HidD_SetNumInputBuffers call or IOCTL_SET_NUM_DEVICE_INPUT_BUFFERS IOCTL on HID device handle. By default, the HID class driver maintains an input report ...
71,016,630
71,016,716
"Invalid use of non-static data member" when initializing static member from global variable
class A { int x; static int i; }; int x = 10; int A::i = x; When I compile the code above, it get the error <source>:8:12: error: invalid use of non-static data member 'A::x' 8 | int A::i = x; | ^ <source>:2:9: note: declared here 2 | int x; | ^ What's causing this...
This is a peculiar language quirk - the scope resolution on the left, in int A::i, affects the lookup scope on the right, so that actually refers to the x member of A. Either rename one of the variables, or specify the scope of the desired x explicitly: int A::i = ::x;
71,016,677
71,016,935
When does std::format throw an exception?
I am using OutputDebugStringA() to output diagnostic info from my program that I can read with DbgView. Today I am using std::stringstream to format messages: int value = 5; std::stringstream ss; ss << "value=" << value; OutputDebugStringA(ss.str().c_str()); This is rather verbose and I am looking into using std::form...
My only worry is that std::format may throw an exception. But under which circumstances? From [format.err.report]: Formatting functions throw format_­error if an argument fmt is passed that is not a format string for args. They propagate exceptions thrown by operations of formatter specializations and iterators. Fai...
71,017,753
71,018,114
benefits for setting dependency interface in cmake target_link_libraries
I use CMake in my C++ project for a while, and my project is an application (not a library) consisting of multiple sub modules, where each module depends on other internal modules in the same project, and depends on multiple third party libraries as well, and each of them is built using CMake. Currently, we use PUBLIC ...
You should absolutely always use a visibility specifier with target_link_libraries. Whether or not target_link_libraries(target lib) is considered to be PRIVATE or PUBLIC by default depends on whether or not you use visibility specifiers elsewhere in the CMakeLists.txt. This risk of changing the visibility of a library...
71,018,062
71,019,037
Save a PCL specific view as image
I am new to C++ and the use of the Pointcloud Library PCL (https://pointclouds.org/). At the moment I am able to generate a viewer of the point cloud by using the <pcl::visualization::PCLVisualizer> and I was wondering if it would be possible to save an image of the current viewer "view". Imagine I have a picture like ...
Of course I posted the question after researching online. However, I could not find the super easy solution available already in PCL. You just need to use the function: void pcl::visualization::PCLVisualizer::saveScreenshot ( const std::string & file ) Documentation here I hope this will be helpful for someone...
71,018,897
71,042,174
Yocto recipe to compile C++ program with usb.h include
I would like to compile a c++ program in my yocto toolchain. For this, I added a new recipe that should compile the program and install it into the image. My issue is that I have to include some kernel headers like `usb.h`` recipe.bb SUMMARY = "Simple helloworld application" SECTION = "examples" LICENSE = "MIT" LIC_FIL...
I believe you need to add libusb as a dependence to your recipe. Add the following line to your recipe: DEPENDS = "libusb"
71,019,078
71,019,832
Efficient overflow-immune arithmetic mean in C/C++
The arithmetic mean of two unsigned integers is defined as: mean = (a+b)/2 Directly implementing this in C/C++ may overflow and produce a wrong result. A correct implementation would avoid this. One way of coding it could be: mean = a/2 + b/2 + (a%2 + b%2)/2 But this produces rather a lot of code with typical compile...
The following method avoids overflow and should result in fairly efficient assembly (example) without depending on non-standard features: mean = (a&b) + (a^b)/2;
71,019,328
71,019,867
Mismatch in integer calculation results between C++ and Python (random number generator)
I needed a pseudo random number generation scheme (independent of standard libraries) for one of my projects and I tried a simple LCG based RNG. It seems to work fine except that it produces different values in C++ and Python. I am giving the relevant code for both below. I am not able to find the error. Any help will ...
The problem is with the shift in: uint64_t M = (1 << 31); the (1<<31) is a negative number -2147483648 for 32 bit integers because this is signed integer math. To fix you can use uint64_t M = (1U << 31); to make the shift use unsigned 32 bit integers. You could also use uint64_t M = (1UL << 31); to have the calculation...
71,020,122
71,129,303
Detecting circles with DIPlib
I'm trying to detect the circles in this image: and then drawing such circles in another blank image using DIPlib in C++. Following the advices of Cris Luengo I've changed the code and now looks like this: #include <iostream> #include <vector> #include <diplib.h> #include <dipviewer.h> #include <diplib/file_io.h> #inc...
The documentation for dip::FindHoughCircles reads: Finds circles in 2D binary images using the 2-1 Hough transform. First, circle centers are computed using dip::HoughTransformCircleCenters, and then a radius is calculated for each center. Note that only a single radius is returned per center coordinates. That is, th...
71,020,324
71,022,902
Function log2l has no function body
I am new to Vivado HLS ( using Vivado HLS 2018.3 ). I am writing this code to generate a 16-bit CRC (Cyclic Redundancy Check) using a 128-bit message and 17-bit generator polynomial. Here in the source code, I am using log2l() in order to find out the number of bits. This code runs smoothly during C Simulation but duri...
I suspect it has something to do with the inclusion of the math library. I guess Vivado HLS has some configurations or flags to supply in compilation and then in synthesis regarding the use of mathematical functions. Nevertheless, a simple and effective workaround would be to implement floor(log2(x)) yourself, somethin...
71,020,560
71,021,030
Is OutputDebugString thread safe?
In my code I call these methods at various places to send diagnostic output to DbgView: inline void dbg_info(std::string s) { std::stringstream ss; ss << "INFO:" << std::this_thread::get_id() << ": " << s << std::endl; OutputDebugStringA(ss.str().c_str()); } inline void dbg_err(std::string s) { std::st...
Yes it is thread safe. It uses a mutex and events. Implementation details here.
71,020,873
71,020,903
Error main: malloc.c:2401: sysmalloc: Assertion Doing a simple C++ fibonacci assignment
I am working on this assignment and i trying to figure this out. When i input any other numbers between 1 to 10 except 6. The fibonacci_fast(n) outputs an error main: malloc.c:2401: sysmalloc: Assertion. However, when i use an array to replace the vector or just uncomment the std::cout. It will work fine. Can anyone en...
std::vector<int> numbers{0,n}; creates a vector of size 2, not of size n. You probably want to use std::vector<int> numbers(n, 0).
71,021,297
71,021,457
std::set elements' reference and pointer invariance after insertion
I came across a paragraph on cppreference that I don't think I understand: No iterators or references are invalidated. [If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was...
Does node handle refer to an iterator? No. A "node handle", introduced in C++17, refers to the data structure internal to a std::set used to hold a single element. It's what the std::set will allocate from the free store to hold the element and any related data structures, such as pointers and flags. A handle to thi...
71,021,339
71,021,440
C++: [[maybe_noreturn]]
As far as I am aware, there is no [[maybe_noreturn]] attribute in C++. I have a function which looks like this: void func() { try { do_something(); } catch (const std::exception& e) { std::exit(1); } } If I would mark func as [[noreturn]] I'd run into UB for the happy case. Is it UB when I ...
Is it UB when I do not return from a function that is not marked as [[noreturn]]? No, it's well defined to terminate the program from a function regardless whether it has [[noreturn]] attribute or not. Using [[noreturn]] is optional when it is appropriate - i.e. when a function terminates unconditionally - but it is ...
71,021,818
71,022,125
Compiler insists rename() function is of type void
I'm trying to write a program capable of renaming files, but I'm encountering a weird issue. When I write this: string oldname, newname; rename(oldname, newname); Everything works fine. The file is renamed and there are no problems. But then when I go ahead and try this: int result; result = rename(oldname, newname); ...
You are expecting to call the C standard library function rename() with signature: int rename(const char*, const char*); But that function would not be a viable overload for rename(oldname, newname) if oldname and newname are of type std::(w)string, since std::(w)string is not implicitly convertible to const char*. So...
71,021,895
71,022,137
How to unravel type dependency? (X uses undefined class Y)
I'm trying to implement simplistic fast memory management for my delegate type, but encountered circular dependency which I can't solve myself. // Size of single bucket of delegates static constexpr size_t _alloc_buffer_bucket_size = 128; template <typename TFunc, typename... Args> struct bucket; template <typename T...
By moving the definition of the bucket struct outside of the scope of Delegate and assigning the _alloc_buffer and _current_bucket variables outside of the class scope, we can achieve compilation. I was able to get it compiling as such: // Size of single bucket of delegates static constexpr std::size_t _alloc_buffer_b...
71,022,354
71,026,288
how to use c++ ->() operator to get a baseclasses private member? so I can access derived?
I am attempting to access a derived class TMAConnection after receiving it via a baseclass factory method template <> class cpool::ConnectionPoolFactory<TMAConnection> { public: static std::unique_ptr<cpool::ConnectionPool> create( const std::uint16_t num_connections, const char* tma_gw_host, const int tma_gw_port)...
ConnectionPool::get_connection() returns a ConnectionProxy which is not a Connection object directly, but holds one: A ConnectionProxy allows you to access the underlying connection object. // create a pool auto pool = ... // get a ConnectionProxy auto proxy = pool->get_connection(); // cast to your type if(auto conn ...
71,022,720
71,022,877
What the value of "chrono::steady_clock::now().time_since_epoch().count()" represents?
cout << chrono::steady_clock::now().time_since_epoch().count() << "\n"; // it prints a 14-digit value Is is the number of nanoseconds passed since 1970?
Is is the number of nanoseconds passed since 1970? Very unlikely. It is the number of some duration unit passed since some time. Neither the unit nor the epoch is standardized. This may not sound useful, and a single reading of std::chrono::steady_clock::now() arguably isn't very useful. (Beyond, say, seeding a ran...
71,022,852
71,022,923
c++ template with partially fixed argument list
Consider a case like the following: template<typename T> class A { ... }; template<typename T, typename DataType = std::vector<A<T>>> class B { .... DataType data; ... } In my case the DataType type can be any std "container", but it must always be specialized with type A. The use of A should be transparent fro...
You can do it with template template parameter, e.g. template<typename T, template <typename...> typename container = std::vector> class B { using DataType = container<A<T>>; ... }; Then use it like B<int> (i.e. B<int, std::vector>) or B<int, std::deque>.
71,022,928
71,023,359
Why doesn't std::integral_constant<lambda> work the same way as std::integral_constant<function-ptr>?
(related to this question). I am trying to combine unique_ptr and lambda via std::integral_constant (taking address of most std functions is outlawed in C++20, I am figuring out a convenient way to wrap them in lambda). I noticed weird behaviour of std::integral_constant that I can't explain (godbolt): #include <type_t...
When performing a function call on an object, not only the call operators are considered. There is a special exception if a non-explicit conversion function to a function pointer type (or function reference type) with suitable cvref-qualifiers exists. In these situations [over.call.object]/2 says that an additional ove...
71,023,144
71,024,534
How to build header only C++ library within Bazel workspace?
I'm working on a C++ project and I need Numpy like arrays and functionalities in C++. I found some alternatives like xtensor, NumCpp etc. These are header only libraries. The problem is I'm experimenting with Bazel for the first time so, I don't have any idea about how do I add header only library to Bazel workspace. T...
For simple things like header-only libraries, I would write BUILD files yourself, without using rules_foreign_cc. Just write a cc_library with no srcs. Something like this: http_archive( name = "xtensor", build_file_content = all_content, strip_prefix = "xtensor-master", urls = ["https://github.com/xten...
71,023,177
71,023,375
My code is outputting an extra line why is this?
This code I've been working on is so close to being done. However, it keeps printing out an extra line in the output. There is only supposed to be 5 lines in the output but there is six and I can't figure out why this is happening. This is my book.h file this file cannot be changed in order to complete the code. #inc...
There's probably a blank line at the end of the data file. Put in if (name.empty()) { continue; } just before you construct the book object. Also as @Eljay said in comments you shouldn't iterate over a file by doing while (!file.eof()): see here.
71,023,187
71,023,946
Can I use std::next on user defined class
If I have a user-defined class : class MyColl { int *data ; public : class Itr { int operator*() {} void operator++() bool operator != (const Itr &oth) } ; Itr begin() {} Itr end() {} } ; Can I use std::next on objects of MyColl If yes, then what ...
// How to implement a forward iterator for your collection class template <typename T> class MyCollection { public: struct MyCollectionIterator { // These five typedefs tell other things about your iterator using iterator_category = std::forward_iterator_tag; using value_type = T; usi...
71,023,392
71,023,704
Can I pass a built-in array to std::ostream_iterator without an array-to-pointer decay?
I have overloaded operator<< to print a built-in array const int (&arr)[N]: template <size_t N> std::ostream& operator<<(std::ostream& os, const int (&arr)[N]) { os << "{ "; bool first{true}; for (int i : arr) { os << (first ? "" : ", ") << i; first = false; } return os << " }"; ...
This has nothing to do with array-to-pointer decay and everything to do with how name lookup works. In this version: for (const auto& subarr : arr) { std::cout << subarr << "\n"; } your operator<< is a candidate because regular unqualified lookup will find it. But that's not what ostream_iterator does, its implementat...
71,023,590
71,023,659
how to pass pointer to constructor in c++
have a derived class that needs to take a pointer as a constructor for the base class. how do you do this in c++, i tried it but it gave me a bug. #include <iostream> using namespace std; class Base { protected: int *num; public: Base(int *num); virtual void print(); }; Base::Base(int *num){ this->nu...
In the constructor initializer list of Derived you have to write Base(num) instead of Base(*num) as shown below: Derived(int *num): Base(num) { //code here } Note that you don't have to dereference the pointer num which you were doing while using it in the constructor initializer list. When you dereference num, yo...
71,024,043
71,226,322
Problem finding multiplicative inverse c++
I need to find the multiplicative inverse to some number e modulo ph. e is a prime number, ph is the result of the Euler function of some number. In the example e = 65537; ph = 3616319324. The pre-calculated correct value is 2373062985. On my own and with the help of the Internet, I wrote several functions to get this ...
The solution was to change the types from unsigned to signed. Also, if the result is negative, you need to add ph to it. And here's working code: #include <iostream> #include <tuple> #include <vector> int32_t xgcd1(int64_t a, int64_t b, int64_t& x, int64_t& y) { x = 1, y = 0; int64_t x1 = 0, y1 = 1; int64_...
71,024,774
71,024,801
Validating Input C++
int num = 0; while(true){ cout << "enter num: "; cin >> num; if(!(num)){ cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "num must be an int" << endl; }else if(num <= 0){ cout << "num must be greater than 0" << endl; }else if(static_cast<double>(static_cast<int>(num...
This: cin >> num; if(!(num)) Should be this: if (!(cin >> num)) You are checking the value of num when you should instead be checking the error state of cin. operator>> returns a reference to the input stream, which is then implicitly convertible to bool, where false means the stream encountered an error. Also, this...
71,025,541
71,025,581
Access protected member function in C++
There are two external class (A and B)that I cannot change. I would like to access protected member of the class A:: doSomething in C (which I can do edit). Is there any way to access it. I understand its not good practice but I did not find any other way of doing it. // External code starts struct A { friend class...
Friendship is not transitive, so inheriting from B doesn't help with this. Inherit from A and form a pointer-to-member to doSomething: struct Helper : A { static constexpr auto ptr = &Helper::doSomething; }; Use that pointer to call a function on a: void doSomethingElse() { A a; (a.*Helper::ptr)(); }
71,025,562
71,025,776
my data in the console is displayed in the wrong sequence
Why is my data in the console displayed in the wrong sequence? I have the following code: #include <iostream> template <typename T, typename T2> T2 printArr(const T* array, int i) { for (int j = 0; j < i; j++) { std::cout << array[j] << " "; } std::cout << std::endl; return array[i - 1]; } int...
Before C++17, given an expression E1 << E2, it is unspecified whether every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2. See cppreference note 19 In your code, using a standard before C++17, it is unspecified whether the return value of printArr() is calcula...
71,025,656
71,025,826
Where are return values stored and how/can they be incremented?
I've done my fair share of reading and researching but I still don't 100% get it. For this solution of " Minimum Depth of Binary Tree", the idea of having multiple returns in a recursive function is killing me. I'm not exactly sure how the value for the "minimum depth" is being incremented, and I understand it may have...
If it helps, logically, what you have above could just as well have been written int minDepth(Node *root) { int result; if(!root) result = 0; else if(!root->left) result = 1 + minDepth(root->right); else if(!root->right) result = 1 + minDepth(root->left); else re...
71,025,763
71,025,880
How to tell, whether a C++ proposal is accepted or not?
Let's take P1907 as an example. Is it accepted into the C++ standard? To which version? When?
Papers can be tracked here. https://github.com/cplusplus/papers/issues Entering is:issue P1907 into the search box produces: P1907 (closed) and P1907R1 (merged) Alternatively, If you use Slack, you can join the C++ slack at cpplang.slack.com and privately message any paper name to @npaperbot to get information about it...
71,025,854
71,027,185
To solve ambiguity of overloaded function without either adding typecasting or remove the overloaded functions
I made a class Dummy, which is just a wrapper of primitive type double. The purpose of the class is to test potential problems before I introduce another class that substitutes the double class. Dummy.h: class Dummy{ private: double content; public: Dummy(double _content) :content{ _content } {}; operator l...
The Dummy class you have shown is only convertible to long int, but fabs() does not accept long int, it accepts either float, double, or long double. Since long int is implicitly convertible to float and double, the call was ambiguous until you added the double conversion operator. If you don't want to do that, then y...
71,026,223
71,028,271
Do I need to fence/sync when I use GL_MAP_COHERENT_BIT in a PMB?
I've seen contradictory documentation about it. In the Khronos documentation it's a bit ambiguous whether I need to glFinish (or variants) or not. I'm currently triple-buffering my buffer to avoid this problem (as I use the PMB dynamically) but it obviously consumes a lot of memory. I know that the flag makes the data-...
There's no implicit synchronization because the driver/GPU has no idea when you're accessing the mapped pointer. That's what persistent mapping is all about, after all. And yes, you still need synchronization. If you're trying to read something the GPU has written... you need the GPU to have written it before you can r...
71,026,400
71,026,528
Conversions to arrays of unknown bound: g++ vs. clang++
Note: this is the follow-up question for this question. Sample code (t334.cpp): typedef int T0; typedef T0 T1[]; typedef T1* T2[]; T1 x1 = { 13 }; T2 x2 = { &x1 }; Invocations: $ g++ t334.cpp -std=c++11 -pedantic -Wall -Wextra -c t334.cpp:6:11: warning: conversions to arrays of unknown bound are only available with ...
The first definition is of an array of known bound that is deduced from the initializer. It has the same effect as: int x1[1] = {13}; That means x1 has type int[1], and &x1 has type int (*)[1]. The second definition is trying to initialize a variable of type int (*)[] from a (brace-enclosed) expression of type int (*)...
71,026,443
74,538,173
How to get gcov results for included C/CPP files
I'm trying to get gcov results on a file that's brought in via #include. If I compile with it as a separate object file it works fine. For example with these files: lib.h int addFive(int num); lib.c #include "lib.h" int addFive(int num) { return num + 5; } testlib.cpp #include "lib.h" int main() { return addFiv...
If I compile test with --coverage instead of -lgcov it does generate a test.gcda. I thought at first this was not what I wanted since I'm looking for coverage in lib.c But if I run both testlib and test and then use gcov on all the files together, it combines the coverage data properly: gcov lib.gcda lib.gcno test.gcda...
71,027,045
71,027,486
Optimize Union Find (Disjoint Set Union) implementation
I have implemented a Disjoint Set Union in C++ for a Kattis problem. However, my solution is inefficient, as I get TLA (Time Limit Exceeded) for the first hidden test case. Can anyone spot an inefficiency with my code? I have based my implementation on this article. In particular, I set the parent of the parent of the ...
This seems to be a Kattis-specific IO problem. Adding ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); to the start of main, and changing both occurrences of endl to '\n' causes it to pass in .2 seconds. I'll also mention that including <bits/stdc++.h> is frowned upon here, but the only cause of your error w...
71,027,176
71,074,776
Inconsistencies with C++11 function signatures
I have questions regarding functions, more specific on function signatures and how to pass them. I might be a trivial or even stupid question, but I couldn't find a satisfying answer yet. Please consider this example which uses a std::unique_ptr to manage a file pointer: #include <iostream> #include <memory> void func...
Function name is the always address of function (pointer to the function). If you want to use something else you can use some wrapper, e.g. std::function: #include <iostream> #include <memory> #include <functional> class Closer { public: void operator ()(FILE *f) { std::cout << "func1 called" << std::endl;...
71,027,437
71,027,481
C++ Struct Members not Updating in Funtion
Firstly, while not new to programming, I am very new to C++, so please bear with me. I am using the Raylib library to attempt making a particle system for a game. This consists of a struct with a few private members and public functions: struct Particle { Particle() { mPosVector = {(float)GetMouseX(), (float)GetMo...
for (Particle part : particles) { part.update(deltaTime); } this is making a copy of each entry , you need for (Particle &part : particles) { part.update(deltaTime); } to get a reference to the object in the vector to update it in place To understand, think that the ranged for is just sh...
71,027,888
71,027,959
C++: Wrapping C style array into unique_ptr leads to "double free or corruption"
I have a C function that returns me a C style array. I would like wrap this into more C++ style code, so I don't have to manage its lifetime manually. So, I defined my wrapper as such: template <typename T> class Wrapper { public: std::unique_ptr<T[]> data; explicit Wrapper(T data[]) : data(data) {} }; Howeve...
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; This variable has automatic storage duration. It will be destroyed at the end of the scope where it is declared. You pass a pointer to the first element of the automatic array into the constructor. The constructor initialises the unique pointer member to point to the automatic a...
71,027,960
71,028,145
Adding syntactic sugar to C++
Edit 2: New edit: it looks like C++20 has a new ranges library, which does what I want from the functional point of view. How would something similar be done on C++17 or earlier? Also, would the Kotlin syntactic sugar be possible? Mainly the person example: val adam = Person("Adam").apply { age = 20 // same as thi...
Your example can be changed to working C++ code fairly easily: template <typename T, typename Fun> auto map(T t, Fun f) { std::vector<typename T::value_type> ordinals; std::transform(t.begin(), t.end(), std::back_inserter(ordinals), f); return ordinals; } This is neither very idiomatic nor optimized for performa...
71,028,202
71,032,447
Making a template function mirror its template argument's signature
I have a template function: template <??? func> ??? wrapper(??? args) { // ... Stuff return func(args); } It should have the same signature as the func non-type template parameter. The closest I've gotten is using auto in the template declaration and then using some form of function traits to deduce the return...
You can create traits to extract returs type and parameters. issue would be to handle arity only from function declaration. If you can wrap in a class/functor, it would be possible: template <auto func> struct wrapper_t; template <typename Ret, typename ... Ts, Ret (*func)(Ts...)> struct wrapper_t<func> { Ret oper...
71,029,221
71,029,283
How to call a non-static method from a function pointer?
I have a class "Person" like so: typedef void (*action)(); typedef std::unordered_map<int, action> keybindMap; // maps keycodes to functions class Person { keybindMap keybinds; void doSomething(); } I use this to call the functions at the right times: iter = keybinds.find(event.key.keysym.sym); // event.key.k...
A non-static method requires an object to call it on. An ordinary function pointer doesn't have room to hold a reference to an object. If you change your map to hold std::function instead, you can then use std::bind() or a lambda to associate an object with a method pointer, eg: using action = std::function<void()>; us...
71,029,666
71,029,964
send and receive binary files properly using sockets c++
hello stackflow users, so i want to send and receive my binary file using sockets in c++ and here is how i send it from server program send(Connections[conindex], reinterpret_cast<char*>(rawData), sizeof(rawData), NULL); and here is how my client program receives it char raw[647680]; recv(Connection, raw, sizeof(raw),...
A rather general way to achieve this (in both C and C++) is something like this: if (FILE *fp = fopen(filename, "rb")) { size_t readBytes; char buffer[4096]; while ((readBytes = fread(buffer, 1, sizeof(buffer), fp) > 0) { if (send(Connections[conindex], buffer, readBytes, 0) != readBytes) ...
71,029,777
71,029,904
Difference between a deconstructor and exit() C++
In college, when learning C++ specifically, we're always taught that we need to deallocate dynamically allocated memory or close an open file using a deconstructor. What is the difference between that and just using the operating system call exit(0)? Just wondering.
They are not comparable. Apples and oranges exit() is a C library function. Cpp Reference tells us: Causes normal program termination to occur. Several cleanup steps are performed: functions passed to atexit are called, in reverse order of registration all C streams are flushed and closed files created by tmpfile are...
71,029,917
71,030,554
Is it possible to depend expected calls in gMock together?
Assume that I want to test following function: template<typename Pack> bool is_valid(const Pack& pack) { if (pack.a() > 0) return pack.b(); return false; }; I will write a small mocker for Pack as follows: class PackMock { public: MOCK_METHOD(int, a, (), (const)); MOCK_METHOD(bool, b, (), (const)); }; ...
Firstly, you can use a testing::Sequence instance to keep track of mock calls in sequence. You can also directly define a InSequence for the test as in the docs. Secondly, your first EXPECT_CALL does not call the b() mock call, because a() returns 0 which then never evaluates the return pack.b(). As an example found he...
71,029,970
71,030,131
C++ istream input fails yet consumes data. Expected to be able read bad data after failure
My understanding of iostream has always been that when an input conversion fails, the data remains in the stream to be read after clearing the error. But I have an example that does not always work that way, and I would like to know if the behavior is correct. If so, could someone point me at some good documentation ...
Plus and minus are valid parts of an integer and so are read, when the next character is read the stream fails and that character is left in the stream but the leading sign character is not put back into the stream. See https://en.cppreference.com/w/cpp/locale/num_get/get for the full rules
71,030,029
71,030,304
I don't understand where I made a mistake
I tried this code after documenting myself : struct person { int a; char s; }; struct person test; test.a = 12; And Code::Blocks returns this following error : error: 'test' does not name a type Can someone explain this error to me? I found this sample code on the internet! I don't understand my mistake. Tha...
To make your code work you need to put it in a function and there should be a main function too. struct person { int a; char s; }; int main() // you need to have a main { // code needs to be in a function /*struct*/ person test; // struct is not needed test.a = 12; return 0; }
71,030,038
71,032,888
How to get template class template parameter?
I have a template class and want to know, how to get template class variable type when it is used as a template parameter of function. I tried to do the following #include <iostream> #include <type_traits> using namespace std; template <typename T> class foo { }; template <typename templateClass> void f() { if (...
You can create traits to extract that information without changing originel types. template <typename T> struct template_parameter; template <template <typename ...> class C, typename T> struct template_parameter<C<T>> { using type = T; }; template <typename T> using template_parameter_t = typename template_param...
71,030,102
71,045,093
How to detect if left mousebutton is being held down with SDL2
I know how to use events to detect when the mouse button is pressed, however, how do detect if a mouse button is currently held down? Note I am not asking how to get it from an event. I have not tried anything apart from SDL_GetMouseState(&x, &y); however it seems to only return the X and Y position of the mouse.
SDL_GetMouseState() returns the buttons that were pressed. Example: if (SDL_GetMouseState(...) & SDL_BUTTON_LMASK) // Left button is pressed.
71,030,397
71,035,870
stable partition in c++ - why is it O(n lg n)?
I was looking at the possible implementation of stable partition in c++: https://en.cppreference.com/w/cpp/algorithm/ranges/stable_partition it’s stated this is at worst O nlgn. How is this possible? it seems like in the worst case a rotate is called at every index, resulting in an O n**2 algorithm.
As ALX23z notes, the sample implementation is not conforming with respect to running time. Here is what an O(n log n) in-place stable_partition could look like (at least from an algorithms perspective; if you want a library-grade implementation go look at the actual libraries). #include <algorithm> template <typename ...
71,030,923
71,032,922
How do I access data in "int20_t"?
I got a lot of memory pieces in 512 bits. I need to write numbers in 20 bits. For example: // a piece of 512 bits memory void *p = malloc(64); struct Coords { int20_t x, y; }; // usage Coords *pcoord = (Coords *)p; for (int i = 0; i < 512 / 40/*sizeof(Coords)*/; ++i) { pcoord[i].x = i; pcoord[i].y = 2 * i; } ...
The type int20_t is only available on very specific hardware with 20 bit registers. You do not need this type to handle your data, you can either use plain int to store the coordinates or possibly use bit-fields but it does not seems necessary. The main issue is the conversion from the external representation (12 packe...
71,030,981
71,031,427
VSCode deal the command parameter as literal
I want to build a Rasterizer project with opencv.The below command work well in shell(some parameter is omitted, such as -static-libgcc): g++ *.cpp -g -o Rasterizer `pkg-config --libs opencv` However, when I want to do the same thing with VSCode, it fails and throw an error: g++: error: `pkg-config --libs opencv`: No ...
let's try this . { "tasks": [ { "type": "shell", "label": "C/C++: g++ build active file", "command": "g++", "args": [ "${fileDirname}/*.cpp", "-fdiagnostics-color=always", "...
71,031,329
71,032,025
why does this for loop in C++ using getline() work
I compiled this nested for loop in C++. It works, however I don't understand why. Can you please explain the mechanics, and also any information on why the push_back() is allowed in addition to the increment. for (std::string line; std::getline(in, line); text->push_back(line), ++ln) // why does this work? { // do s...
The for loop for (A; B; C) { D; } is equivalent to { A; while (B) { D; C; } } and any of A, B, C, and D can be empty. If those parts are syntactically correct in the while loop, they are also correct in the corresponding for loop. So your nested loop is equivalent to { std::st...
71,031,682
71,031,744
Can only compile and run when including .cpp file
I'm doing some linked list practices in C++ and created a simple class for the single linked list. When I try to include the header-file in the main program however I get an undefined reference error. If I include the .cpp file however it works as I want it to. It's been a while since I last coded in C++ and I can't fo...
You include the header file, so prototypes are available, and the compiler does not complain. The linker needs to find the source associated with those functions. Using g++ -std=c++11 LinkedList.cpp -o LinkedList.exe to compile means that you're only using the main file source and not the other file that contains the l...