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
73,147,274
73,161,012
How to build Opencv code in a docker file
I want to build and run a c++ opencv code using docker. Here is my dockerfile: FROM nvidia/cuda:11.5.0-cudnn8-runtime-ubuntu20.04 FROM ubuntu ARG DEBIAN_FRONTEND=noninteractive RUN apt-get update && \ apt-get install -y \ g++ git wget cmake sudo RUN apt-get install -y \ build-essential cmake git libgtk2....
Using @emrhzc's answer I could build my code inside the dockerfile. Now my final working command is: RUN g++ -o wav wav.cpp `pkg-config --cflags --libs opencv4`
73,147,898
73,149,890
Inherit CTAD constructor
I have derived from std::tuple and but was unable construct the derived class from an initializer list due to issues with class template argument deduction. Is there a better way to construct such a class beyond just giving it an already constructed tuple first{ std::tuple{1, 1.0f, 1u} };. template <typename T, typenam...
Inherited constructors are not part of CTAD. You might replicate std::tuple's CTAD: template <typename T, typename... Types> first(T, Types...) -> first<T, Types...>; // auto tuple = first{1, 1.0f, 1u}; // is ok now // auto tuple = first{ std::tuple{1, 1.0f, 1u} }; // broken now Demo
73,147,987
73,148,066
Understand shell script interpreter with custom shell
I try to understood how shell script interpreter working. for example i wrote custom shell with c++ : #include <iostream> #include <string> using namespace std ; int main() { string input; while (1) { cout << "prompt:> "; cin >> input; if(input=="exit") return 0; ...
No idea what that means If you compile your program to /tmp/a.out and have an executable file script with: #!/tmp/a.out test wrong_command1 wrong_command2 exit which you invoke on command line as ./script then the shell running the command line will invoke /tmp/a.out ./script. I.e. looks at the shebang, invokes t...
73,148,061
73,148,647
Find Key index in a rotated sorted array using binary sort?
here in this code i am facing issues regarding my output of find the correct index for the key. the output of pivot element is correct but i was unable for find the error in the key index part of my code . can some debug it for me please or at least tell me where i was doing it wrong. this is a code of me trying to fin...
This looked supsicous: int mid = s+( e-s )/2; It's not using modulo arithmetic correctly. There's confusion of comparing arr[mid] with normalized vs. unnormalized coordinates and how that applies to recomputing start and end on each iteration of the binary search loop. You want start and end to be recomputed in the "...
73,148,526
73,148,594
Boolean If Statement with a Pointer to a Class
#define NULL 0 class Sample{ public: Sample():m_nNumber(0){} Sample(int nNumber):m_nNumber(nNumber){} ~Sample(){} int GetNumber(){return m_nNumber;} void SetNumber(int nNumber){m_nNumber = nNumber;} private: int m_nNumber; }; Sample* TestSample(Sample* mSample){ int nNumber = m...
Both is perfectly valid and though some might argue better ways exist to handle this, still used frequently. NULL is a valid value for a pointer. Checking if a pointer is NULL or not is valid (that is what an if statement is doing in C++, checking if the value given is not zero). What is not "allowed" is dereferencin...
73,149,011
73,149,053
Throw when reassigning
try { object = mayThrow(); } catch (const std::exception& exc) { //... } If mayThrow() actually throws, will the original object be untouched? Or is it better to do it this way? try { Object newObject = mayThrow(); object = std::move(newObject); } catch (const std::exception& exc) { //... }
Unless mayThrow() has direct access to object and does some monkeying within, the final assignment happens if and only if mayThrow() returns successfully and the object stays unchanged otherwise.
73,149,117
73,149,210
Class Pointer reference inside of another Class defined below? (C++ 14, VS 2019)
Problem Summary I'm attempting to write a series of classes in C++ 14, that are all supposed to be inside of the same class, and have pointer fields that point to object instances of each one of the classes. They are all also supposed to have constructors that assign those fields, using arguments that are pointers to t...
The problem is that you've forward declared class C in global namespace instead of class scope A. This means that there are two different class named C one of which is declared to be in the global namespace ::C and the second one as an inner class A::C. To solve this, just move the forward declaration of class C to in...
73,149,385
73,149,923
usr/bin/ld skipping incompatible ./libSPECcon.so when searching for -lSPECcon
Currently, I'm using Ubuntu 22.04. I have main.cpp and a .so file. I got this error when i try to compile with following command g++ -L. -Wall -o code main.cpp -lSPECcon. .so file and main.cpp are in the same folder It gives me this output: main.cpp: In function ‘int main(int, char**): main.cpp:51:22: warning: ISO C+...
I solve the problem by linking my .so file to /usr/lib. This question helped me: usr/bin/ld: cannot find -l<nameOfTheLibrary>
73,149,905
73,150,241
Which STD container to use to get [] operator and erase elements without moving memory around?
I used std::vector<MyClass> and everything was fine until I had to use erase() function. Problem caused by MyClass having MyClass(const MyClass&) = delete; MyClass& operator=(const MyClass&) = delete; This is needed because MyClass holds unique_ptr objects and I generally want to avoid copy. But at this point my code ...
As std::unique_ptr<T> is a moveable and non-copyable type, any class with a std::unique_ptr<T> member will by default be moveable and non-copyable (as long as all of the other members are at least moveable). #include <memory> #include <utility> struct A { std::unique_ptr<int> ptr; }; int main() { A a; //A...
73,150,688
73,150,845
What does this C++ pointer syntax mean?
Say datais a direct pointer to the memory array used by a vector. What then, does &data[index] mean? I'm guessing data[index] is a pointer to the particular element of the array at position index, but then is &data[index]the address of that pointer?
Start with working out the types. Suppose data is a T*; a pointer to the first element of an array of T. Then data[index] is a T, and that T is an element of the array. And since data[index] is a T, &data[index] is a T*; it is a pointer to the array element data[index]. Also, if data is a pointer, data[index] is equiva...
73,151,238
73,151,948
LNK1104 cannot open file 'libboost_regex-vc90-mt-gd-1_37.lib'
Hi my team developed some years ago an application which consists of c# windows forms and c++. All developers gone away and nobody knows how to compile the source code. Now it is my job trying to compile it to be able to develop it further. As I am not a real software developer (studied mechanical enginnering) and just...
The name of the Boost library reflects a number of things. Specifically, libboost_regex-vc90-mt-gd-1_37.lib is the Boost Regex Library for Visual Studio 2008 (containing VC++ 9.0) MultiThreaded version 1.37 (i.e. Boost version) You downloaded VS2022, which explains why you got vc143 (VC++ 14.3). And you downloaded Bo...
73,151,255
73,171,127
clang error: cannot pass object of non-trivial type 'std::vector<long>' through variadic method; call will abort at runtime [-Wnon-pod-varargs]
I build with gcc,compile success,and run success! but when i build my repo with clang, i meet compile error! this is one error,other errors similar ./engine/dispatcher.h:74:57: error: cannot pass object of non-trivial type 'std::vector<long>' through variadic method; call will abort at runtime [-Wnon-pod-varargs] boo...
Why not also pass the function as a template parameter: #include <iostream> #include <string> #include <vector> bool save(int a, std::vector<long> arr) { std::cout << a << '\n'; std::cout << " hello \n"; return true; } template <typename T, typename Callable, typename... Args> bool sum_super_cool(T v, Cal...
73,151,279
73,151,628
How do I initialize an object using a static member function of that object's class?
I have a class with some static functions. The class constructor takes a function as one of its arguments. template <typename T> class MyClass { public: static std::function<T(T, T)> func1 = [](T a, T b) { ... } static std::function<T(T, T)> func2 = [](T a, T b) { .....
MyClass is a template not a class. The class that has a static member you want to pass to the constructor is MyClass<int>. Your code has some typos (missing ;), I had to add inline for in-class initialization of the static members, I introduced an alias, and for brevity I used struct rather than class (the class has on...
73,152,131
73,152,230
ESP home using Arduino library
I am about to write a custom ESPHome component. I don't have much experience with C language and I am facing some troubles using external library. For demonstration, I prepared a simple component class.. class Test: public Component { public: auto t = timer_create_default(); void setup() override { ES...
You can not use auto to declare non-static member variables so you need to replace auto with the type returned by timer_create_default(). If you are not sure what type it returns, you can simply use decltype in the declaration: decltype(timer_create_default()) t = timer_create_default(); If I read the code in the repo...
73,152,583
73,152,866
How to compare two downcasted object types in C++
I have two objects inheriting from Base class. Both are stored in vector: std::vector<Base*> m_vector; How can I check if the first type of object is equal to the second type of object? Scenarios: 1. First object type: A : public Base Second object type: B : public Base Result: Not equal First object type: A : p...
I am simplifying things a lot to get a point across. You have a std::vector<Base*> m_vector; This basically means: You have a vector of pointers to B. The actual objects are polymorphic, meaning you don't care what the actual type is as long as they inherit from B. Now you want to do something that requires you to kno...
73,152,967
73,153,603
Why doesn't copy elision work in my static functional implementation?
I am trying to implement a "static" sized function, that uses preallocated store, unlike std::function that uses dynamic heap allocations. #include <utility> #include <cstddef> #include <type_traits> template <typename T, size_t StackSize = 64> class static_function; // TODO: move and swap // - can move smaller in...
It is not possible to elide the copy/move. The capture is constructed when the lambda expression is evaluated in the caller resulting in a temporary object. That lambda is then passed to the constructor and the constructor explicitly constructs a new object of that type in the storage by copy/move from the passed lambd...
73,153,462
73,153,537
How can I set class member variable correctly from vector in C++
I'm trying to set a class member variable from STL vector in C++. But it doesn't work the way I want it to. The variable doesn't change, The variable is the same like before. Am I programming in the wrong way? Here's the code. #include <iostream> #include <vector> using namespace std; class Test { private: std::stri...
You're copying the elements from the vector each time you iterate through it in your loop. Try changing your code to something like this: for (auto& test : myTests) { test.setName("My new name"); } In this case, the ampersand (&) marks the variables as a reference, which means you can manipulate it directly. The w...
73,153,748
73,153,850
type_info compiler bug in MSVC?
So I've got this code: #include <typeinfo> #include <iostream> void thing(char thing[2], int thing2) { } void thing2(char* thing, int thing2) { } template <typename T, typename U> struct are_types_same { constexpr operator bool() const noexcept { return false; } }; template <typename T> struct are_types_same<...
Does this count as a compiler bug? Yes, this seems to be a msvc bug which has been reported as: type_info yields incorrect result when comparing functions. The two functions do have the same type and the check info == info2 should yield true.
73,154,067
73,154,504
Problem when linking C++ functions from .so
I have the following folder structure in my HOME: - myproject/ + src/ + utilities.cpp + inc/ + Executor.hpp + utilities.hpp + lib/ + utilities.o + libutilities.so - other_project/ + main.cpp The utilities.hpp contains: #pragma once #ifndef UTILITIES_HXX #define...
You declare the function readFromCSV in the namespace myproject and define the function readFromCSV in the global namespace. Thus you get the error undefined reference to myproject::readFromCSV.
73,154,194
73,154,446
How do I know which C++ source files include a specific h header file
I am studying a big C++ project and find a critical header file. I want to find all those .cpp files which include this header file to know the header file's influence scope. However I cannot find a simple way (several clicks or commands) to achieve this via vscode. Is there any trick can get this done? preferably usin...
Try "Edit->Find in Files" option inside VSCode for the header file you are looking for. The search result will give you the desired answer.
73,154,241
73,154,592
Is there a way to test a self-written C++ semaphore?
I read the "Little Book Of Semaphores" by Allen B. Downey and realized that I have to implement a semaphore in C++ first, as they appear as apart of the standard library only in C++20. I used the definition from the book: A semaphore is like an integer, with three differences: When you create the semaphore, you can ...
This code is broken. Your current state machine uses negative numbers to indicate a number of waiters, and non-negative indicates remaining capacity (with 0 being no availability, but no waiters either). Problem is, you only notify waiters when the count becomes zero. So if you had a semaphore with initial value 1 (bas...
73,154,797
73,155,569
What is the meaning of Conan Revision on Conan Center?
On Conan Center, there are 6 revisions of boost/1.79.0, but when I look at the "List of available binary packages" section, I can see a list longer than 6. Each binary package contains a unique set of settings, aka revisions. What is meant by Revision 6? https://conan.io/center/boost?tab=configuration&os=Linux
Revisions are changes to the recipe itself (i.e. changes to the conanfile.py or other parts of the recipe). The revisions will be to fix bugs, add more options or add newer versions of boost. You can see the changes at https://github.com/conan-io/conan-center-index/commits/master/recipes/boost Each revision of the reci...
73,155,027
73,155,067
Why is a bit-wise AND necessary to check if a bit is set?
I am learning a backtrack problem with memoization using bit-mask. When checking if the i'th bit is set in a bit-mask, all the solutions I have come across are doing (mask >> i) & 1. I was wondering, why is the & 1 necessary? Isn't (mask >> i) a 1 when the i'th bit is set, and a 0 when the bit is not set? That already ...
(mask >> i) cannot eliminate the higher bits. For example, when mask = 5 (101 in binary) and i = 1, the value of (mask >> i) is 2. This evaluated as true, but the 2nd lowest bit is 0, so you fail to check the bit correctly. Therefore, & 1 is necessary to eliminate the higher bits and check one specified bit correctly.
73,155,255
73,208,822
QT C++ All datas shown on same column when export csv?
I want to save a set of data in csv file. I have no problem with registration. My problem is in the form of saving. All data are collected in column A. I have 2 graphs in total, graph1 and graph2. Graph1 should be in column A and Graph2 should be in column B. How can I set this up. Here is code for export csv void Main...
you should open the generated file with a text editor and post some lines of it here to your answer. By Opening the File with excel you need to set the seperator it will use to split the the row into columns. Usually it will use ',' but sometimes it will default to ';'. this will seperate them by comma, which is the st...
73,155,412
73,155,464
Optimized string storage for static strings
I know that in C/C++, if you write a string literal, this is actually placed into read-only memory with static (lifetime of the program) storage. So, for example: void foo(const char* string) { std::cout << static_cast<void const*>(string) << std::endl; } int main() { foo("Hello World"); } should print out a...
The easiest way I can think of is to do it with a user-defined literal operator. struct cow_string { /* stuff */ }; cow_string operator "" _cow( const char*, size_t ); Then, when someone does: cow_string betsy = "moo"_cow; the argument to operator""_cow is guaranteed to be a static string. I mean, barring pathologi...
73,155,522
73,155,623
OpenGL doesn't draw a point
OpenGL draws only the background, the yellow point does not appear. I want to draw it with glBegin and glEnd. The coordinates are variables, because I want to move that point later. Most of the code is just GLFW initialization the function that worries me is the draw_player function since there the draw call is contain...
The coordinate (100, 10) is not in the window. You have not specified a projection matrix. Therefore, you must specify the coordinates of the point in the normalized device space (in the range [-1.0, 1.0]). If you want to specify the coordinates in pixel units, you must define a suitable orthographic projection with gl...
73,156,198
73,156,345
Eigen matrix template alias
I had a class definition that compile with VS C++ 20 and not with g++-11 It just consist in an overload of the Eigen Matrix class to define a Vector type. with g++ the compiler says: error: wrong number of template arguments (1, should be at least 3) using BaseVector = Eigen::Matrix< typename T, Eigen::Dynamic, 1, Eige...
Its a combination of MSVC accepting typename in a place where it does not belong and gcc producing a rather confusing error message. 1, should be at least 3 ?!? Probably it gets stuck at typename T, stops there and reports the wrong error. Remove typename (T is not a dependant name): #include "Eigen/Dense" template<ty...
73,157,920
73,158,471
Undefined behavior (according to clang -fsanitize=integer) on libstdc++ std::random due to negative index on Mersenne Twister engine
I'm using clang++ 10 on Ubuntu 20.04 LTS, with -fsanitize-undefined-trap-on-error -fsanitize=address,undefined,nullability,implicit-integer-truncation,implicit-integer-arithmetic-value-change,implicit-conversion,integer My code is generating random bytes with std::random_device rd; std::mt19937 gen(rd()); s...
Although as the other answer indicates it is undefined behavior per standard to instantiate std::uniform_int_distribution with uint8_t template argument, the UBsan warning here is unrelated to that. UBSan is flagging the implementation of the Mersenne twister itself, but the implementation doesn't have any undefined be...
73,158,173
73,174,012
Is there a way to make VS Code stop highlighting C++ errors without disabling the extension?
Please, help me. I need VSCode to stop highlight (underline) errors in C++ (.ino files). I am trying to code a firmware for Arduino board but its highlighting, for example pinMode() as error (not defined) even if both Arduino and Arduino snippets extensions are installed and enabled. I already tried to set problems.de...
Go to Files -> Preferences -> Settings -> Here you can disable the relevent IntelliSense suggestions.
73,158,228
73,158,799
Clang can't find C++ module with `-fprebuilt-module-path`
I have two files, main.cc and S.cc, in the same directory. S.cc contains a module named S_mod. When compiling I get an error about S_mod not being found despite using -fprebuilt-module-path=.. I've tried creating a separate directory for the *.pcm files but that had no effect. main.cc: import S_mod; int main() { r...
For the following, I added some output to your main.cc so it looks like this, to demonstrate it's all working. import S_mod; #include <iostream> int main() { S s = { 1, 2 }; std::cout << s.x << " " << s.y << std::endl; return 0; } You need to make sure all the names of your module artifacts are correct. ...
73,158,620
73,158,703
Specialize class templated on constrained non-type parameter
Let's consider the following code for compile-time evaluation of the factorial function: #include <concepts> template <std::integral auto num> struct factorial { constexpr static auto val{num * factorial<num - 1>::val}; }; // Note: This only specializes the class for (int)0 template <> struct factorial<0> { c...
Instead of explicitly specializing for specifically 0 (i.e. an int with value 0), you can partially specialize for any value which compares equal to 0: template <std::integral auto I> requires (I == 0) struct factorial<I> { static constexpr auto val = 1; }; which if you prefer can also be spelled this way: templat...
73,158,775
73,160,895
Why do I import std.core but not std?
I did the steps described here with MSVC2022 and was able to do: import std.core; but not import std; what is the difference? What is this std.core?
I suggest you read this issue carefully, the problem is similar to yours. And usually, In MSVS std refers to namespace, you could use the contents of std by adding using namespace std;, such as std::cout, etc.
73,158,786
73,158,894
Locking an array of std::mutex using a std::lock_guard array
I have the following array of mutexes: std::mutex mtx[5]; And I would like to lock them all with an RAII style: std::lock_guard<std::mutex> grd[5] { mtx[0], mtx[1], mtx[2], mtx[3], mtx[4] }; While the above code works, it isn't ideal as I can't write it independently of the size of the array (here 5). Is there a way ...
What you want is std::scoped_lock. It takes N mutexes and locks them on creation and unlocks on destruction. That would give you std::scoped_lock sl{mtx[0], mtx[1], mtx[2], mtx[3], mtx[4]}; If that's still too verbose you can wrap that in a factory function like // function that actually creates the lock template<ty...
73,158,957
73,159,034
Is Visual C++ SEH available on other OS?
I learned about Visual C++ Structured Exception Handling (SEH) recently. I am considering implementing it, but my code is supposed to be as cross platform as possible. In the future, I'm thinking of porting ny code to Linux, MAC, Android, IOS and potentially consoles. Is SEH something that can work on all of these plat...
SEH is a Microsoft-specific extension. Clang-cl has partial support for SEH (on Windows platforms), which could presumably be adapted for use on other OSes, but it wouldn’t be straightforward and it wouldn’t offer support for the sorts of things you can catch with SEH but not standard C++ extensions. Don’t use SEH if y...
73,158,968
73,158,991
Why are 'top' and 'pop' seen as undeclared identifiers when I subclass the STL stack class?
I'm feeling rather stupid - must be missing something silly --- I wanted to subclass the generic STL stack class so that I could extend it with a combined top followed by pop operation but my compiler is telling me that both top and pop are undeclared identifiers. template <typename T> class MyStack : public stack<T> {...
First, don't descend from std classes, rather use private member (composition) and delegate functions - that's a common warning. With that said, the error is because a base class with a template argument is not considered in ADL lookup regarding the descendant class. You might have using stack<T>::pop; and similar decl...
73,159,026
73,159,820
How to reduce compilation time with GLM?
I'm using GLM, which is a library that provides some low level math types and functions I use everywhere. But using this Visual Studio addon revealed that GLM comprises about 50% of my compilation time, or around 30 seconds, during each build. The documentation mentions using "precompiled headers" to speed up compilat...
(Submitting an answer so others know what I did, but credit to @john for answering in the comments) Precompiled Headers got my build time down from 2 minutes to 10 seconds(!) In order to utilize "precompiled headers" in Visual Studio from an empty project, the steps I followed were: Add a pch.h and pch.cpp file to the...
73,159,092
73,159,126
How to test if a user inputted string is valid in do/while loop?
So essentially, I am asking the user for a departure time, as well as if it is in the AM or PM. In the code provided, I only test for AM/am (caps or lowercase), but in my actual program I will be testing for both AM/am and PM/pm. Now, when I set my do/while loop up like this: do { cout << "Please Enter a Valid Peri...
Think about this condition } while (departure_amOrPM != "AM" || departure_amOrPM != "am"); This condition is true of every string. Every string is either not equal to "AM" or not equal to "am" (most strings are not equal to both). That's why you couldn't proceed. What you meant to write is this } while (departure_amOr...
73,159,440
73,159,501
C++ dependency injection through constructor
I tried making a simple DI test, where a class car is injected with a container interface. It gives an error 'incomplete type', see the comment in the code. What am I doing wrong? #include <iostream> #include <string> class Car; class IContainer { public: virtual ~IContainer()=default; }; class Container: public...
Your C++ compiler reads your C++ program from beginning to the end, compiling as it goes along. At any point your C++ compiler only knows what it's read so far (we'll ignore some specific exceptions that do not matter here). class Car; Your C++ compiler now knows that your program has a class named Car. It doesn't kno...
73,159,529
73,159,588
What does this code do? (A question about rvalue references)
So I was reading "The C++ Programming Language" and this code got shown. How does it exactly work? I tried asking elsewhere, watching a video on references and another one on basic move semantics but I'm still insanely confused. template<typename T> void swap(T& a, T& b) { T tmp {static_cast<T&&>(a)}; a = static_ca...
This is used in order to employ move semantics, if possible, with these objects. If move semantics are not possible then this automatically devolves to plain, garden-variety, copy-based swapping. The capsule summary is as follows. If you look at plain, garden-variety swapping: T tmp{a}; a=b; b=t; If these objects ar...
73,159,641
73,159,954
How to get a value of the return only?
How to get the value that is returned from a function without running the function again? For example: int difficulty() { char x; while (true) { if (kbhit()) { x = getch(); if (x == '1' || x == '2' || x == '3') { return x; break; } ...
I am assuming you want to create x in menu() and then store it as a variable to pass down the chain of function calls started in menu(). Under this assumption what you ought to do is simple. menu() becomes: void menu(){ if(kbhit()){ char x=getch(); // CHANGED if(x=='s' || x=='S'){ syst...
73,159,681
73,189,274
What will be preferred way to share data between game engine and plugin?
I'm a beginner programmer ( I know scripting and basic C++). I'm using UnrealEngine5/C++ and want to update some variables inside engine using my own programs (Lisp) at runtime. Currently I'm using text file as a buffer. Are there better ways? I don't want each part of engine have a plug for constantly checking this fi...
There are quite a few ways to do what you want, and they are mostly not specific to Lisp. So, I'd like to give you some general advice and add a few Lisp-related comments where appropriate. Basically, there are two extremes among the different approaches you might decide to take: Tight coupling Louse coupling Tight c...
73,159,720
73,159,764
cout macro value doesn't work as expected
#include<iostream> using namespace std; #define C 1<<(8*1) int main(){ if(C==256){ int a=C; cout<<a; } } My expectation is 256 but it print 18. What's wrong with it? Thanks!
I assume your question is about std::cout << C;, not about std::cout << a;. Macros are simple copy-and-paste text replacement. When preprocessor encounters macro name, it replaces it with the definition as text without any analysis. So, what happens is that std::cout << C; is replaced with std::cout << 1<<(8*1); whic...
73,159,830
73,159,878
Why can a C++ function type alias be used to pass a lambda to a function?
Have a look at the code example listed below, I tested it with Compiler explorer (using gcc and clang) and it works and prints out the (expected) output of 200. What I am trying to figure out: why exactly is this valid C++. Or is it not? Here, I'm using the using keyword to define an alias (instead of a typedef) for th...
My question is: where/how does the C++ standard say that this should actually work? This is specified in [expr.prim.lambda.closure]/7, which specifies that a lambda's closure type has a conversion function to a function pointer type matching the lambda's parameter and return types if the lambda is non-generic and doe...
73,159,970
73,160,069
vscode - ofstream not creating a new file, .exe works normally
I cannot create or read files using vscode with fstream. Program run from .exe works normally (creates a file empty.txt). main.cpp: #include <fstream> int main() { std::ofstream file("empty.txt"); } The above program does not create a file when run with vscode. Editor: Visual Studio Code Compiler: MinGW-w64 (MS...
Change cwd in both launch.json and tasks.json to "cwd": "${workspaceFolder}",. See also the official how to.
73,160,006
73,160,055
clang doesn't see base class constructors pulled in via typedef
The following code #include <vector> #include <string> template<typename T> struct V : public std::vector<T> { using Impl = std::vector<T>; using typename Impl::vector; // the constructors }; int main() { std::string empty; V<std::string> meow{42UL, empty}; } Is compiled fine by GCC 8.2 (calls the si...
Since the recent resolution of CWG issue 2070 it is not possible anymore to use a dependent alias to inherit the constructor in a using declaration, except if repeating the name of the alias. You must use the same identifier to name the base class as you are using to refer to the constructor (the last unqualified-id af...
73,160,283
73,746,679
set text align to be the center of sf::text with multi lines in SFML
I have a sf::Text with multiple lines how can I set its content alignment in the center sf::Text? with just single line i can handle it with setOrigin but with multiple lines i dont know how
Depends on what your object is. I would reccomend having the multiline object be a vector of multiple sf::Text objects (each Text object is a new line). You get the right size of the box you want your multiline text to be in and then you use origin on each line to center each text in its position. You can try something...
73,160,419
73,160,437
Is the value of a variable always guaranteed to be 1 word away from the variable created outside of scope if it comes immediately after?
int main() { {int x = 532;} int xc; int x = *(&xc+1); cout << x << endl; // prints 532 } I create an int variable with a value of 532 and then it immediately goes out of scope. I then create another int variable right after so that it has an address of 1 word before x. I then assign that value of whate...
No, the arrangement and padding (and even the existence) of variables on the stack is implementation-dependent, and what you have here is Undefined Behavior. The language specifies that you must not use a pointer to access the memory of any object other than the one it points to. In this case, &xc + 1 points to memory ...
73,160,731
73,160,799
Why do C++ standards introduce more output methods without input counterparts?
C++20 introduces <format>(and sooner C++23 introduces <print>). I like those methods, and I always try to use std::format when it's supported rather than use a series of <<. But I notice that this evolution seems to only appear in the output. Why isn't there something like <scan> for input?
std::format and std::print are already quite a big library addition in itself and I could image that the limited resources for the standard committee to consider the addition of additional features didn't allow them to consider an input equivalent at the same time. It might also be that the committee wanted to collect ...
73,160,854
73,161,163
Casting parameter-less generic lambda to a function pointer
I'm trying to cast a parameter-less generic lambda to a function pointer. This problem generally applies to generic lambdas, which parameters don't depend on the template argument. Example tries to cast the lambda with one parameter (int) which is typewise independent of the template parameter T. #include <iostream> i...
How do I cast lambda to a function pointer that uses operator(int)<char> TL;DR: you don't. First, function pointers point to functions. Templates are not functions yet; a function template only becomes a function when you supply it with template parameters. A function pointer can point to a specific instantiation of ...
73,161,183
73,162,895
Use variables with both cores and tasks ESP32
Im trying to read data from an i2c device, which is recieved by core 0, then that data is stored into some global values, and then those values are readed by the core 1, and then printed out. The problem is whenever the core 0 tries to access those variables, it outputs "guru meditation error core 0 panic'ed (loadproh...
You can create a semaphore and take it when try to access the variable. If you done accessing it, you can give it back. When you take a semaphore, other code blocks will wait for the other to give it back. You can configure the time it should wait for a given semaphore. Here is a (link) explaining in more details. Here...
73,161,277
73,161,860
How to wrapper ofstream?
I'm trying to wrapper the standard ofstream, and hope I can do additional compare and output. Everything goes well, except the std::endl or end used as first output token. But, when I turn on the #if0 ... #endif block in the main function, the g++ report many errors. How can I solve it? Is there a alternative solution....
Just use inheritance directly. #include <iostream> #include <string> #include <fstream> using namespace std; class Logger : public ofstream { template<typename T> friend Logger& operator<<(Logger&, T); public: Logger(const string& file_name) { open(file_name); } private: uint32_t count = 0; }; te...
73,161,558
73,162,237
C++ inject member variable only if template arguments are present
I'm writing a simple generic Graph class, referencing the Boost.Graph implementation. The implementation is like this: template <typename GraphTraits, typename... Properties> class Graph { public: using vertex_type = GraphTraits::vertex_type; using vertex_iterator = GraphTraits::vertex_iterator; using edge_t...
You could store the maps in a tuple. If you don't mind changing from unordered_map to map, it could be done like this: template <typename GraphTraits, typename... Properties> class Graph { public: using vertex_type = GraphTraits::vertex_type; using vertex_iterator = GraphTraits::vertex_iterator; using edge_t...
73,161,739
73,162,016
Rotate a 2-D array by 90 degrees
How can I take the array size input from the user and pass it to the function. I tried #define inside the function, it doesn't work since the array definition needs the array bound at compile time. I tried global variable too, it says to define a integer constant which is not feasible in my case since I want to get th...
One way to make it work is get the input of rows and cols from user and make a one dimensional array dynamically. for example: Let ROWS and COLS be the values you got via cin. Then the array can be declared as int* arr = new int[ROWS * COLS]; Instead of writing arr[i][j] you have to write arr[i * COLS + j] Also you h...
73,162,229
73,162,271
Basic C++ problem - Using variable within the class
I have problem with C++ class. Is there have any way to reuse variable in the same class in the header file? I have try PubSubClient mqttClient(this->secureClient); PubSubClient mqttClient(mqtt.secureClient); but fail. Why? #ifndef __MQTT_H_ #define __MQTT_H_ #include "Arduino.h" #include "WiFi.h" #include "WiFiClien...
The declaration PubSubClient mqttClient(this->secureClient); is treated as a function declaration. An invalid one. If you want to initialize the member variable (using other member variables), you need to do it with a constructor initializer list: class MQTT { public: MQTT() : secureClient(), mqt...
73,162,238
73,162,508
Is there any chance that CLOCK_REALTIME changes time automatically?
I'm using linux api clock_gettime(realtime) to print current time. Check log index ending with 649 and 917. The real clock time was 1646948676.999081502(at index 649) ,but after 10 secs it suddenly jumped more than >24 hours back and was 1646860487.614595043(index 917). Main thing i wanna know is what is VuC offset? Wi...
CLOCK_REALTIME is your classic "wall clock", similar in spirit to what is returned by the older gettimeofday() function call. In particular, it is non-monotonic, which means that it can be expected under some circumstances to 'jump' forward or backwards by an arbitrary amount. Generally "some circumstances" will be li...
73,162,806
74,124,118
ListView with List Items arranged on Half Circle using QML
I'm Trying to make a Circular ListView with List Items arranged on Half Circle. it should look something like this: I'm using Qt open source license and i cannot find a controller similar in QtControls. Please any idea or suggestion ? Thanks in advance
Here is a solution based on the link that folibis shared in the comments above using PathView to layout the items of a model along a PathArc. import QtQuick import QtQuick.Window import QtQuick.Shapes Window { visible: true width: 400 height: 400 Shape { ShapePath { strokeWidth: 2 ...
73,162,859
73,163,323
Qt C++ unable to connect to QTcpServer using Telnet
I have watched VoidRealm's Youtube video, C++ Qt 67 - QTCPServer - a basic TCP server application and followed his instructions, however, I can't connect to the QTcpServer I created using Telnet. My Code: //myserver.h #ifndef MYSERVER_H #define MYSERVER_H #include <QObject> #include <QDebug> #include <QTcpServer> #in...
You error message indicates the issue: qt.core.qobject.connect: QObject::connect: No such slot MyServer::newConnection() in ..\First_Server\myserver.cpp:8 Server started! You have created the connection between the signal and slot here. connect(server,SIGNAL(newConnection()),this,SLOT(newConnection())); First of all...
73,163,384
73,163,646
Syntax for check if all variadic parameters are trivially copyable
Yesterday I answered this question. One user commented that it will work only for trivally copyable data. That is clear, but not enforced. I wanted to add a static_assert, but I use the wrong syntax. Here I need help. To explain a little bit more. The functions can take containers that have a size() and data() member f...
The correct syntax would be static_assert(std::conjunction_v< std::is_trivially_copyable< std::remove_pointer_t< decltype(std::declval<Args&>().data())>>...>, "Not trivially copyable"); However, there is no need to use decltype(std::declval<Args&>().data()) to get the return type of the data(), since yo...
73,163,428
73,186,571
Alpha-beta pruning with a silly move
After learning about alpha-beta pruning algorithm for a while, I decided to write a simple chess program. However, when running the program, the computer decides to make a silly move. I don't know where the functions are written wrong. What do I have to fix for the program to work properly. This is my static evaluation...
What this really means is that your engine thought it found a refutation. For example, perhaps it analyzed QxP at depth 1. It would think that it had just won a pawn, which is great! But, one move later it realizes that it would lose the queen. This is a problem even at higher depths - an engine might thing QxP leads t...
73,163,473
73,168,291
Best alternative to passing std::optional<std::shared_ptr<Data>> as parameter?
I have some existing code that in many places passes boost::optional<std::shared_ptr<Data>> as a parameter to a function. The function itself does not need "ownership" of the function so copying the shared pointer is both inefficient and misleading. If it wasn't for the 'optional' I would change this to take a Data co...
First, there is nothing wrong with passing a raw pointer provided: the function does not store the pointer for later use (takes/shares ownership) passing nullptr to the function is meaningful But lets look deeper into your type: boost::optional<std::shared_ptr<Data>> So this can be a shared pointer or none. And a sh...
73,164,072
73,189,510
Call Win32 DeviceWatcher API from Dynamic Link Library
I create a DLL project in VS 2022. How is it possible to add a call to the Win32 DeviceWatcher API? I need to add this to use it: using namespace Windows::Devices::Enumeration; using namespace Windows::Foundation But where must I add references to the Win32 API?
The DeviceWatcher Class is Windows Runtime API. I suggest you should create a Windows Runtime component DLL or class library universal windows. For more details I suggest you could refer to the Doc: DLLs
73,164,605
73,165,455
Qt C++ QTcpServer not connecting to Threaded Socket
I have worked through C++ Qt 68 - QTcpServer using multiple threads and followed his steps, but I can't seem to get the program to work correctly. I am using Qt 6.3.0 and the only difference between VoidRealm's code and mine is that I am using the new Signals and Slots system. My Code: //myserver.h #ifndef MYSERVER_H ...
I found my problem. The int in the incomingConnection(int socketDescriptor) should have been a qintptr, making it incomingConnection(qintptr socketDescriptor) The program works now.
73,164,881
73,168,344
Programming principles and practice using C++ error: constexpr
In Stroustrup's "Programming principles and practice" book, there's an example of constexpr like this: void user(Point p1) { Point p2 {10,10}; Point p3 = scale(p1); // OK: p3 == {100,8}; run-time evaluation is fine constexpr Point p4 = scale(p2); // p4 == {100,8} constexpr Point p5 = scale(p1); // error...
You know who is really good at telling you if something is allowed as a constexpr? Your compiler. https://godbolt.org/z/4Kdocx83v And you are right, it's broken.
73,165,096
73,166,579
How to initialize constexpr static class members per class instantiation basis?
Basically, I want to allow the clients of the class Foo to define its static constexpr member variables using arbitrary values based on the template type argument they pass to it when instantiating Foo. Here is an MRE: #include <iostream> #include <concepts> template < std::unsigned_integral size_type, cla...
ITNOA My assumption is Foo class has many static constexpr variables and writer of Foo class does not like to write long template signature So I hope to below solution is simple and scalable enough for Foo class writer template <std::unsigned_integral size_type, size_type... args> class Foo { public: static constex...
73,165,179
73,165,396
What does system_clock::now() value after seconds represent in C++ 20?
I'm exploring the timestamp in C++ 20 returned from system_clock::now() and when I print out the returned std::chrono::time_point it prints the date and time in the format YYYY-MM-DD HH:MM:SS.xxxxxxx. Any idea what the xxxxxxx value is? I assumed microseconds initially but I realised microseconds are to six decimal pl...
It's the fractional part of a second. The output you're getting comes from operator<<(zoned_time). This outputs the time in the format "{:L%F %T %Z}" (see cppreference.com). The %T part of the format is equivalent to "%H:%M:%S" (reference) and the %S specifies the seconds as a decimal floating-point number with a preci...
73,165,184
73,167,705
How to rotate scene OpenGL with Qt
I've got couple of methods to get reaction on some Qt events. In one of those methods i'm drawing point in OpenGl widget. And in another I want to rotate them on some angle. The scene is plane scene. Here are those methods: #include "GLMap.h" GLMap::GLMap{} void GLMap::initializeGL(){ glClearColor(r,g,b,alpha); }...
The glRotatef() function applies a rotation to the matrix currently at the top of the matrix stack. When you draw, it does so using the matrix currently at the top. And when you glPopMatrix(), you revert the matrix stack to the one below. So the pattern while issuing commands in a painting function will typically look ...
73,165,250
73,165,387
no default constructor exists for class Move
I developed two modules with separate implementation and interfaces. These are the ones: This is file Move.h: #pragma once #include "utils.h" class Move { private: int x; int y; public: Move(int x_inp, int y_inp); char getX(); int getY(); }; And this is Move.cpp: #include "Move.h" Move::Move(int...
you should try literally adding a default constructor to your "Move" class. public: Move() {} //default constructor Move(int x_inp, int y_inp); char getX(); int getY(); }; ´´´´
73,165,322
73,165,920
RegEnumValueA returns 87 ("Invalid Parameter")
I am currently implementing functions and classes from Borland C++ Builder 5 in Visual Studio 2022. One of the classes is used to handle Windows registry IO, and one of its methods is supposed to return a list of values which the current key contains. I am using Windows' RegEnumValueA function which, after passing corr...
Your lpcbData parameter, which you have set to NULL is invalid. This should be the address of a DWORD that specifies the size (in bytes) of the buffer pointed to by the lpData parameter (i.e. the size of the cData array). From the documentation: [in, out, optional] lpcbData A pointer to a variable that specifies the s...
73,165,810
73,168,951
Vulkan vertex drawing order
I am currently getting into vulkan and am now at the point where I want to draw a qube with perspective projection. But the drawing order of the faces doesnt seem to woek right. This is the depth stencil info of my pipeline const auto depth_stencil_state_create_info = VkPipelineDepthStencilStateCreateInfo{ .sTyp...
Your problem has nothing to do with vertex order since you're not culling backfaces: .cullMode = VK_CULL_MODE_NONE, If you're trying to avoid setting up a depth test by just drawing front faces, you need to change this to .cullMode = VK_CULL_MODE_BACK_BIT, and then you'll either be able to see only the front face...
73,166,228
73,166,482
How to solve this Coverity issue called OVERRUN
I write a C++ code as below and use Coverity to check it. Coverity report OVERRUN error of it, as attached picture shown. But I don't understand what does it mean and how to fix it. Any hint? wchar_t* GetMainAppPath() { const wchar_t* mainAppName = L"AIScreenshot.exe"; const wchar_t* agentName = L"AIScreenshotA...
But I don't understand what does it mean It's telling you that the call to wcsnlen_s is reading off the end of your string. I'm not going to transcribe the error from your picture of text, but you can read it for yourself. Your string is actually sixteen wchars (followed by a null wide character). You told wcsnlen_s ...
73,166,348
73,166,874
Is This The True Way To Implement Explicit Template Specialization Of Template Function In C++20
Hi I wrote that code for my c++ course assignment, it works but I don't know if it is best way to implement explicit specialization. I am waiting for your helps, thank you in advance. #include <iostream> template <typename T> T Max(const T* pArr, size_t arrSize) { T result{ pArr[0] }; for (size_t i = 0; i < arr...
At very first: You are re-inventing the wheel, there's already std::max_element doing nearly (returning an iterator to, not the element itself) the same! Then to specialise a template you first need a base template and then the specialisation, for instance: // the base template: template <typename T> void demo (T const...
73,166,509
73,167,227
Integer sequence as a non-type template parameter
I'd like to pass several arbitrary length integer sequences as non-type parameters to a template class, so the instantiation would look something like this: Foo<Bar, {1,2,3,4}, {5,6,7}> foo; Is there a simple way to do this, possibly with C++11? *** EDIT Ok, here's a more specific situation: #include <vector> using st...
Here is an example on how to use arbitrary length integer sequences as template parameter in c++11. It requires a bit of template magic as we can see :P #include <array> #include <utility> #include <iostream> // Crude c++14 integer_sequence template<int...> struct ints { }; // Turn an integer sequence into a std::arr...
73,166,884
73,168,749
Partially specialized template static constexpr in template class
(A toy, minimal not-working example) The next code won't compile with cpp20/17: template<typename TSomeTemplate> struct A { static constexpr size_t B = 1; template<typename T, typename... Ts> static constexpr size_t C = 4; template<typename T> static constexpr size_t C<T> = B; }; int main() { ...
GCC and MSVC are wrong in rejecting the code as the program is well-formed. B is a constant expression and can be used as an initializer when initializing C during its partial specialization. This is a msvc bug reported here as: MSVC rejects valid code when using constexpr static data member as initializer. Moreover, ...
73,167,362
73,168,118
C++: In the switch I need to press twice to get a single input
I try to make a menu with ncurses library, I made a switch with a getch() that takes the input. When I'm moving in the menu I need to press twice the keys to get the right input. For example if I want to go to the "exit" line from "options" line I need to press twice the KEY_DOWN, if I press only one time the cursor do...
You call (w)getch twice in the loop: while(getch()!='x'){ int push = wgetch(win); // ... } Try this to get the character and check for the loop condition at the same time: int push; while ((push = wgetch(win)) != 'x'){ // ... }
73,167,680
73,167,821
Why are get/set functions used in C++ so often?
What is the point of doing this: class thing { public: void setMarbles(int _marbles){marbles = _marbles;} void getMarbles(){return marbles;} private: int marbles; }; when you can just do this: class thing { public: int marbles; }; I feel like this is a super common question, but I cant...
Encapsulation, maintainability, debugability Consider: void thing::setMarbles(int _marbles) { // runtime error if incorrectly used assert(_marbles > 0); marbles = _marbles; } void thing::setMarbles(int _marbles) { // log to some file to debug some specific scenario someLogUtility("Marbles write", _...
73,167,852
73,569,844
Instantiation of QAxObject from dumpcpp segfault with minGw C++ -o2 or -o3 flag
Qt version: 5.12.10 I wanted to interface with an application using the COM layer, this application was delivered with a .tlb file so I used Qt's dumpcpp to generate header and source file. To use the generated class, I first get an IUnknown from windows ROT and then instantiate the classes I need from a class I used a...
The mistake was on me. After getting the IUnknown * from the COM, we have to get a IDispatch * from it and then instantiate directly the classes: //Initialize COM, load the ROT, get the monikers and for each monikers //Check if the monikers name is the one we want if (!wcsncmp(monikerDisplayName, appComIdentifier,...
73,168,762
73,168,834
How can I call a function from a third party lib that is not marked constexpr from a constexpr function?
I want to do exactly what the title says. I have some third party code with an API. The information needed to evaluate the function should all be available at compile time to evaluate the function. However it does not appear the third party labeled it constexpr sadly. Furthermore, I don't have the source code for th...
First of all a function can only be called in a constant expression if its definition is available in the translation unit with the constant expression. That means that if the function definitions are not inline in the header, then it is impossible to call the function in a constant expression at all. If the function d...
73,168,909
73,169,028
Create CommandQueue and Command Allocator using IID_PPV_ARGS
I am learning how to create CommandQueue, Command Allocator, and CommandList in DirectX 12. However, a question arose in the process of creating each with the Create function. The following is the code from the major. ComPtr<ID3D12CommandQueue> mCommandQueue; ComPtr<ID3D12CommandAllocator> mDirectCmdListAlloc; ComPtr<I...
IID_PPV_ARGS() expects the address of an interface pointer variable. Both ComPtr::operator& and ComPtr::GetAddressOf() return such an address - the address of the internal ComPtr::ptr_ data member. The only difference between them is that ComPtr::operator& calls Release() on the current interface if it is not null, w...
73,168,961
73,174,503
macOS Xcode, how to link/compile libvips as a static lib
I have a small app called Messer. It's a native macOS app using Swift and SwiftUI. The way the app works is by using the native macOS apis to manipulate the image (NSImage) and finally saves a png file to disk. Further conversion to other formats (with optimization) is left to embedded binaries of popular open source l...
A fully static library is difficult, and probably not necessary. libvips itself is easy to build static, but it has a lot of dependencies (it can be more than 40 other projects), and you'll need to make static versions of all those libraries too. It's a lot of very annoying work. Instead, I would use homebrew to build ...
73,169,352
73,169,648
Overload resolution of int vs std::vector<int> with an initializer list of a single int
Why does c++ choose a primitive type overload match over a "better" matching initializer list? #include <vector> void foo([[maybe_unused]] int i) {} void foo([[maybe_unused]] const std::vector<int>& v) {} int main() { foo(0); foo({1,2,3}); foo({0}); // calls foo(int) and issues a warning, ...
{0} doesn't have a type, so we need to try and convert it to the parameter types of the overload set. When considering void foo([[maybe_unused]] const std::vector<int>& v) {} We need to consult [over.ics.list]/7.2 which states Otherwise, the implicit conversion sequence is a user-defined conversion sequence whose se...
73,169,457
73,169,604
Is there an alternative to overloading or template specialization? I am attempting to call a specific function based on a template parameter
I have generated a simpler example of what I am trying to accomplish. I would like to be able to call a function, which returns a class containing two template parameters, based on one of the two templated parameters (Variance). My hierarchy can be simplified to this. template<typename T> class AbstractType {}; templ...
Without following all of it really in detail, don't you just want e.g. template<typename T, Variance Type> auto CreateBaseInstance(T t, int value) { // Instead of `auto` maybe `std::unique_ptr<BaseType<T, Type>>` auto OutObj = std::make_unique<FinalType<T, Type>>(t); if constexpr(Type == Variance::Weig...
73,169,671
73,171,920
Is it possible to truncate C preprocessor identifiers?
In C, with #define, we can use the token pasting operator ## to concatenate an identifier with some other text. Is it possible to do the reverse as seen in the example below? #define millimeter //truncate to milli //convert to millisecond I am specifically trying to use this for function name generation, so a call to ...
The units of input to the C preprocessor are (preprocessing) tokens such as identifiers, operators, and string literals. Tokens are atomic as far as the preprocessor is concerned -- it has no mechanism for dividing them into pieces or for operating in any other way on partial tokens. Under some circumstances, you can ...
73,169,877
73,169,971
How to insert a new node at any given position in linked list?
Kindly check my code below. I am not getting the actual output when I run this program. What I want to do is to insert a new node at the position entered by the user. I have tested this code by entering 5 values for 5 nodes i.e 1,2,3,4,5 and then I entered position 2 to insert a value 8, but when I display it, it gives...
Your problem is here: cout<<"Enter data you want to insert:"; newnode=new Node(); cin>>newnode->data; newnode=temp->next; temp->next=newnode; newnode=temp->next makes newnode equal to 0, then temp->next=newnode makes temp->next equal to zero. Perhaps you meant to write newnode->next = temp->next instead?
73,170,075
73,170,136
using std::launch::deferred does not defer the function in std::async
https://godbolt.org/z/MEsandWGe Here's the code I'm testing, same as the above godbolt link: #include <future> #include <string> #include <iostream> #include <chrono> #include <thread> using namespace std::chrono_literals; int main() { int v = 0; auto a1 = std::async( std::launch::async | std::launch...
std::launch::async | std::launch::deferred means that std::async can choose which of the two policies is selected. It is implementation defined which one is used but it looks like your standard library chooses async rather than deferred.
73,170,352
73,170,393
Does the pointer in a class get deleted when the class gets deleted/destroyed?
I'm new to C++, and I want to know, does a pointer gets automatically deleted when the class gets deleted / destroyed? Here is an example: class A { public: Object* b; }; Will b get `deleted when the class is deleted?
The object that the pointer points to will not be deleted. That is why it is a bad idea to use a raw pointer to refer to an object created with dynamic storage duration (i.e. via new) like this if the class object is intended to be responsible for destroying that object. Instead use std::unique_ptr: #include<memory> /...
73,170,389
73,170,483
A question about dynamic memory allocation
Consider the portion of code below (please do not care about deleting the firstArray and secondArray): int *firstArray = new int[10]; int *secondArray = new int[20]; firstArray = secondArray; I have three questions here: Is the expression firstArray = secondArray; safe even though they have two different sizes? ps: ...
Okay, let's talk about what you're doing here. Is it safe? Yes. But it's a mistake because you have orphaned the data that secondArray used to point to. They now point to the same space in memory. Imagine that firstArray holds the memory address 0x1000 and secondArray holds address 0x2000. After this assignment, they...
73,170,931
73,174,028
GLM perspective matrix ruins rendering
I created a projection matrix for Vulkan renderer using GLM, but after multiplying it with vertex itself in vertex shader, nothing renders. I have defined GLM_FORCE_RADIANS and GLM_FORCE_DEPTH_ZERO_TO_ONE (to be fine, I tried without both of these, or without one of these). Also I tried to pass fovy param as degrees or...
I fixed it. The "problem" was that projection and perspective division maps the [-near, -far] range to [-1, 1], which lead to flipping Z coordinate. Meanwhile I had Z coordinate as 10.0f, it was actually behing the camera. Solution was setting up Z coordinate value as -10.0f, which will be flipped to 10.0f after projec...
73,171,392
73,171,626
flex/bison gives me a syntax error after printing the result and if another input is written to work
After running the compiler and type the entry on, works fine. Then if I type another entry (and if it also works ok) it gave me Syntax Error. I must mention I am a new in ​​the world of flex/bison. To be honest I do not know what's could be wrong, some one please help? Here is my lex code: %{ #include <stdio.h> #i...
Your parser is written to accept a single input INICIO rule/clause, after which it will expect an EOF (and will exit after it sees it). Since instead you have a second INICIO, you get a syntax error message. To fix this, you want your grammar to accept one or more things. Add a rule like this: input: INICIO | input I...
73,172,098
73,172,337
How to conditionally get template type of multiple base class with multiple inheritance
This is NOT a duplicate of link Consider the following code: #include <type_traits> template <typename... Bases> struct Overloads : public Bases... {}; template <typename T> struct A { using AType = T; }; template <typename T> struct B { using BType = T; }; template <typename T> struct C { using CType = T; };...
My precise use case is: 1. Determine if Derived is derived from A<T> for some T. 2. If so, figure out that T. With C++20 concepts, this isn't too difficult. You need a function that takes A<T> as a parameter. There need not be a function definition; we're just using template argument deduction. It will never be calle...
73,172,193
73,180,292
Can you static_cast "this" to a derived class in a base class constructor then use the result later?
We ran into this scenario in our codebase at my work, and we had a big debate over whether this is valid C++ or not. Here is the simplest code example I could come up with: template <class T> class A { public: A() { subclass = static_cast<T*>(this); } virtual void Foo() = 0; protected: T* subclass; }; clas...
In my opinion this is well-defined according to the current wording of the standard: the C object exists at the time of the static_cast, although it is under construction and its lifetime has not yet begun. This would seem to make the static_cast well-defined according to [expr.static.cast]/11, which reads in part: .....
73,172,507
73,172,783
How to use cv::Mat::at<double>(i,j,k) (to access a multi channel matrix)?
#include <iostream> #include <opencv2/highgui/highgui.hpp> int main() { double m[1][4][3] = { {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}, {10.0, 11.0, 12.0}}}; cv::Mat M(1, 4, CV_64FC3, m); for (int i = 0; i < 1; ++i) for (int j = 0; j < 4; ++j) for (int k ...
opencv treats the number of channels in each element of a cv::Mat as separate from the number of dimensions. In your case cv::Mat M(1, 4, CV_64FC3, m) is a 2 dimensional array where each element has 3 channels. cv::Mat::at returns an element in the cv::Mat. In order to use it in your case you need to: Pass 2 indices f...
73,172,543
73,172,649
Type traits `is_noexcept`, `add_noexcept`, and `remove_noexcept`?
Motivation: In the implementation of P0288 std::move_only_function, I'd like to write a non-allocating special case for conversion from move_only_function<int() noexcept> to move_only_function<int()>: move_only_function<int() noexcept> f = []() noexcept { return 42; }; move_only_function<int()> g = std::move(f); // sh...
Aside from qualification conversions, the only possible implicit conversions between pointer-to-function types are the ones that remove noexcept and similarly for pointers-to-member-functions (except for base-to-derived conversion), so I think the following should work struct C {}; template<class A, class B> struct is...
73,172,791
73,178,560
How to dynamically create a lot of data for INSTANTIATE_TEST_CASE_P parameterized unit tests
I need help with INSTANTIATE_TEST_CASE_P(prefix, test, testing::ValuesIn(container)). Running VS 2022 and latest google test ("Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn" version="1.8.1.5") The problem is, INSTANTIATE_TEST_CASE_P appears to only use the data in the container at compile time. I've tried ...
The generator expressions (including parameters to the generator) are evaluated in InitGoogleTest(). Therefore, it is necessary to read the data and put it to g_data_in_file before InitGoogleTest() is called in main function. And Environment::SetUp() is called only from RUN_ALL_TESTS(). So, it's too late to read the da...
73,172,806
73,181,022
Function Pointer using "typedef" keyword with Function Address stored as Variable? (C++ 14, VS 2019)
Problem Summary I'm attempting to create a callable function pointer inside of a function using templates for its return value and its arguments using C++ 14. I want the callable function pointer to return the templated type, and accept templated arguments. However, I also want the callable function pointer to point to...
After a lot of research, and posting this question on other programming forums, I reached an answer, and several other conclusions that I believe are worth sharing in regards to my original problem (very informative answers provided to me on this forum: https://cplusplus.com/forum/general/284539/). Immediate Solution T...
73,173,100
73,173,115
How can i access Array declared in one switch case and use it in another switch case C++
Im trying to create a menu driven program to perform operations on an array , I'm trying to figure out how to access variables from one switch statement to another. [I am a noob] This is the program #include <iostream> using namespace std; int main() { int c,a=0; do { cout << "-----MENU------" << endl; ...
Your first problem is that int array[s]; is not legal C++. It's a variable length array which is legal in C but not in C++. The C++ solution is to use a vector. #include <vector> std::vector<int> array; switch (c) { case 1: { cout << "Enter the size of array :"; int s; cin >> s; array.resize(s); .....
73,173,317
73,244,778
"Missing argument in parameter list" error while creating .dll file from the .o file
Am just starting learn jni and decided to do a hello world. i created a helloworld java file whose code is public class HelloWorld { public native void displayHelloWorld(); static{ System.loadLibrary("hello"); } public static void main(String[] args){ new HelloWorld().displayHelloWorld(...
The problem is that in PowerShell comma has a special meaning of comma operator unlike, e.g., in Bash, where in such context there is no any special meaning to it. When your command is parsed, -Wl is considered a parameter name and , is interpreted to form an array (parameter list) as its argument. As seen in linked do...
73,173,328
73,210,001
In C++ can I create a Binary Search Tree using objects/structs as the node?
In other related c++ work I managed to create a sort of binary search tree template. The implication here is that using this template, I can create a BST for all sorts of data types... Int, string, so on. I've been asked to use a BST as a data structure. Let's imagine it's weather data. A measuring device records the t...
As trincot pointed out, there are quite a number of ways to use a binary search tree with structures. I kept in mind that I should NOT use a separate structure to store my records, as they rightly pointed out that using my BST template it should generally be declared as BST< Record > rather than BST< int >. In my earli...
73,173,393
73,173,464
C++ char array compare ' ' and '\0' and counter doesn't work
I'm new to C++. I have a simple practice function I try to count how many words in a full name, first I pass a char array fullName to nameCount function with a counter then it will compare each char in the array with ' 'and '\0' if it meet any of these 2 chars, counter will +1. But I don't know why the counter give bac...
You have the common newbie confusion between parameters and return values. When you want a function to calculate something you return that value from the function, You don't pass the variable as a parameter. Here's how your code should look int nameCount(char fullName[]) { int count = 0; for (int i = 0; i < LEN...
73,173,608
73,173,675
Red-black tree in C++ STL
In current C++ STL, where are red-black tree used? (I assume map and set do?) Is the red-black tree used 2-3 tree (ie only left or right child can be red) or 2-3-4 tree (ie both left and right child can be red)? is there a red-black tree lib in STL?
std::map, std::multimap, std::set and std::multiset are often implemented in terms of red-black trees but doing so is not mandated by the standard. Since using a red-black tree is not required there is also no requirement for any particular flavor of RB tree. I believe (though am not certain) that SGI's STL (upon which...
73,173,609
73,173,712
C++ - Should you delete allocated memory in the copy assignment operator of a class that uses raw pointers?
I am still somewhat new at c++, and I am a little confused about this. Say we have struct struct_x that uses raw pointers as attributes. Should the raw pointers then be deleted in the copy assignment operator, when they are already allocated? Or should you just assign the new pointee to the pointer? (I am aware that it...
If you are implementing a string-like class as an exercise, then m_len and m_alloc_len should not be pointers at all. Only m_arr should be a pointer. If you are not doing an exercise, you should be using std::string or perhaps std::vector<char>. Having said that... It is perfectly fine and necessary to delete owning ra...