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,218,664
71,219,422
is it efficient to define random number generator inside function integrator?
Consider an Euler integrator that solves a stochastic differential equation: void euler(vector<double> &x0, vector<double> &dxdt, const double dt) { std::random_device rd; std::mt19937 rng(rd()); std::normal_distribution<> dist(0, 1); f(dxdt, t, dt) for (int i=0; i<x0.s...
Seeding a PRNG if often costly and should usually only be done once during the whole program run so, no, this is not efficient. I suggest that you break the creation of the PRNG out into a separate function that has a static PRNG (only initialized once). std::mt19937& rng() { static std::mt19937 instance{std::rando...
71,218,831
71,219,192
Undefined reference to shared object when linking with cmake
I am trying to create a shared object library that I can share with another person without sharing the ".cpp" files and without having to install it in "/usr/". In order to do so, since I am inexpert with cmake, I am starting with a minimal example, but I am having problems when importing the library. I have an Example...
The problem was fixed changing ${EXAMPLELIB} -> EXAMPLELIB set_property(TARGET EXAMPLELIB PROPERTY IMPORTED_LOCATION "lib/libExample.so") -> set_property(TARGET EXAMPLELIB PROPERTY IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/lib/libExample.so) As the user @KamilCuk suggested.
71,218,884
71,222,608
Dealing with multiple special opcodes
So I've been working on making a disassembler for Rockstar's scripting engine, and I'm currently dealing with adding all of the opcodes. To give a bit of background, each opcode is a string of bytes, with the first byte being the identifier to which opcode it is, followed by the data that opcode needs. The main problem...
If you need performance, I would go with the hardcoded table. If design is a big concerned and you can accept some performance lost, you could use the strategy design pattern. For example: class IOpcodeHandlingStrategy { public: virtual ~IOpcodeHandlingStrategy() = default; // Override this for every opcode, ...
71,220,383
71,234,093
C++: Array of differents types of objects (access to the methods of the child class)
I have created an array of Position which is a parent class of several classes : Player, Item, Mob, and Map. I want to create an array of several types of objects in my Position array (dynamically created object) and then want to use the methods of my objects which are unique. I can't use the virtual type because I wou...
You have following options, depending on what do you want to happen if the element doesn't contain the type you think it does: static_cast<Player *>(positionObject[i][j])->infoPlayer(); - undefined behavior on type mismatch. dynamic_cast<Player *>(positionObject[i][j])->infoPlayer(); - cast returns null on type mismat...
71,220,593
71,220,935
What is the reason for "stack smashing detected"?
I am new to programming and am currently studying about address typecasting. I don't seem to understand why I am getting this : *** stack smashing detected ***: terminated Aborted (core dumped) when I run the following code?? #include<iostream> using namespace std; void updateValue(int *p){ *p = 610 % 255; } int ...
The problem is that you're typecasting a char* to an int* and then dereferencing p which leads to undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefin...
71,221,127
71,221,321
What is the difference between a Technical Report and a Technical Specification?
The terms Technical Specification and Technical Report are used seemingly interchangably when talking about upcoming C++ features (e.g. here or cppreference.com), however I could not find any meaninful distinction or definition of the terms. What is the difference if there even is one?
Quoting The different types of ISO publications: International Standards An International Standard provides rules, guidelines or characteristics for activities or for their results, aimed at achieving the optimum degree of order in a given context. It can take many forms. Apart from product standards, other examples i...
71,222,176
71,229,159
fmt Library - Formatting to a (compile-time) string_view
I would like to use the fmt library to create a string_view from my format args. There is plenty documented about passing in a compile-time string as the format string, however, I want to output a compile-time string, so that I may use it in other static parts of my code. Is there a way to do this? So far, all the func...
You can do this with format string compilation (FMT_COMPILE): #include <fmt/compile.h> consteval auto example(unsigned i) -> std::array<char, 16> { auto result = std::array<char, 16>(); fmt::format_to(result.data(), FMT_COMPILE("You sent {}"), i); return result; } constexpr auto result = example(42); This give...
71,222,185
71,230,635
Boost::Graph-algorithm does not write data with PropertyMap (kamada_kawai_spring_layout, bundled properties)
I have a an adjacency_list graph with randomly connected nodes using Erdos-Renyi edge generation. The graph uses bundled properties by defining data structures both for the vertices (Graph_Node) and edges (Graph_Edge), which is used to assign the position of the nodes and the weights of the edges. I'm trying to use for...
The return value of the algorithm: Returns: true if layout was successful or false if a negative weight cycle was detected or the graph is disconnected. When you print it, you'll see that it is false. So, your graph doesn't satisfy the requirements. Raising the edge probability makes for connected graphs: Live On Com...
71,222,196
71,237,113
Visual Studio project dependancy question
I have a Visual Studio solution with projects A, B, and C. A and B are indpendant and should do some task T every time they are build. Project C is denendant to A, B and when C is built, task T should be done as well. For any case it's needed task T to be done once. First approach: I tried to trigger task T as pre-buil...
My colleague suggested to add this to vsxproj file: <ItemGroup> <UpToDateCheckInput Include="$(SolutionDir)\a.txt" /> </ItemGroup> It is path to a nonexisting file a.txt. Now it is built every time
71,222,422
71,222,423
How can I auto-format Rust (and C++) code on commit automatically?
I would like to automatically format the code when I do commit using rustfmt the same way as I did it before for clang-format -i. I.e. format only the lines of code which has been updated in the commit without touching other code. How to do it?
It might be done using git pre-commit hook in the following way: Add file pre-commit to the folder .githooks in your repo with the following text: #!/bin/bash exe=$(which rustfmt) if [ -n "$exe" ] then # field separator to the new line IFS=$'\n' for line in $(git status -s) do # if added or...
71,223,105
71,223,374
c++ equivalent to python self.attribute = ObjectInstance()
i want to know if there is an equivalent way of doing this in c++: class B: def foo(self,parameter): print("B method call from A, with non static method",parameter) class A: def __init__(self): self.b = B() parameter = 10 a = A() a.b.foo(parameter)
self.b in C++ could be this->b, but also just b as this is implicit in C++. However, in C++, you have to declare (member) variables, while in Python you create them by assigning to them and the type of the variable is determinated by this assignment and can be changed. So next code is similar (not compiled, tested): #i...
71,223,301
71,223,330
C++20 No more dependent scope needed
I have upgraded to c++20 recently and noticed that the compiler doesnt throw an error when i dont put typename infront of a dependent cope type alias e.g. using iterator = (no typename here) std::vector<int>::iterator Is this now part of the new c++20 standart or is it just a gcc thing and not all compilers do this?
It is a C++20 thing: In some contexts, only type names can validly appear. In these contexts, a dependent qualified name is assumed to name a type and no typename is required: A qualified name that is used as a declaration specifier in the (top-level) decl-specifier-seq of: a simple declaration or function definit...
71,223,385
71,223,840
Using a function with a variable number of arguments
Consider the following code: #include <iostream> int var_arg_func(...) { std::cout << "Func called!"; } int main() { var_arg_func(0, 1, 2); } As you can see here I can pass a variable number of arguments to the function var_arg_func. But my question is how can I access those arguments from the function itsel...
You can use variadic templates. One example for printing out all the passed argument is given below: #include <iostream> //provide an ordinary function to end recursion void print () { } template<typename T, typename... Types> void print (T firstArg, Types... args) { std::cout << firstArg << "\n"; // printing the ...
71,225,774
71,227,357
segmentation fault when acessing attribute of an smart pointer to class, inside another class
i tried to make this: #include <iostream> #include <memory> class B { public: std::string var; B() { var = "original"; } void print() { std::cout << "composition " << std::endl; } }; class A { public: int a_attribute = 10; std::unique_ptr<B> b; }; ...
You problem is here, in A you have std::unique_ptr<B> b; this creates a smart pointer to a B object. But it there is no B object that it points at. Before you can use it you must create a B object and set 'b' to point at it. I dont know exactly how and when you want to create your B but you can do this A a; a.b = std:...
71,226,082
71,226,403
ITK image allocation and sysmalloc
I am currently inheriting old code and trying to run it. As part of this there is an image generation done through ITK (which has been built and installed on the system) The (truncated) function causing issue at the moment is the following void PrintDensityImage(std::vector<float> *HU, imageDimensions dimensions, std::...
The error comes from malloc.c, so from C run-time library. Are you using some experimental or beta version of compiler? Or some modified CRT? Or some software which replaces malloc by their own version (e.g. to track memory leaks)? I doubt this has much to do with ITK. What happens if you replace image->Allocate(); by ...
71,226,137
71,226,232
Does accessing the 4 bytes of a float break C++ aliasing rules
I need to read the binary content of a file and turn the extracted bytes into single precision floating point numbers. How to do this has already been asked here. That question does have proper answers but I'm wondering whether a particular answer is actually valid C++ code. That answer gives the following code: float ...
Is this actually valid C++ code? Potentially yes. It has some pre-conditions: std::uint8_t must be an alias of unsigned char sizeof(float) must be 4 bytes + 3 mustn't overflow a buffer. You can add a checks to ensure safe failure to compile if the first two don't hold: static_assert(std::is_same_v<unsigned char, st...
71,227,116
71,227,159
Default initialization explicit constructor c++
How does default initialization work in C++11 if the default constructor is explicit? For example: #include <iostream> struct Foo { int x; explicit Foo(int y = 7) : x{y} {} } int main() { Foo foo; std::cout << foo.x << std::endl; } In main, the variable foo is default initialized. Based on my understanding,...
Your use is okay. The worst thing that could happen would be that the compiler would not be able to use the constructor since it is explicit and fail to compile. However, defining a variable as you have will correctly call the explicit default constructor. The use of explicit for a default constructor prevents uses lik...
71,227,360
71,227,535
CMake Release evaluates bool when compiling, not during execution
I'm working on a multi-threaded project. I am using CMake to compile. I have one file/function that sets a bool to true every so often #include <chrono> void mainloop_click(int *cpm, bool *click, bool *end) { auto start_time = std::chrono::system_clock::now(); while (!*end) { *click = false; wh...
Your code contains several errors which results in Undefined Behavior. I'll highlight two in this answer that could explain the behavior you observe. A bool, like most objects, can't be used to communicate between threads without synchronization. You have two threads, one that writes to and one that reads from the same...
71,227,845
71,227,919
C++ inline initialize static function member
I want to implement a member function as follows: void X() {} class Foo { static void(*Bar)() = X; }; This does not compile: error: 'constexpr' needed for in-class initialization of static data member 'void (* Foo::Bar)()' of non-integral type I know this is not legal. I have to either initialize Bar outside of...
Since C++11 you can use constexpr to initialize static members of non-integral/enumeration types in the class declaration. As @paddy comments below, this makes Bar const so it would only be a viable solution if you don't plan to modify it, what you are not doing in the question's code. [Demo] #include <iostream> // co...
71,228,609
71,228,651
How to compare number in a string with length of the string?
I'm new at programming and I'm trying to make a code that checks if a number inside of a string equals to the length of a string. I don't understand why it doesn't work. Can somebody explain what's wrong with my code? #include <iostream> using namespace std; int main() { string str; cin >> str; int length = st...
You forgot to parse the value of the character into an actual integer: #include <iostream> using namespace std; int main() { string str; cin >> str; int length = str.length(); int number = 0; for (int i = 0; i < str.size(); i++) { int a = 1; if (('0' < str[i]) && (str[i] <= '...
71,228,700
71,228,740
Storing an unsigned integer in std::any
Can I make ::std::any hold an unsigned integer? Something like: ::std::any a = 4; unsigned int x = ::std::any_cast<unsigned int>(a); results in an ::std::bad_any_cast exception because a actually holds a signed integer.
Yes, just put an unsigned integer in it: ::std::any a = 4u; // or ::std::any a = static_cast<unsigned>(4); https://godbolt.org/z/vzrYnKKe9 I have to caution you. std::any is not a magical tool to convert C++ into a dynamically typed language like python or javascript. Its use cases are very narrow and specific. It's ...
71,229,047
71,229,216
returning multiple value in a loop
In my program I try to return two values after performing operations in the "Durchfluss" method. These values should then be displayed in the loop. but when I display them I get 0 for f_ml1 and 170 for f_ml. why do I get 0 for the variable f_ml1? where is the error? This Method has been calling in a loop. class Sensor ...
Frankly, I would add a pair of getter methods and read f_ml1 and f_ml directly from your sensor object: class Sensor { ... public : int get_f_ml1 () { return f_ml1; } int get_f_ml () { return f_ml; } ... } void loop() { sensorOne.Durchfluss(); Serial.println(sensorOne.get_f_ml1()); Serial.println(...
71,229,120
71,229,237
Using a std::vector<std::array<T,N>> as a flat contiguous array of T
A std::vector stores its elements contiguously in memory. An std::array<T,N> is just a wrapper around N contiguous T elements, stored directly in the object itself. Hence I am wondering if a std::vector<std::array<T,N>> of size n can also be seen as an array of T of size N*n. Consider the following code (also here): in...
No, but yes. No, the C++ standard does not let you treat structs with arrays in them, or even structs with uniform elements, packed together as a single contiguous larger array of the base type. Yes, in that enough in world production code requires this to work that no compiler is going to break it from working any tim...
71,229,230
71,229,489
C++ Raylib how to detect the side of a rectangle that a circle has collided with
I can use the function CheckCollisionCircleRec(Vector2{ x, y }, radius, paddleRect) to find out simply if my circle has collided with my rectangle, but I want to be able to find out what side of the rectangle my circle has collided with. How would I go about doing this? None of the algorithms I've made are working. Exa...
A simply way is to use the PREVIOUS location of your circle. Not sure if you can in your program, but since you have an x and y handy, I'll assume you can have a prevX and prevY. I'll also assume these values represent the CENTER of the circle. Now if (prevX < paddleRect.x), then you likely collided with the left side ...
71,229,468
71,229,641
C++ Is there any fast way to detect how many std::vector elements has been updated/modified?
I'm currently implementing a caching system that has a similar API to std::vector, but it has a member function called Flush, which is for transferring elements to somewhere(e.g. hardware, network, etc.). What I want to do is to make the caching system be able to minimize the transfer overhead through flushing, by just...
The short answer to the question that's contained in the title of this question is simply "no", there's nothing like that, neither in vector nor any other C++ library container. If you need to track changes to the values in the container it will be up to you to implement the entire scaffolding that does so. Other than ...
71,229,527
71,229,662
Why does a Member initialized list for a default constructor in a composite class not call the member object constructor?
The Member initialized list for a default constructor in a composite class does not call the member object constructor. #include <iostream> struct test{ test(){ std::cout << "defualt is called" << std::endl; } test(int num){ std::cout <<"parameter is called" << std::endl; } }; struct tes...
test2 b(); is a function declaration, not a variable declaration. It declares a function named b that takes no arguments and returns a test2. Either of the following would produce a test2 variable that uses the default constructor: int main(){ test2 b; // No parentheses at all } int main(){ test2 b{}; // Curly...
71,229,574
71,229,642
C++ GetCursorPos always returns NULL
I'm writing a MFC program and I want to get the selected tree item by using HitTest(). Below is part of my code: POINT ptMouse; GetCursorPos(&ptMouse); TRACE("x = %f, y = %f\r\n", ptMouse.x, ptMouse.y); TRACE("Error Code %s\r\n", GetLastError()); m_Tree.ScreenToClient(&ptMouse); TRACE("x = %f, y = %f\r\n", ptMouse.x, p...
The problem is that ptMouse.x is not a float! But %f parses a float. Replace %f with %d and it should print a proper value. For example, this program: #include <Windows.h> #include <cstdio> int main() { POINT p; GetCursorPos(&p); printf("\nx: %f\n", p.x); printf("\nx: %d\n", p.x); return 0; } Giv...
71,229,810
71,229,883
Implementing Delta Time (In Seconds) into Velocity
Using C++, SDL2, and Vulkan, I'm trying to implement delta time into my game movement by multiplying movement speed by delta time like so: velocity += speed * dt; I've got this code below which apparently calculates delta time dt, but I don't really understand much of it and what I need to modify in order to be able t...
Never change the velocity, instead let your physics calculations include delta time as a component. In general, multiply by (delta_since_last_frame/arbitrary_constant_you_tune). EDIT* For example: position += velocity * (delta * ARBITRARY_TUNING_CONSTANT); It's tempting to set ARBITRARY_TUNING_CONSTANT to TARGET_FPS/10...
71,229,874
71,230,110
With FlatBuffer full reflection get the underlying vector type?
Using the FlatBuffer full reflection Relevant code const reflection::Schema& schema = *reflection::GetSchema( binary_fbs_file.c_str() ); auto root_table = schema.root_table(); auto fields = root_table->fields(); for (size_t = 0; i < fields->size(); i++) { auto field = fields->Get( i ); // 14 is the enum numbe...
field->type()->element() Is the type of the vector contents. See reflection.fbs for details on element.
71,230,435
71,231,202
How to fix gcc warning "friend declaration declares a non-template function"
So I have some code here that compiles with gcc, clang, and msvc: #include <cstdio> #include <type_traits> struct c_class; template <class T> struct holder { friend auto adl_lookup(holder<T>); }; template <class C, class T> struct lookup { friend auto adl_lookup(holder<T>) { return holder<C>{}; } }; struct cpp_cl...
The second snippet is ill-formed, because a friend declaration cannot be a definition of a template specialization. An open clang bug report for accepting this is here. The first one seems valid to me. The warning by GCC is annoying, because defining a non-template function as friend is what you want to do here. Unfort...
71,231,065
71,231,258
How to declare a member variable that is only visible to one class method per class instance?
Is there a way to declare member4 that only visible to Function1 and it is not shared by all instances? class Test { public: void Function1() { ???? int member4 //visble to Function1 (single instance) } void Function2() { static int member3;// visble to Function2 (all instances)...
Your question looks like an XY Problem. Anyway, here are two possible solutions. First, you could wrap the field into a class and declare the method as a friend: class Test { public: // Don't forget to init Data: Test(); void function1(); void function2(); private: class Data; Data *data; }; ...
71,231,731
71,231,968
Recursively finding all paths in a grid
I am writing a small program that calculates--recursively--all paths to (0,0) on the grid given some walls that need to be avoided. The grid looks something like this: . . . . . . . . . . . | . . | . . . . . . . . . | . . . . . . . . . . - - - . . - - - - . | . . . . . | . . . . . . . . | . | . . . . . . . . . -...
I noticed at: return recursive_find_path(x-1,y, distance-1,blocked_grid)+recursive_find_path(x,y-1, distance-1, blocked_grid)+recursive_find_path(x+1,y, distance-1, blocked_grid); The two points (x + 1, y) and (x - 1, y) cannot both be closer to the origin, yet you pass (distance - 1) to both of those recursive calls....
71,232,149
71,232,518
Inter-process communication (C++ to C#) using Memory mapped file (IOException)
There are two processes: one written in C++ and the other written in C#. Simply, C++ process will create a file name "test.dat", map the file to its memory, and keep on writing on it. C# process on the other hand will open the file and read whenever there is a change on the memory. The problem is that on the C# end, it...
FileStream defaults to only allowing read sharing which is not compatible with how you've opened your c++ file. You need to request write sharing too: File.Open(@"...", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
71,233,059
71,253,039
`ld` undefined reference error, but libraries are linked to by CMake and symbols exist
I have a CMake file like this: cmake_minimum_required(VERSION 3.12) project(cpp-service VERSION 0.1.0) add_compile_definitions(OPENVDB_7_ABI_COMPATIBLE) list(APPEND CMAKE_MODULE_PATH "/usr/local/lib64/cmake/OpenVDB/") find_package(OpenVDB REQUIRED) ### https://stackoverflow.com/a/69290761/3405291 list(APPEND CMAKE_MO...
Fix The cause of the linker errors was this statement: if(LINUX) The fix was to replace it with this: if(UNIX AND NOT APPLE) This commit fixes the problem: Reference: https://stackoverflow.com/a/40152725/3405291 Strangely, CMake wasn't complaining about anything and just throwing random linker errors.
71,233,631
71,234,540
c++ implement of array broadcast
In python language, we can use A[A!=0]=-10 to trans all the non-zero value in A to -10. How can I implement this function in C++ language or is here any similar function in 3rd party? #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> using namespace std; usin...
Range-based for loops will not work since the cv::Mat::begin() is a member function template. You'll have to use begin<mat_type>() and end<mat_type>(). Example: #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <algorithm> #include <iostream> #include <iterator> int ma...
71,233,815
71,234,161
MySQL statement is exiting my for loop without finishing the iteration C++
I am working on a project, and I need to push a list to my database. I want to iterate through the said list and execute a statement that adds said list to my table. Running the exact script within MySQL works perfectly fine. However, when I try to iterate through the list and run the script, it does it once before exi...
I seem to have figured it out after a bit of digging on the website and found that I needed to use execute() not executeQuery().
71,234,694
71,253,885
Why this include order causes link error on unordered_map?
I had a problem with include order that I cannot explain. I will show you a minimal example with four files: // A.h #pragma once #include <functional> struct A {}; namespace std { template<> class hash<A> { public: size_t operator()(const A&) const { return 0; }; }; } // B...
I tested the same code in Visual Studio 2022 and got the same error. After my exploration, I found the problem. Firstly, I copied the contents of A.h and B.h into main.cpp and removed the #include directive. After compiling, I still got the same error. Then I tested and found that as soon as I moved namespace std {...}...
71,235,133
71,235,160
Iterate over two possible types of iterable objects C++
I'd like a program of mine to be flexible and for it to either be able to iterate over a list of files in a directory for which I'm currently using for(const auto& dirEntry : fs::directory_iterator(input_dir)) where fs is filesystem. I'd also like the possibility of iterating over a vector of strings, and to c...
You can extract the code with the loop into a template, e.g. template<class Range> void DoWork(Range&& dirEntries) { for (const auto& dirEntry : dirEntries) ; // ... } and then instantiate/call the template with DoWork(fs::directory_iterator(input_dir)); or DoWork(myVectorOfStrings); Note that whatever y...
71,235,171
71,236,368
Function with single optional parameter and default value in template function
I want a function with has only 1 argument which is optional with generic type and has assigned boost::none as default value. Is that possible? #include <iostream> #include <string> #include <boost/optional.hpp> template <typename T> void f(boost::optional<T> v = boost::none) { if (v) { std::cout<<"v h...
Mmm the other answer is close. But not quite there. f(12) doesn't "try to instantiate f<int&&>". In fact, it fails to deduce T because T is in non-deduced context. Also, your question was beside the point: even without a default value you have the same problem: Compiler Explorer template <typename T> void f(boost::opti...
71,235,683
71,235,825
Unnamed union member has non-trivial operator
I am working on a project started back to 1980s, my mission is to substitute the primitive double with the Dummy class I create. The following is the simplified problematic code: class Dummy{ private: double d; public: Dummy(){}; Dummy(double d1): d{d1}{}; Dummy& operator = ( const Dummy& dm ) { ...
Not sure if those modifications are possible for you, but following compiles class Dummy { private: double d; public: Dummy() = default; Dummy(double d1): d{d1}{} Dummy& operator = ( const Dummy& dm ) = default; }; struct A{ bool isDummy = true; union{ Dummy dm; int i; ...
71,235,818
71,236,051
OpenCV: Stack Vectors to Mat
I got 3 Vec3f and want to stack them to a 3x3 Matrix (C++). Is there a nice way to to so? In python its easy with numpy, however I dont know if there is a better way than assigin every single value from Vector to the corresponding Mat entry? Cheers
Yes you can. It depends on the precise packing arrangement that you want, but the simplest way is to simply copy their bytes into a properly sized Mat. You access the bytes of a single Vec3f instance Vec3f v by using &v[0]. You access the bytes of a matrix Mat m by using m.data (not a function). Here's an example: cv::...
71,235,900
71,236,432
Why can variables be initialized(and used) without its declaration and definition "being run"?
C++ disallows "goto-ing over a definition:" goto jumpover; int something = 3; jumpover: std::cout << something << std::endl; This will raise an error as expected, because "something" won't be declared(or defined). However, I jumped over using assembly code: #include<iostream> using namespace std; int main(){ asm("...
Jumping between asm() statements is not supported by GCC; your code has undefined behaviour. Literally anything is allowed to happen. There's no __builtin_unreachable() after it, and you didn't even use asm goto("" ::: : "label") (GCC manual) to tell it about a C label the asm statement might or might not jump to. Wha...
71,236,946
71,240,197
How to interface an existing class
I have this Class that have an enum "AT_Color" inside: class K_DxfDwgColor { enum AT_Color { Normal = 0, ByLayer = 1, ByBlock = 2 }; COLORREF m_crColor = 0; AT_Color m_atColor = AT_Color::Normal; public: K_DxfDwgColor(COLORREF pkColorref) :m_crColor(pkColorref) {}; K_DxfDwgColor(K_DxfDwgColor::AT_Color paCol...
Move the enum outside of the class, it is necessary to be known from the calling party: enum AT_Color { Normal = 0, ByLayer = 1, ByBlock = 2 }; class K_DxfDwgColor { public: K_DxfDwgColor(AT_Color paColor):m_atColor(paColor){}; }
71,237,422
71,238,172
Where to use an rvalue as a function parameter?
I know there are plenty of questions about the argument, but I still don't understand some basic stuff about rvalues. Supposing I have a function of this kind: /* 1 */ void func( std::string s ) { /* do something with s */ } which I use in this way: int main() { func( "a string" ); } In a case like that, in which I...
In your specific example where a temporary string is created at call time, both expressions are equivalent. Indeed, you could not keep both and use overload resolution, because they capture the same type of object (again, only in your example). They both can capture the temporary string and have it available in paramet...
71,238,176
71,239,650
How can I pass args to a curl request executed via boost::process:child?
I'm able to execute a http POST request using curl via boost::process::child by passing the entire command line. However, I would like to pass the arguments via boost::process::args but I cannot get it work. This works: const std::string cmdDiscord = "curl -X POST https://discord.com:443/api/webhooks/1234567890 -H \"co...
It should be std::vector<std::string> argsDiscord {"-X", "POST", "https://discord.com:443/api/webhooks/1234567890", "-H", "content-type: application/json", "-d", "{\"content\": \"test\"}"}; Since command i...
71,238,876
71,239,229
Can a VAO name be re-used after calling glDeleteVertexArrays by calling glGenVertexArrays later?
It is my understanding from the OpenGL documentation that a VAO can be deleted (glDeleteVertexArrays), and then later regenerated (glGenVertexArrays). However, I have an issue when I am getting an OpenGL error when trying to re-use an existing VAO variable in a Chunk class (for a Minecraft clone). This only happens for...
Just as delete ptr; in C++ or free(ptr); in C does not actually change the pointer value of ptr variable, calling glDelete* on an OpenGL object does not change the value of the variables you give it. It is up to you to not use the variable again or to assign it to a neutral value. That having been said, if your intent ...
71,239,663
71,783,407
Does callback copy jnienv, jinstance inside a JNI function?
The lambda that I pass to builder is populated into className object, and called at regular intervals (every hour) of time to refresh the other members. It gets called the first time successfully. I'm not sure if the lambda retains env, instance to legally call the reverse JNI function? JNIEXPORT jint JNICALL Java_com_...
To answer this question, I have found a slightly different kind of hack. Don't copy the JNIEnv, and object or create references to them. They get deleted as soon as your JNI function goes out of scope. I'm not sure why copying doesn't work (if someone could answer this, that would be great). Alternatively, I've used Ja...
71,240,104
71,240,299
How do c/c++ preprocessors work when encountering unknown directives?
Do c/c++ preprocessors process all lines that begin with #? Does is errors out when encountering unknown macros or will it just ignore them? for an example, #include <stdio.h> #hello int main(){ printf("Hello World!"); return 0; } what happens in this situation?will it produce an error or will it work (ignori...
The language grammar specifies all pre-processor directives that exist in the language. If you use any other name for the directive, then that is a "conditionally-supported-directive". If the conditionally supported directive isn't supported, then the the language implementation is required to issue a diagnostic messag...
71,240,128
71,241,469
Writing to Framebuffer using multiple shaders
I'm currently implementing skeletal animation in my deferred rendering pipeline. Since each vertex in a rigged mesh will take at least an extra 32 bytes (due to the bone's vertex IDs & weights), I thought it would be a good idea to make a different shader that will be in charge of drawing animated meshes. That being sa...
Turns out that I wasn't clearing my vector of render submissions, so I was adding a new mesh to draw every frame.
71,240,343
71,243,977
How do I pack a Gtk::Entry into a Gtk::HeaderBar so the entry completely fills the header bar?
I'm making a program in gtkmm-3.0 which has a Gtk::HeaderBar as the title bar. I'm trying to pack a Gtk::Entry into it using this code: Gtk::HeaderBar headerBar; Gtk::Entry entry; headerBar.set_hexpand(); headerBar.set_halign((Gtk::Align)GTK_ALIGN_FILL); entry.set_hexpand(); entry.set_halign((Gtk::Align)GTK_ALIGN_FILL...
The problem is that Gtk::HeaderBar also has a "title" widget taking space. You could set a title, resulting in this: An you see why only half the screen was given to the entry. One workaround is to define your own, custom, header bar. Here is an extremely minimal example: #include <gtkmm.h> class MainWindow : public ...
71,240,481
71,240,723
why the below boost variant visitor code doesnt work
I have a struct A: struct A { //some implementation } My boost variants are: boost::variant<double, A> v1 = 1.0; boost::variant<double, A> v2 = 2.0; My visitor functor is defined as: class SomeWork: public boost::static_visitor<int> { public: int operator()(const A& data1, const A& data2) const {...
boost::apply_visitor needs to consider every possible combination of types that your variant instances hold. This means SomeWork is missing the following combinations: int operator()(const A& data1, const double& data2) const { //some work return 3; } int operator()(const double& data1...
71,240,604
71,240,761
Can I use a const char* or std::string variable containing grammar as argument to libfmt?
Hopefully this is a silly question. I have the following code: #include <iostream> #include <fmt/format.h> #include <string> int main(){ double f = 1.23456789; std::cout << fmt::format( "Hello {:f} how are you?\n", f ) << "\n"; return 0; } And this works as expected --Hello 1.234568 how are you? But if I want to en...
Since libfmt 8.1, you can wrap the format string in fmt::runtime to enable runtime formatting: #include <iostream> #include <fmt/format.h> #include <string> int main() { double f = 1.23456789; const char* m = "Hello {:f} how are you?\n"; //can't be constexpr, generated at run time std::cout << fmt::format(fmt::runti...
71,240,646
71,242,266
C++ Template explicit rvalue type
#include <iostream> using namespace std; namespace mine { template <typename T> struct remove_rval { using type = T; }; template <typename T> struct remove_rval<T&&> { using type = T; }; template <typename T> void g(const T& = typename remove_rval<T>::type()) ...
From dcl.ref/p6: If a typedef-name ([dcl.typedef], [temp.param]) or a decltype-specifier ([dcl.type.decltype]) denotes a type TR that is a reference to a type T, an attempt to create the type lvalue reference to cv TR creates the type lvalue reference to T, while an attempt to create the type rvalue reference to cv TR...
71,240,929
71,241,106
why infinite loop terminates? or go infinite
I was trying a test and I wrote this program... #include<iostream> using namespace std; main() { int arr[5]={1,2,3,5,3}, num=5; for(int i=0; i< num; i++) { for(int j=(i+1); i< num; j++) { if (arr[i]==arr[j]) { cout<<"test"; } co...
Without the if (arr[i]==arr[j]), you simply have an infinite loop, which is perfectly valid in this case. j will just keep getting incremented (eventually this will overflow, which in undefined behaviour, see [basic.fundamental]/2), and the condition will never be met, since i does not change. However, with the if (arr...
71,241,706
71,241,790
Sum of 1 + 1/2 + 1/3 +.... + 1/n without iterations using digamma function and Euler's constant
So i like to make my life hard, i've got a task to calculate the sum of 1 + 1/2 + 1/3 + 1/4 +.... + 1/n. The conditions is to not use iterations but a closed formula. On this post : https://math.stackexchange.com/questions/3367037/sum-of-1-1-2-1-3-1-n I've found a pretty neat looking solution: 1+1/2+1/3+⋯+1/n=γ+ψ(n+1) ...
Euler is known for having a lot of things named for him. That can easily become confusing, as seems to be case here. What you are adding to the digamma function result is Euler's number. You are supposed to add Euler's constant, which is a different number named after Euler. You can find the correct number in boost as ...
71,241,717
71,241,827
How to initialize nested array of structs in C++?
I have the following definitions: struct Display_font_char { unsigned char * data; int originX; int originY; unsigned int width; unsigned int height; unsigned int delta; }; struct Display_font { Display_font_char * chars; unsigned char rangeStart; unsigned char rangeEnd; }; How c...
You cannot initialise a pointer with a braced init list of multiple values. Here is an example of how you could initialise an instance of the class: unsigned char uc[] = { 1, 2, 3 }; Display_font_char fc { uc, 1, 2, 3u, 4u, 5u, }; const Display_font font = { &fc, 1u, 2u, }; As a s...
71,241,817
71,242,096
Returning a pair of objects
The following is an anti-pattern: auto f() { std::vector<int> v(100000); return std::move(v); // no need to use std::move thanks to RVO (return value optimization) } Using a std::move can even produce worst code (see here) However, what should I do in the following situation: auto f() { std::vector<int> v0(10000...
For the second snippet, auto f() { std::vector<int> v0(100000); std::vector<int> v1(100000); return std::make_pair(std::move(v0),std::move(v1)); // is the move needed? } return returns the result of the std::make_pair() function. That's an RValue. However, the OP's question probably condenses to whether (or why ...
71,241,987
71,472,305
How to assert that constructor throws exception using CppUnitTestFramework
Looking to verify that the constructor throws exceptions in the required places using CppUnitTestFramework. Assert::ExpectException<std::exception>(Service pService = Service(hServiceManager, L"NotValidName")); The above code doesn't work but I can't figure out how this should be implemented. Also can't seem to only e...
"Solution": Move to GTest if using Visual Studio
71,242,632
71,244,017
why "#define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1" doesn't work as expected?
Reference: https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/overview/core/handler_tracking.html https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/example/cpp11/handler_tracking/async_tcp_echo_server.cpp Based on the documentation, when enabled by defining BOOST_ASIO_ENABLE_HANDLER_TRACKING, Boost.Asi...
As the commenter helpfully pointed out: you have to define the preprocessor define before the first inclusion of any (!) Asio header. However, there's another reason why specifying it in your build script is FAR superior. Using BOOST_ASIO_ENABLE_HANDLER_TRACKING breaks interface. It must be defined in every translation...
71,243,379
71,243,564
pointer type operator VS const bool operator precedence
#include <cstdint> #include <iostream> struct a_struct { int64_t* le_int; bool not_ok; a_struct() : le_int{ new int64_t(0) }, not_ok{ false } {} ~a_struct() { delete le_int; } operator bool() const { return !not_ok; } operator int64_t* () { return le_int; } }; int ma...
Since your object s is not const, it prefers the non-const way of calling the type cast operator. So, removing the const from your bool type cast operator does the trick.
71,243,671
71,243,762
C++ vs Python execution time mathematical operations
I have the same code in two different languages: C++ and Python. C++ code: #include <iostream> float m = 16442.34; float c = 2434.1; float t = 0.34; int n = 3; float i = 934380.72; int k = 111; int ris = 0; int tot = 0; int main() { while(tot<1000000){ ris++; tot = (ris * (m - c)) - (int(ris/n) * ...
Python is an interpreted language while C++ gets compiled to machine code. This enables a C++ compiler to produce highly optimized code while the python interpreter "has to think more in order to execute the program". You could compile the python code (as Samwise said), e.g., with Cython. Also, you are using 32-bit flo...
71,243,721
71,246,506
absl::FormatSpec results in ambiguous function call under clang
Under Clang, the following code gives me an ambiguous function call error: #include "absl/strings/str_format.h" struct Foo {}; template<typename... Args> void func(absl::FormatSpec<Args...> format, const Args&... args) {} template<typename... Args> void func(Foo, absl::FormatSpec<Args...> format, const Args&... args...
The reason why you see different behaviour on GCC and Clang is that GCC and Clang are seeing different versions of the FormatSpec class, which is defined here On GCC, the ABSL_INTERNAL_ENABLE_FORMAT_CHECKER feature is off because this feature relies on the compiler-specific enable_if attribute, which is only supported ...
71,243,880
71,244,241
std::unique not working as expected with struct
I'm currently working on a 2D game where the level is defined by edges: struct Edge { vec2int start; vec2int end; } The struct vec2int is a vector with x, y coordinates and has all needed operators (in this particular case operator==) overloaded. Because of a data structure that stores the edges inside of a gr...
std::unique removes consecutive equivalent elements. In your example, you do not have consecutive equal elements, so it should not remove anything. If you do not care about the order of the elements in your range, you can sort it before calling std::unique.
71,243,906
71,249,619
GLFW Window poll events lag
I have a problem handling GLFW poll events. As far as I know, all user input events are handled via callbacks or via constantly checking keyboard / mouse states. The latter is not so efficient an can even result in missing some input (e. g. when button pressed and then released between checking state). What is more, so...
GLFW is not at fault here. It's how the operating system handles certain user input events like mouse down on the decorator resize handles of a window or moving the whole window. See this answer for a more elaborate detail: Win32: My Application freezes while the user resizes the window GLFW uses the standard Windows P...
71,243,910
73,235,853
What is the name of tool that gives you the declaration of a function in C/C++
Just a simple question about definitions in C/C++ toolchains and IDE's: What is the name of tool/mechanism/software that direction you to the declaration of the function like when, for example: You are in a Eclipse based IDE and press "CTRL + Left Mouse Button" on a function name and you are directioned to the function...
In summary, like said in comments the name of this tool depends of each IDE. But it could be described in general words as " 'go to definition' feature"
71,243,987
71,272,749
debug error: stack around the variable 's' was corrupted
edit(fixed): so the error seems to appear because writing a 20 character array will add \0 as a character and become a 21 character array. I'm trying to detect a char c and remove it from a string char[20] s, but if I wrote a string s of 20 characters exactly, the debug error pops but the code works fine. why does it h...
the error seems to appear because writing a 20 character array will add \0 as a character and become a 21 character array. by writing for example qwertyuiopqwertyuiop which is 20 characters, there won't be enough space in the array for the \0 character, so you should write a 19 character word (or less) or increase the ...
71,244,005
71,244,198
Euler function in C++
Can someone explain me, what is mean this Euler function: int phi (int n) { int result = n; for (int i=2; i*i<=n; ++i) if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } if (n > 1) result -= result / n; return result; } I...
We are iterating like this for the time performance because all prime factors of a number are equal or less with the square root of that number (if a number has not on of this, then it is a prime number). Then when we find a prime factor of the number we divide our number n by that factor until we can no longer divide ...
71,244,483
71,324,488
ARM 7 Assembly - ADC with immediate 0
I have written a little c++ function on godbolt.org and I am curious about a certain line inside the assembly. Here is the function: unsigned long long foo(uint64_t a, uint8_t b){ // unsigned long long fifteen = 15 * b; // unsigned long long result = a + fifteen; // unsigned long long resultfinal = result ...
The arm32 is only 32 bits. The value 'a' is 64bits. The instructions that you are seeing are to allow computations of sizes larger than 32bits. rsb r2, r2, r2, lsl #4 # 15*b -> b*16-b adds r0, r2, r0 # a+(15*b) !LOW 32 bits! could carry. adc r1, r1, #0 # add a carry bit to the high po...
71,244,634
71,244,680
Calling getters inside a setter function vs direct access to data members
The question is simple: Is it unnecessary to call getters inside setters to have access to an object's member variables? Suppose that all the getters are inlined and return const references to members. As an example: class Foo { public: inline const std::uint32_t& getValue( ) const noexcept { return m_v...
Code in the class always has full acess to the internal data members (and member functions too). So it is not necessary. My thoughts on if you should do it if the getters and particularly setters have side effects (imagine you keep a count of how many times a particular value is changed, or validate a value) then you ...
71,244,656
71,245,667
What define's Boost's svg_mapper scaling and translation?
This code: #include <fstream> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/polygon.hpp> namespace bg = boost::geometry; int main() { std::ofstream svg ( "test.svg" ); boost::geometry::svg_mapper<bg::model::d2::point_xy<double>, true, doub...
svg_mapper calculates a bounding box from all add-ed geometries. Then, a map_transformer is used to scale down to the desired width/height. Contrary to what you might expect, add doesn't do anything besides expanding the bounding box. Likewise, after the first map call, no other add has any effect on the bounding-box u...
71,244,738
71,245,097
Why does Forward List's methods have "after" version, instead of using List's interface?
insert, emplace, erase and splice from List, are replaced by insert_after, emplace_after, erase_after and splice_after in Forward List. Why is that? *I understand the difference between the methods, I'm asking why do we need a different method to do those operations
insert is defined as "insert before" for most containers, because end() iterator is defined as "one past the end". With insert() as "insert before", you can call it on whole range [begin(), end()], inclusive. If you defined insert() as "insert after", calling it on end() iterator would be Undefined Behaviour. This howe...
71,244,903
71,244,957
Is there any benefit at all for explicitly discarding a value via (void) in C
One of the uses of the void keyword in C/C++ is to discard the value of an expression: (void) expr; Is there any benefit at all of the above construct except to avoid "unused parameter" warnings like the below? void foo(int x, int y) { (void) x; //.. }
C++ Because void is not a reference to object type, the result of this cast is a prvalue even if the input was an lvalue. In C++ this is stated in [expr.cast]. Based on that fact, it should force an lvalue-to-rvalue conversion on the expression. For ordinary variables, such a conversion with discarded result has no s...
71,244,923
71,244,977
Can't use classes not defined yet in c++
So I am coding a program in c++, I got a version of the program that returns the same error: #include <iostream> class A { public: B foo() { return B(); } }; class B { public: A bar() { return A(); } }; int main(int argc, char const *argv[]) { A x = A(); B y = x.foo();...
You need to split declaration and definition. Also, you need to declare B as a class before A uses it. #include <iostream> class B; class A { public: B foo(); }; class B { public: A bar(); }; B A::foo() { return B(); } A B::bar() { return A(); } int main(int argc, char const *argv[]) { A x = A(...
71,244,933
71,244,934
Does POSIX require comparison operators for `pthread_key_t`, `pthread_once_t` and `pthread_t`?
The standards document for sys/types.h (https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_types.h.html), says "There are no defined comparison or assignment operators for the following types:", then lists a bunch of types. However, some of the non-arithmetic (or rather not-necessarily arithmetic) types are ...
TL;DR: Comparison or assignment of pthread_key_t and such may or may not be valid, depending on the particular pthreads implementation. Comparison or assignment of pthread_mutex_t and such must never be valid. No, it doesn't mean that conforming implementations have to provide comparison or assignment operators for tho...
71,245,006
71,245,345
What is the most accurate way to measure the time to perform a function, and what is its accuracy?
I'm working on a project that involves recording the time that a certain function takes to run one hundred times. I'm using a solution using the library but I seem to remember that there is a more accurate way that uses the processor's internal timing system for very accurate timing. Is there a better solution, and wh...
Using the chrono library will be your most accurate option likely. There is no way to know the resolution and accuracy of the clock without knowing exactly your setup, but you can assume it's small enough for all practical uses.
71,245,140
71,301,162
How to define a key value pair with values having a max size in c++
I would like to make a dictionary (may be similar to std::multimap) with several values for the same key. The main thing here is that I want the values to have a maximum size(n) and if an (n+1)th value comes, then the 1st value should be removed (like boost::circular_buffer or something). More specifically, I have a st...
Thanks everyone for the replies. I got it solved with help from fCaponetto. #include<iostream> #include <boost/circular_buffer.hpp> #include <map> #include <vector> struct Vis { double x; double y; double z; bool seen; uint id; }; typedef boost::circular_buffer<Vis> VisBuffer; typedef std::s...
71,245,181
71,248,238
How to create a 2d grid in OpenGl windows?
I am trying to print a 2d grid on my entire window. code: float slices(15); std::vector<glm::vec3> vert; std::vector<glm::uvec3> ind; for (int j = 0; j <= slices; j++) { for (int i = 0; i <= slices; i++) { GLfloat x = (float)i / (float)slices; GLfloat y = (float)j / (float)slices; GLfloat ...
Normalized device coordinates are in range [-1.0, 1.0]. Map the coordinates from [0.0,1.0] to [-1.0, 1.0]: vert.push_back(glm::vec3(x, y, z)); vert.push_back(glm::vec3(x * 2.0f - 1.0f, y * 2.0f - 1.0f, z));
71,245,195
71,245,290
How to bubblesort a pointers in the array without changing order of the array
So say I have two arrays intdataArray[10] = {61 34 46 114 73 29 13 93} and int *pointerDataArray[10] which has the pointers of the dataArray in the same respective index. How would I be able to sort the array through pointers and get the sorted array but also while still being able to print the original array. My bubb...
In your pointerSort function, you're calling the swapIntPtr function in the addresses of both integers. It actually changes the content behind the pointers, i.e., it swaps the integers. Instead, you want to call swapIntPtr with the address of the pointers and the function needs to change the pointers. void swapIntPtr(i...
71,245,261
71,868,328
How can I save a Window form in QTableWidget as it was a matrix?
I'm trying to save a Window form inside a QTableWidget table. int rows = 0; int columns = 0; QTableWidget cellTable; What I'm doing is that I first set the rows and columns cellTable.setRowCount(++rows); cellTable.setRowCount(++columns); For every time I increase the rows, I call this code for(int i = 0; i < rows; i+...
Casting should work if you've inherited from QWidget properly. Casts return nullptr if failed. So, it's safier to check if it's failed or not: if(databaseMeasurementType != nullptr){ //some works with databaseMeasurementType } It's recommended to use qobject_cast if you've written Q_OBJECT macro inside your class....
71,245,298
71,245,442
How can I store a uint32_t or uint64_t in a void pointer
I have a uint32_t (and in the future it might become uint64_t) variable. There is a function in one of the libraries that I use that allows passing a void pointer to it. How can I pass a uint32_t to this void pointer: uint32_t myEntity = 1242242; // not a pointer; so, error about invalid conversion actor->userData = st...
For what you are attempting, you need to use reinterpret_cast instead of static_cast, eg: uint32_t myEntity = 1242242; actor->userData = reinterpret_cast<void*>(myEntity); uint32_t myEntity = reinterpret_cast<uint32_t>(actor->userData); Since you mention that the value may be changed to a uint64_t in the future, just...
71,245,464
71,245,526
Conditional Incrementing Incorrectly
My function int numSteepSegments(const int heights[], int arrSize) { int mile = 0, steep_count = 0; while (mile <= arrSize) { int height = heights[mile]; int height_next = heights[mile + 1]; if ((height + 1000) < height_next) { ++steep_count; } else if ((height - 10...
C/C++ arrays are zero-based. The indices for an array with arrSize elements range from 0 to arrSize-1. Your loop index mile ranges from 0 to arrSize (inclusive), so heights[mile] is walking off the end of the array. Also, you are indexing heights[mile+1] which would exceed the array limits even if your index were lim...
71,246,119
71,246,158
How should header file look like for C++ projects?
I`ve studied C, and now I decided to switch to C++. So, in C, I used #ifndef #endif in my header files. Should I use the same commands in C++? Or are there some alternatives?
Yes, the preprocessor works (mostly) the same way, so you should still use preprocessor directives to guard against including the same code more than once. Any differences in functionality between the preprocessor in C and C++ are likely to be edge cases that are unlikely to be relevant at your current learning level.
71,246,461
71,250,882
Calling function from v8 engine throws error
I am making an application that requires me to call a function within some Javascript code. The problem is, despite looking it up many times, I still get the same error. No matching function for call to 'v8::Object::Get(v8::Local<v8::Context>&, v8::MaybeLocal<v8::String>)' I have looked up on several different posts ...
(V8 developer here.) @pm100's comment is spot on: Local and MaybeLocal are not interchangeable, a function that needs the former can't deal with the latter. The "Maybe" part of the name indicates that due to some error that may have happened (usually an exception), the value might be nonexistent. The required explicit ...
71,246,966
71,247,025
How to constrain my template to only accept lambda with specific input & output type?
Inspired by other question to calculate taylor series of a function(Original question), I wrote a template without any constraint to successfully calculate the sum. Here is current code (Template body removed, as @Elliott says it's irrelevant to the point..): #include <iostream> #include <cmath> #include <limits> temp...
I am trying to constrain the template to accept only lambda with unsigned long long int as a input, and long double as output. You can use compound requirements with return-type-requirement: template<typename F> concept my_lambda = requires(F f, unsigned long long int x) { { f(x) } -> std::same_as<long double>; }...
71,247,107
71,249,174
mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')
I want to use C++ functions in Python program, so I compiled the dynamic library file with the command: cc -fPIC -shared -o encrypt_for_python.so encrypt_for_python.cpp -L/opt/homebrew/Cellar/openssl@1.1/1.1.1l/lib -I/opt/homebrew/Cellar/openssl@1.1/1.1.1l/include -lssl -lcrypto -std=c++11 But when I used it in python...
I found this: file ~/miniconda3/bin/python /Users/debris/miniconda3/bin/python: Mach-O 64-bit executable x86_64 By installing python for amd64, I solved this problem.@Alan Birtles Thank you very much.
71,247,774
71,248,070
std::vector move assignment vs move construction: why is the state of 'other' not consistent?
For move construction: After the move, other is guaranteed to be empty(). 1 For move assignment, the oft-quoted: other is in a valid but unspecified state afterwards. 2 Why is the state of other different in these two cases?
There are 2 popular ways to implement move in containers like vector that internally hold a pointer to the data: you can empty this, then copy the pointer (and size and capacity) from other to this and then set other members to nullptr/zero you can swap the data members (the pointers, size and capacity). The standard...
71,247,792
71,247,997
Compiler generates call to memcpy from std::copy when pointers are of __restrict type?
The gcc compiler generates call to memcpy when i add __restrict to function parameters. How does compiler/standard library figure out that it can generate calls to memcpy when appropriate? void call_stdcpy_r(int *__restrict p, int *__restrict q, int sz) { std::copy(p, p+sz, q); // generates call to memcpy } void cal...
Your quote applies to std::copy_if, not to std::copy. The only requirement for std::copy is that q is not in the range [p,p+sz). The destination range is allowed to overlap and therefore memmove is the only option without additional assumptions, such as introduced by __restrict. __restrict guarantees the compiler that ...
71,248,187
71,248,485
Qt Application with layout's, QPushButton and QGraphicsItem
I am trying to draw various shapes like rectangle, ellipse, text etc uisng QGraphicsView and QGraphicsScene. For that I am trying to create an interface where there will be a vertical layout and besides that there will be few buttons. On clicking those buttons, I can show various QGraphicsItem's on screen. I want to cr...
Actually, it should work with the hints given in my comments. I made an MCVE to convince myself: #include <QtWidgets> int main(int argc, char **argv) { qDebug() << "Qt Version:" << QT_VERSION_STR; QApplication app(argc, argv); // setup GUI QWidget qMain; qMain.setWindowTitle("Test Box Layout"); qMain.resiz...
71,248,543
71,248,600
How come std::distance() doesn't work for rvalues?
For example: std::list <int> list1 = {1, 2, 3, 4, 5}; auto first = list1.begin(); std::cout << std::distance(--first, ++first); The output is 0. Strange enough, if we change --first to first--, the output becomes 5 (although here it should be 0, as it returns first). What am I missing?
The order in which the arguments in a function call are evaluated is unspecified. --first may execute first or ++first may execute first. If the former is the case, the decrement has undefined behavior, because decrementing a .begin() iterator is not allowed. Since one of the allowed execution orders has undefined beha...
71,248,851
71,249,222
How could one delay a function without the use of sleep / suspending the code?
I need to delay a function by x amount of time. The problem is that I can't use sleep nor any function that suspends the function (that's because the function is a loop that contains more function, sleeping / suspending one will sleep / suspend all) Is there a way I could do it?
If you want to execute some specific code at a certain time interval and don't want to use threads (to be able to suspend), then you have to keep track of time and execute the specific code when the delay time was exceeded. Example (pseudo): timestamp = getTime(); while (true) { if (getTime() - timestamp > delay)...
71,249,100
71,249,342
strange compiler error with friend function
The following code is rejected by GCC/Clang/MSVC though it seems to be able to compile. class B { }; class C : private B { friend B& to_B(C& c) { return static_cast<B&>(c); } }; class D : private C { friend C& to_C(D& d) { return static_cast<C&>(d); } friend B& to_B(D& d) { r...
I can't find chapter and verse to back it up, but C's private inheritance makes B completely private if it's looked up from within the definition of D. (Essentially, B is first looked up in the inheritance chain, and since name lookup stops at the first match, it is private to C. The global definition is never consider...
71,249,234
71,249,557
How to perform chmod recursively?
How can I change permissions to 0777, at runtime, of a folder and all its subfolders, recursively? The code is in c++, mac. I'm including <sys/stat.h> which has chmod, however there's no documentation on how to do it recursively.
The simplest and most portable way would be to use the std::filesystem library that was added in C++17. In there, you'll find a recursive_directory_iterator and many other handy classes and functions for dealing with filesystem specific things. Example: #include <iostream> #include <filesystem> // see notes...
71,249,356
71,249,400
Is it possible to enumerate functions in C++?
Suppose I have some functions which have the same parameters and datatype, and I want to push them into a std::vector and enumerate them. Is it possible to do this? Pseudocode: typedef int func(int, int); int add(int a, int b) { return a + b; } int minus(int a, int b) { return a - b; } vector<func> operation...
What you are missing in your code is a * in std::vector<func> because you want to store pointers to the function: #include <vector> #include <functional> #include <iostream> typedef int func(int, int); int add(int a, int b) { return a + b; } int minus(int a, int b) { return a - b; } int main() { std::vec...
71,249,522
71,249,566
Virtual destructor needed for class which is both derived and base?
Say we have the following: #include <iostream> struct A { virtual ~A() { std::cout << "destr A\n"; } }; struct B : A { // no need to be virtual? ~B() { std::cout << "destr B\n"; } }; struct C : B { ~C() { std::cout << "destr C\n"; } }; Now, I create an instance of C and assign it to a pointer of its...
Is ~B() virtual because I declared ~A() with the virtual function specifier? Yes. Per https://timsong-cpp.github.io/cppwp/n4659/class.dtor#10: If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.
71,249,538
71,249,604
Why i++ uses less memory than ++i while retaining same speed?
I was solving George And Accommodation and submitted two accepted versions of code with slight difference. Compiler used: GNU C++14 Version A (Time: 15ms, Memory: 4kb) #include <iostream> using namespace std; int main(){ int n = 0, p = 0, q = 0, a = 0; cin >> n; while(n--...
This is just a random effect. It has no meaning. The memory used is probably measured in pages, so the stack just happened to cross a page boundary in the second case. A page is typically 4kb. Whether you use a++; or ++a; is completely irrelevant if a is a built-in type. The compiler will compile it to exactly the same...
71,249,944
71,495,190
How to link libs in CLion?
I'm using CLion as my IDE for C++ development and I'm trying to get Eigen included. How do I do this? I've downloaded and unzipped Eigen and placed it in C:/ (Which I've read online is the path where CMake looks for libs when you use find_library()) In the CMakeLists.txt I've added find_library(Eigen3 3.4 REQUIRED NO_M...
The solution ended up being to use include_directories(C:/CPP_Libs/Eigen3) in my CMakeLists.txt, and #include <Eigen/Dense> in whichever file needs it
71,250,007
71,250,138
Why can my constant not be used to create my array?
I want to make an array that holds a number of tile objects (called Tile) but it's saying that my constant int, numTiles, cannot be used as a... constant int... what? The code I'm having issues with is here (error on line 5): // Variables - Tilemap const int tileSize = 32; const int screenWidth = GetScreenWidth(); cons...
Thanks to the people in the comments of the post for explaining this to me: The variables are calculated at runtime when they need to be calculated at compile time (this was due to my usage of GetScreenWidth(), which obviously cannot run during compilation).
71,250,043
71,250,397
How to store qt containers inside qt containers
Do I understand right that it does not make real sense to have QVector<QSharedPointer<QVariantHash>> and that I can stick just to: QVector<QVariantHash> due to implicit sharing? Honestly, using STL, I would never do like this and would have std::vector<std::shared_ptr<std::unordered_map<...>>>. UPDATE: My question is...
No, those have different behaviour. The QVector<QVariantHash> is still copy-on-write, so copies of the vector only share elements up to the first modification, whereas so long as you leave the pointers alone, the QVariantHashs pointed-to by the elements of QVector<QSharedPointer<QVariantHash>> will still be the same ob...
71,250,053
71,257,322
How to get value by field name in MYSQL xdevapi 8.0 connector c++
For connector c++ 1.1, in this example, it's quite easy to get values by specifying the column name (or alias name). But when I upgraded to version 8.0 xdevapi, I found this feature is no longer supported. #include <mysqlx/xdevapi.h> using namespace std; using namespace mysqlx; Session sess(<server_url>); auto result...
There is no way, at the moment, to get the column value using name. A way is, as you suggest, a map with the name / index pair. Something like this would work: SqlResult sql_res = sess.sql("select * from table").execute(); std::map<std::string, size_t> columns; auto fill_columns = [&sql_res, &columns]() -> void { si...
71,250,562
71,257,546
Why WinApi SendHttpRequest may be slow on VirtualBox machine
Testing my app on few machines show that WinApi HttpSendRequest performs slow sometimes. On non virtual machine it takes ~100-~300 ms, same results on virtual machine sending the same request through curl. But sending request with HttpSendRequest on virtual machine with Win10 takes ~5s and on Win7 - ~20s. Here is a sam...
Probably because VirtualBox has a network implementation that's a little bulky(ish). For me, it made a whole new network adapter (Virtual Ethernet, basically). What it does is, the VM thinks it's connected to Ethernet. Then the VirtualBox backend redirects it through my normal Wi-Fi. These kinds of things are very comp...