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
68,664,151
68,664,270
Unable to compile C++ program on a macosx: error: unknown type name 'constexpr'
I am trying to compile the below program. However it's giving me the error: unknown type name 'constexpr' error. What should I do? Code: //this is model.cpp. battery.cpp and load.cpp are two secondary files #include "load.h" #include "battery.h" //compile time constants - Settings constexpr int intervals = 96; constex...
That json config is not used if you are calling the compiler directly from the command line. In that case you have to specify every option yourself: g++ -std=gnu++17 -Wall -Werror model.cpp battery.cpp load.cpp I just added -Wall -Werror for good measure, you should never compile your code without them. Without the -s...
68,664,851
68,665,054
unique_ptr that contains unique_ptr
Disclaimer: I at first wrote a version of the question that I thought would be clear but that wasn't at all. I've reworked it here as a MRE. I have the following bit of code: #include <map> #include <memory> #include <string> using std::make_unique; using std::string; using std::unique_ptr; template <typename T> cla...
This, of course, leads to errors about implicitly-deleted copy constructors. I think I understand why this is so You generally get such errors when you try to copy objects of a type that has non-copyable members. Solution: Don't try to copy non-copyable objects. Disclaimer: Obviously a unique_ptr can't manage somet...
68,664,934
68,664,950
convert int to hex string <sstream>
I have an int number as 0x30, when I convert to string it will return "48". But what I want is "30" int var = 0x30; std::string text = std::to_string(var);
You can use std::stringstream #include <string> #include <sstream> int main() { int var = 0x30; std::stringstream ss; ss << std::hex << var; std::string text = ss.str(); }
68,665,101
68,669,161
Why do we need pointers to arrays when we have regular arrays?
What's the need of pointers array when we already have simple arrays for array data? We can already use arrays to store data; why would we ever want to use pointers to arrays? int array[100]; int *ptr = new int[100]
There are several reasons to use dynamically-allocated arrays rather than arrays that are local variables. Space limitations. If you declare an array as a local variable, it’s typically stored in a region of memory called the stack. The stack has limited size and space, usually on the order of tens of megabytes, and i...
68,665,210
68,665,282
what is the point of `++a=20;`
I got confused when accidentally tried this code ++a=20;, which is not allowed in C. But it works and a turns out to be 20. Is it working with pointers? #include<iostream> using namespace std; int main() { int a=10; ++a=20; cout<<a<<endl; return 0; } And that is from https://godbolt.org/ mov D...
Short answer: Pointless Let's read the Assembly code. mov DWORD PTR [rbp-4], 10 4 byte (32 bit) is allocated for the integer variable a. Therefore it is positioned in [rbp-4]. This code simply assign its value to 10. Now a = 10. add DWORD PTR [rbp-4], 1 It is equivalent to adding 1 to a This can be both a++ or ++a...
68,665,394
68,674,304
How to use retranslateUi() recursively on all ui in QMainWindow?
In my Qt5 application I am trying to switch the language at run-time. So far here my simple function: QTranslator _translator; void MainWindow::switchLanguage(QString lang) { if (!_translator.isEmpty()) qApp->removeTranslator(&_translator); if (lang == "it") { _translator.load("Language_it_IT.qm", ...
Reimplement the changeEvent of your form classes like this: void Form::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) ui->retranslateUi(this); QWidget::changeEvent(e); }
68,665,410
68,665,487
Why do we need auto after function concept arguments in C++20?
I have the following compile error which cause I am failing to understand. template<typename T> concept floating_point = std::is_floating_point_v<T>; auto add(const floating_point f1, const floating_point f2) { return f1+f2; } In the above vertion the compiler is complaining: ssource>:6:16: error: expected 'auto'...
So the question really is why do we need auto here? Because floating_point is not a type, and add is not a plain function. However, something like void add(floating_point, floating_point); totally looks like a regular function declaration, and nothing tells us here that this is actually a template written with terse ...
68,665,603
68,665,642
Does Endian-ness affect the union members when they are integers?
union Chunk { struct { uint32_t index, total; } m_; uint64_t m_PlaceHolder; } chunk; chunk.m_.index = 1; chunk.m_.total = 2; SendOverTCPNetwork(chunk.m_PlaceHolder); // different platform OS will receive this A union member is set for 2 integers and then a (combined) long integer is sent over a TCP network as show...
Will the endian-ness of the source machine & destination machine affect the values of the chunk variable? Yes. Endianness affects all integers, even when they are members of classes. (Except of course signed char and unsigned char). SendOverTCPNetwork(m_PlaceHolder); You cannot access non-static members without a...
68,665,629
68,665,775
How to pass a function template as a template argument?
#include <iostream> template<typename... Args> void print(Args const&... args) { (std::cout << ... << args); } int main() { std::cout << 1 << 2 << 3 << std::endl; // ok print(1, 2, 3); // ok print(1, 2, 3, std::endl); // error! How to make it work? } See online demo...
You will have the same issue with other io manipulators that typically are functions that take the stream as parameter, when they are templates. Though you can wrap them in a non-template callable: #include <iostream> template<typename... Args> void print(Args const&... args) { (std::cout << ... << args); } i...
68,666,013
68,666,531
Alias to variadic template with no arguments
I found some similar topics, but none seem to give straight answer about my particular problem. I have a class (let's call it Foo) within some library that we are using across few modules. Now I need to transform this class to be a variadic template(so now I have: template<class... T> Foo() {}), as some new uses need e...
If you rename the templatized definition of Foo to some other name FooExtended, then you can typedef the empty template to Foo //old class Foo; //new template<class... Args> class FooExtended; using Foo = FooExtended<>;
68,666,087
68,666,830
Declaring an array of functions inside a class
I have a batch of functions in a class: class Edges // Edges of a Rubik's cube { // Stuff protected: // Edges movements void e_U(); void e_D(); void e_F(); void e_B(); void e_R(); void e_L(); // More stuff }; A new class inherits this fu...
The answer to your question is that e_U, e_D, etc are all member functions, and not just plain functions, so the type of pointers to them are pointer-to-member functions. The declaration and usage for your array would look like: class Cube : public Edges { // ... static void (Cube::* const USlice[24])(); }; vo...
68,666,414
68,666,434
Can't exit the while loop after guessing the right number
I'm trying to make a simple number guessing program with while loop but even after finding the right number (I changed the num with 5 and it didn't work) it does not exit the while loop. Can you tell me where the problem is? int guess; int num; cout << "Enter the number (0-10): "; cin >> guess; while(guess != num){ ...
int num = rand() % 10; is a declaration of a new variable num within the loop body and that shadows the num defined at the top of the program: while (guess != num) is using the latter. The solution is to write num = rand() % 10; instead. You will need to initialise num to a value before attempting to read it, else tech...
68,666,801
68,667,906
C structure and C function with the same name in C++
When I was mixing C and C++ code I ran into a problem when Linux C struct statx has same name as statx() Linux system call. For the case that statx() system call is not present in the installed glibc version, I implement my own version of statx(). I tried to implement an alternate statx() function in the anonymous name...
Name hiding [basic.scope.hiding] 2. If a class name ([class.name]) or enumeration name ([dcl.enum]) and a variable, data member, function, or enumerator are declared in the same declarative region (in any order) with the same name (excluding declarations made visible via using-directives ([basic.lookup.unqual])), the ...
68,667,131
68,668,033
RValue-reference overload of std::forward potentially causing dangling reference?
This question is a follow-up question to: Second overload of std::foward (example on cppreference.com). StoryTeller's answer made me think about the value categories involved in the statement foo(forward<decltype(forward<T>(arg).get())>(forward<T>(arg).get()));. Doesn't the second overload template< class T > constexpr...
Doesn't the second overload ... potentially cause dangling references? If the argument is a non-dangling reference, then so will the returned reference be non-dangling. If the argument is a temporary, then the reference will become danging after the full-expression. I wouldn't say it has been "caused" by std::forward...
68,667,175
68,667,314
cin.ignore not working: further inputs get skipped even with clear()
I am trying to make a checked bool input, but for some reason it keeps getting into an infinite loop, or (if I move std::cin.ignore() to be first thing executed after std::cin.clear()) asks for phantom input. I tried simple ignore() and ignore(std::numeric_limits<std::streamsize>::max(),'\n') and it still gets into an ...
Your problem here is your order of operations. With std::cin.clear(); std::cout << "Enter " << testString << " value (true/false)\n"; std::cin >> std::boolalpha >> value; std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); You call clear, get input, and then ignore the leftovers. The issue with that i...
68,667,348
68,667,622
constexpr variable must be initialized by a const expression
With the code below, I get Constexpr variable 'max_digits' must be initialized by a constant expression with Apple clang version 12.0.5 (clang-1205.0.22.11) running C++14. However, if I #define WORKING_CODE it works fine with base_two_digits being a global function. If I move the contents of base_two_digits into log_ba...
Let me simplify the code first (please ignore the nonsensical behaviour) to the following example illustrating the same issue: template<typename T> constexpr T log_base_10(T value) { constexpr auto index = value? 1:0; return 0; } int main() { constexpr auto foo = log_base_10(42); return 0; } The probl...
68,668,285
68,668,378
Is it legal to use function with no definition c++?
I've seen some snippet of code from this page https://en.cppreference.com/w/cpp/types/result_of and have noticed this specific function template signature type: template<class F, class... Args> static auto call(F&& f, Args&&... args) -> decltype(std::forward<F>(f)(std::forward<Args>(args)...)); Note: From the given im...
Yes, this is allowed. decltype is an unevaluated context so the function isn't actually called, only it's return type is determined. Take std::declval for example. It is a function template declared by the standard and is only allowed to be used in an unevaluated expression as it may have no definition. I like to call...
68,668,956
68,669,301
C++ How to implement a compile time mapping from types to types?
Is there a canonical/reference implementation of a compile time map, which maps types to types? For example, I would need a type mapping from IBar -> IFoo or from int -> IFoo. At compile time I can then select IFoo when given a IBar. How would one go about this with C++17? Edit: here is an example using structs https:/...
You could define one with overloading and return types. This will act like a map data structure that you can initialize and reuse with many types for many purposes. template<typename T> struct type_tag { using type = T; }; template<typename K, typename V> struct pair { using first_type = K; using second_t...
68,669,010
68,669,157
Can't created a boost::shared_ptr from this
Say I have the following abstract Class A. Now I'm trying to create a shared_ptr to A from inside Class A. So in A i have the following function: class A { void A::setupArguments() const { ext::shared_ptr<A> ptr = ext::shared_ptr<A>(this); } } When compiling, it gives the error Error C2440 ...
Since setupArguments is a const-qualified function, this is of type const A*. And const A* is not convertible to A* so it fails to compile. You would need to use shared_ptr<const A> or remove the const qualifier. The full error given should look like: error C2440: 'initializing': cannot convert from 'Y *' to 'A *' ...
68,669,125
68,669,243
Do I need to include libraries in my main cpp, even if it's been included in a header file?
Say I have a file, player.h, and in player.h I have included the following: #include <iostream> #include <string> #include <vector> #include <fstream> Would I need to include these again in player.cpp, where I flesh out the functions declared in the header file? If I don't, do I need to include them when I run main.cp...
An include preprocessor directive tells the preprocessor to replace it with the contents of the file. Hence when you have // some_header.h #include <foo> and // some_source.cpp #include <some_header.h> then if you compile source.cpp, what the compiler gets to see after the preprocessing step is this: // some_source.c...
68,669,187
68,670,707
Overload operator over and over
I've overloaded operator << in my own vector class that will work as follows int main() { my_vector<int> vec; vec << 1 << 2 << 3; // will add elements at end [ 1, 2, 3 ] display(vec); } This works perfectly fine as I want, but I wanted to make it more efficient I did this 10 << vec; ...
One potential solution is to create a proxy object, or even a full-fledged vector object, that aggregates the elements to be inserted. The interface would look approximately like: vec_front_inserter(20) >> 10 >> my_vec; Note that I recommend using the extraction operator (>>) to indicate front-insertion, as it reads b...
68,669,576
68,669,695
C++ threading model for creating multiple instances of class spawning threads
Abstract: I am designing a class (Inner) which spawns 2 threads- a producer and a consumer. In one usage there is one instance and in another context there are multiple instances. In Standalone I need the two threads to continue writing/reading messages. However, if there's multiple instances I need the code to spawn t...
A resource of which you need one for each instance of a class, and who's lifetime is the same as that of the matching instance is best represented as a member variable. So just make the threads member variables of Inner that are launched at construction, and joined at destruction: template<Owner> class Inner { Inne...
68,669,802
68,670,019
My program cannot find my shared library during execution
My program cannot find my shared library during execution. That's how I compiled everything: //shared library fct g++ -c -fpic fct.cpp g++ -shared fct.o -o libfct.so //my program g++ main.cpp -L/home/user/shared_library/ -lfct -I/home/user/shared_library/ -o main When I tried to run the program, it gives me this erro...
The shared library path is needed twice, both at compile time and runtime. Passing the library path to the compiler does not guarantee that the linker will be able to find it. For a temporary solution, you can add home/user/shared_library to the LD_LIBRARY_PATH environment variable (on Linux & macOS). For a more perman...
68,669,838
68,669,904
Trouble using std::make_unique with member variable of class
I have not used std::make_unique before, and code inspection encouraged me to do it. If I use this, it does not display errors: auto x = make_unique<CChristianLifeMinistryHtmlView>(); But when I try it with my class member variable CChristianLifeMinistryHtmlView *m_pHtmlPreview it does not like it: m_pHtmlPreview = st...
Your issue is nothing to do with the class member, rather its type! std::make_unique() returns std::unique_ptr for the template type T (i.e. std::unique_ptr of an instance of type T) template< class T, class... Args > unique_ptr<T> make_unique( Args&&... args ); ^^^^^^^^^^^^^^ The member CChristianLifeMinistryHtmlView...
68,671,111
68,671,236
How to properly define is-derived-from-view-interface?
LWG3549 proposes that view_interface<D> does not need to inherit view_base, which allows range adaptors to better perform empty base optimization. In the latest [range.view], the definition of view concept has undergone the following changes: template<class T> concept view = range<T> && movable<T> && enable_view<...
That wording means "use template argument deduction". template <class D> void test(view_interface<D>&); template <class R> concept is_derived_from_view_interface = requires (R& r){ (test)(r); };
68,671,908
68,672,083
How to calculate sum of a vector till a specific index using accumulate() in c++
I would like to know if there is anyway to perform Sum of a vector till specific index using accumulate(). Example vector<int> v ={1,2,3,4,5,6}; int sum = accumulate(v.begin(), till_index_4, 0); All examples i found says accumulate(v.begin(), v.end(), 0); I tried with iterator also but my code is not compiled. Please ...
C++ standard library provides function std::next which takes an iterator into a sequence, and yields another iterator n steps apart. For std::vector iterators this is an O(1) operation. If you know that n-th position in your vector is valid, you can accumulate as follows: int sum = accumulate(v.begin(), std::next(v.beg...
68,672,040
68,678,313
Serial port receives same bytes it just sent
I'm trying to use Boost.Asio to read from and write to a serial port. Here is my code: void async_read(boost::asio::serial_port& serial_port) { auto buffer = std::make_shared<std::vector<uint8_t>>(64); serial_port.async_read_some(boost::asio::buffer(*buffer), [buffer, &serial_port](const boost::syst...
This is the expected behaviour for a serial port. These were typically used to connect a terminal like a vt100 to a computer. When you type on the keyboard, the character is sent to the computer, and the serial port echoes it back to the vt100 screen where it is displayed. If you run stty -a -F /dev/ttyTHS0 on the remo...
68,672,360
68,673,256
Why values [2][0] and [2][1] of glm::frustumLH_ZO are negated?
Let's say I am coming from a left-handed world space. My positive Z is into the screen, and my Y is up, the same as OpenGL's default in clip space. It is my understanding that, when coming from a right-handed world space (which is somewhat required when using older functions such as gluLookAt which maps the forward vec...
Why are these entries in the matrix flipped? You are right, they shouldn't be, but they are in the most recent glm code base to date. Looks like you found a bug in glm. It did probably go unnoticed so long because a) most people use glm with default GL conventions, and b) these two elements are typically 0 in your st...
68,672,384
68,672,755
Does the virtual keyword affect performance of the base class methods?
I read that there is minor performance hit when calling virtual functions from derived classes if called repeatedly. One thing that I am not clear about is whether this affects function calls from the base class itself. If I call a method in the base class with the virtual keyword, does this performance hit still occur...
If I call a method in the base class with the virtual keyword, does this performance hit still occur? That the virtual function is being called from the base class will not prevent virtual lookup. Consider this trivial example: class Base { public: virtual get_int() { return 1; } void print_int() { ...
68,672,586
68,672,977
How to compile programm with error "no matching function for call to 'to_string'"? c++
If I have here DATA_T = std::string, I can't compile this code, because of error "no matching function for call to 'to_string'". The function does not allow converting a string to a string. But I need to get the string anyway, how can I work around this error and compile the program? template <typename DATA_T> std::str...
As shown in other answers you can add a special case for std::string. This will solve your problem with std::string, but how about other types? When I first saw to_string I was rather disappointed, because it has only a finite set of overloads. However, I misunderstood what to_string is meant for. It is meant to conver...
68,672,933
68,673,078
Why does default initialization of a class field in C++ require destructor invocation?
Please help me with this program: struct U { U(int *) noexcept; private: ~U() noexcept; }; struct B { B(); ~B(); U v; //ok U w{nullptr}; //ok U u = nullptr; //error }; Here struct U has a private destructor only for demonstration that the destructor is not really invoked by the compiler a...
If B::B() is not compiled in this translation unit, why field default initialization is considered at all? Because member initialization is part of the class' definition. So it's the class definition itself that's invalid, without having to involve the definition of its constructor(s). In the standard, you can start ...
68,673,376
68,673,445
Fill an array with different classes which all inherit from the same class
My situation looks something like this: class Parent; class Child1 : public Parent; class Child2 : public Parent; class ChildOfChild1 : public Child1; std::vector<std::vector<Parent>> matrix; I want to be able to contain all the classes within this one matrix but I am not sure of the best way to do it. Right now i...
I think it is a duplicate of this question The thing you want to use is called Object Slicing Try this: std::vector<std::vector<Parent*>> matrix
68,673,408
68,673,845
Template accepting all member function pointers (including CV-qualified and ref-qualified)
I want to write a template which accepts a pointer to a member function (possibly CV-qualified and/or ref-qualified) while also matching all the relevant types (return value's type, class type and types of the arguments). Simple version could look like: template <typename ReturnValue, typename Class, typename... Argume...
How about pass the member function pointer to the foo and using a helper trait we retrieve the types of class, return, and arguments! Provide a trait something like: template<typename Class> struct class_traits final {}; template<typename ReType, typename Class, typename... Args> struct class_traits<ReType(Class::*)(Ar...
68,673,443
68,676,618
Is there a way to avoid implicit conversion to void*?
I'm using an API that accepts void* in certain functions. I frequently accidentally pass the wrong pointer type to the function, and of course it compiles fine, but doesn't work at runtime. Is there a way to disable implicit conversion to void* for pointers to a certain class?
You can add a deleted overload for the API function: // API function void api(void* p) { // ... } // Special case for nullptr inline void api(std::nullptr_t) { api((void*)nullptr); } // Everything else is disabled template <class ...T> void api(T&&... t) = delete; int main() { int i = 0; void* p = &...
68,673,667
68,673,701
Is there a way to put 2 variable in one variable? (it is kind of hard to explain)
For example: int hello1; int hello2; int hello3; for(int i = 1; i <= 3; i++) { helloi = 99; } How can I do something similar like this but with it actually working... also, sorry if I'm being vague here.
What you're looking for is an array: int hello[3]; for (int i = 0; i < 3; ++i) { hello[i] = 99; } Note that arrays use zero-based indexing, so the indices run from 0 to 2 rather than from 1 to 3.
68,673,780
68,673,906
The return value of >> operator
I just read an article that says: using the >> operator returns the operand which is on the left side of the >> operator. Also, it gives some examples like: #include<iostream> #include<string> using namespace std; int main() { int a, b, c; cout << "Insert 3 integers " << endl; cin >> a >> b >> c; co...
The >> operator for input streams (that is, classes derived from std::basic_istream) does, indeed return its left-hand operator. This is so that you can 'chain' input operations, as you have done in your cin >> a >> b >> c; statement. Looking at what this does, we first input a from cin and then continue by inputting b...
68,673,784
68,673,835
Best Practices? Converting from pointers to Unique_Ptrs
I am trying to convert from naked pointers to smart pointers. But I am not quite sure how to keep currentBar (Who will also be located in myBars) while using unique pointers Class Foo { public: Bar* getCurrentBar(); //!! other stuff not important private: Bar* currentBar; std::vector<Bar *> myBa...
There is nothing wrong with non-owning raw pointers. Use the unique_ptr in the vector to manage the lifetimes, and then use regular pointers or references for your interface. That would look like Class Foo { public: Bar* getCurrentBar(); // or Bar& getCurrentBar(); private: Bar* currentBar; s...
68,673,796
68,674,184
A version of DebugBreak that breaks the debugger without crashing the app
Is there a way to do something like DebugBreak() where when that function is hit the debugger breaks, but continue running when no debugger is attached? I have a lua error handler that presents a user-friendly error message when something goes wrong, but if I'm debugging I want to stop execution as soon as I've detecte...
You can use IsDebuggerPresent to check for an attached debugger, and then conditionally invoke DebugBreak: if (IsDebuggerPresent()) { DebugBreak(); }
68,673,969
68,674,132
Why can't I insert this transformed directory_iterator into a vector?
I am trying to insert a transformed range of directory entries into a vector using its insert(const_iterator pos, InputIt first, InputIt last) member function template. Unfortunately I can't get the following code to compile under GCC 11.1.0, which should have ranges support according to https://en.cppreference.com/w/c...
fs::directory_iterator is an input range. Which means that when you adapt it via transform you still get an input range (naturally). This transformed range's iterators have a postfix operator++ that returns void. This was arguably a defect in the C++98 iterator model, which still required even input iterators to have a...
68,674,947
68,675,018
C++ Understanding the Initialization
I have been going through a piece of code. Can someone explain this line of code. What is this doing? dt = (dt < temp ? dt : temp) Looking for a response.
This is using the ternary operator to implement a manual min() operation. The code is roughly equivalent to this: if (dt < temp) dt = dt else dt = temp; It is setting dt to the value of itself if dt < temp is true, otherwise it is setting dt to the value of temp if temp <= dt is true. IOW, it is the equivalent...
68,674,954
68,674,999
Why does this segmentation fault?
I was trying to make a factorial program that takes input from the terminal but it doesn't work.. giving it anything but no arguments gives a segmentation fault // factorial calculator #include <iostream> using namespace std; long factorial(long a) { if (a > 1) return (a * factorial(a-1)); else ...
long number = (long) argv[1]; This takes argv[1] and casts it to long. argv is a char*[] (for simplicity, I'll assume it's the very similar type char** for this explanation). Hence, argv[1] is a char*. Casting a char* to long takes its address as a numerical value. That's a position in memory on your computer and not ...
68,674,989
68,675,195
Issue compiling C++: gcc: error: CreateProcess: No such file or directory
As much searching as I've done, I've found so many answered questions here, yet absolutely none of them help my problem. I've been using gcc to compile my C code, and it's been working fine. I decided to start using C++. I tried compiling it and didn't work: PS D:\huntr> gcc ./test.cpp -o ./test.exe gcc.exe: error: Cre...
You did not install the required component mingw32-gcc-g++. You want to run the MinGW Installation Manager and select the required option on the Basic Setup pan.
68,675,165
68,675,206
can we clear errono after function call
I have some function call like below, and want to print success after success call, but got failure, even the function actually behave correctly. int myfunction() { // does some linux sys call for example int error = run_cmd ("ifconfig usb10 up"); int syserrorno = errno; strerror(syserrorno); retur...
When using errno, always set errno=0; before calling the function(s) whose status you want to check. C library and POSIX functions will set errno to a non-zero value if they encounter an error, but they do not reset it to zero if they succeed. (The reason they work this way: When a function reporting via errno is actua...
68,675,166
68,675,974
When I compile and run; which it does perfectly fine; it is not outputting anything to the file named "Warframe_Weapons_Sheet." in the code
#include <iostream> #include <string> #include <fstream> using namespace std; //Variables string Weapon_Name = "undefined"; string Weapon_Type_Name = "undefined"; bool Weapon_Type_M_or_R = false; int main(int args, char * argv[]) { cout << "Input the weapon name." << endl; cin >> Weapon_Name; cout << "...
The line if (Weapon_Type_M_or_R = true) { should read if (Weapon_Type_M_or_R == true) { The first is assigning a value of true to the variable and then "evaluating" that expression. The second is comparing the variable to the constant true which is what you want. Also note that if you are comparinf to true you can simp...
68,675,303
68,675,384
How to create a function that forwards its arguments to fmt::format keeping the type-safeness?
I have two broadly related questions. I want to make a function that forwards the arguments to fmt::format (and later to std::format, when the support increases). Something like this: #include <iostream> #include <fmt/core.h> constexpr auto my_print(auto&& fmt, auto&&... args) { // Error here! // ~~~~~...
C++23 may include https://wg21.link/P2508R1, which will expose the format-string type used by std::format. This corresponds to the fmt::format_string type provided in libfmt. Example use might be: template <typename... Args> auto my_print(std::format_string<Args...> fmt, Args&&... args) { return std::format(fmt, std:...
68,675,404
68,675,502
What is in unhandled error in c++ and how do I fix it?
I keep getting an "exception thrown" and "Unhandled exception" error on the last for loop of my code. I am not sure why this is happening, what it means, or how to fix it. The output won't even show up long enough for me to see if it is right. Any help would be appreciated. The error says : Exception thrown at 0x00855...
Your code has accessed uninitialized memory, the location 0xCCCCCCCC means uninitialized pointer in debug mode in visual studio 0xCC When the code is compiled with the /GZ option, uninitialized variables are automatically assigned to this value (at byte level). I think the '}' needs to be put befo...
68,675,444
68,675,479
why would type_identity make a difference?
I know that a lambda object is not a std::function object, so I understand that this would not work: template <typename ...args_t> void func(std::function<void(args_t...)> function_, args_t ...args){ /// do something here } void test() { func([](int a){ }, 1); } but why would it work if I add a type_identity...
The former code doesn't work because implicit conversion (from lambda to std::function) won't be considered in template argument deduction, which causes deduction of template parameter args_t on the 1st function parameter function_ failing. Type deduction does not consider implicit conversions (other than type adjustm...
68,675,472
68,675,537
Are all of zero() in chrono the same thing
I've found many zero() in the namespace std::chrono: std::chrono::system_clock::duration::zero(); std::chrono::minutes::zero(); std::chrono::seconds::zero(); std::chrono::milliseconds::zero(); ... Are they all the same thing? I'm coding with std::chrono and I have many variables whose types are std::chrono::seconds, s...
So the seconds, milliseconds etc are typedefs of the duration type with different ratios: ... std::chrono::milliseconds duration</*signed integer type of at least 45 bits*/, std::milli> std::chrono::seconds duration</*signed integer type of at least 35 bits*/> std::chrono::minutes duration</*signed integer type...
68,677,494
68,677,807
compare 3 or more objects
Currently, to compare 3 or more integers, We do it this way. (a < b) && (b < c). I know that, a < b < c translates to (a < b) < c and compares boolean with integer. Is there any way such that, I can overload some operators on a custom Class to achieve continuous comparison? How does languages like python does this? Upd...
a < b < c is grouped as (a < b) < c. If a or b are a type that you define, you could overload < for that type to return a proxy object, for which an overloaded < is also defined. That proxy object would contain the value of b along with the result of a < b. It's some hassle, and will not make your code readable either ...
68,677,903
68,678,007
Is it possible to omit the template parameter when i have the type on the left hand side of the assignment?
I want to write a function that returns a preallocated vector. Since it should work for any kind of vector, I am using a template. My question is whether it is possible to deduce the template parameter of the function call with the template parameter of the left hand side vector ? template<typename T> std::vector<T> cr...
Is it possible to deduce the template parameter of the function call with the template parameter of the left hand side vector ? No, except for conversion operator (for classes): struct CreateVector { std::size_t m_capacity; CreateVector(std::size_t capacity) : m_capacity(capacity) {} template <typename ...
68,678,424
68,678,585
code is resulting only first value of for loop eg. 1
[when we gives input 3 the expected answer is 6 but actual answer I getting is 1
The return statement is reached without control, so in the first loop step the function will return 1. The first step of the loop i=1, so ans +=i is 1. You need to let the for loop complete and then return the ans. #include <bits/stdc++.h> using namespace std; int sum(int n) { int ans=0; for(int i=1; i<n; i+...
68,678,512
68,678,634
Push_back elements dissapear after function is finished
I'm trying to recursively iterate through a tree of nodes and extract the bone structure by pushing elements to a vector called children using push_back() function. I can clearly see that the elements are being added but after the iteration is completed all children from the 2nd generation and below disappear. struct B...
Nothing disappeared from the bone in parent.children - it was just never modified. push_back adds a copy of Bone child to parent.children. That means you now have two bones: the original one still referred to by child, and the one in parent.children. You pass the original bone to the recursive call. That recursive cal...
68,678,903
68,685,841
What is the difference between default constructed object return and empty braces return in C++?
In the following code: #include <memory> struct A; std::unique_ptr<A> ok() { return {}; } std::unique_ptr<A> error() { return std::unique_ptr<A>{}; } Clang++ compiles fine ok() function and rejects error() function with the message: In file included from /opt/compiler-explorer/gcc-11.1.0/lib/gcc/x86_64-linux-gnu/1...
Neither should compile. The destructor for the result object is always potentially invoked. In the case of unique_ptr that requires A to be complete.
68,678,971
68,679,353
C++: using declaration and overload paradigm
I was looking at this page about "new" features of C++17. In particular I understand almost all of the following code: #include <iostream> #include <variant> struct Fluid { }; struct LightItem { }; struct HeavyItem { }; struct FragileItem { }; template<class... Ts> struct overload : Ts... { using Ts::operator()...; }...
using purpose is not only for changing accessibility, but to "resolve" ambiguity and/or unhide base methods. See https://en.cppreference.com/w/cpp/language/unqualified_lookup#Member_function_definition otherwise, if the declaration sets in Bi and in C are different, the result is an ambiguous merge: the new lookup set...
68,679,462
68,679,607
Need help storing a value I get from a sqlite3 DB in a C++ variable
I'm having a 'Data.db' with 3 tables in it that store some kind of 'football data'. One table is for 'teams' and another one is for 'players'. What I want to do now is to get the 'highest' ID from 'Teams' so I can assign newly generated players to that team. (Every player has a _teamId) I am able to print the ID I want...
You have a void* argument in sqlite3_exec which you currently set to 0. Instead, pass a pointer to an object there. This makes it possible to store what you like in that object in the callback. One often passes a pointer to an object and call a non-static member function in that object to deal with the callback. Exampl...
68,679,476
68,679,904
Non-static data members class deduction
I'm trying to solve type deduction issue. Here's the demo code, that uses function overloading to define, whether the passed variable is int or double std::string tcast( const double &x){ return "Floating Point";}; std::string tcast( const int &x){ return "Integer";}; int main(){ double dA; int iB; ...
We can use template argument deduction to our advantage here. Pointer to member data's syntax is DataType Class::*Pointer After deducing the member type we can call the required overload. template<typename Class, typename MemType> std::string tcast(MemType Class::*mData){ return tcast(MemType{}); } Link to the co...
68,679,699
68,690,809
Eclipse C++ unable to compile, undefined reference to 'xTaskCreate'
I am trying to move my project to Eclipse (from platformio). I want to pull in some libraries, but I am failing to setup the environment properly to get things compiled. in my main.cpp I have the following includes: extern "C" { #include <stdio.h> #include "board.h" #include "peripherals.h" #include "pi...
As always... once you know what to do, it's really simple ;-) Go to project properties C/C+ General Paths and Symbols In the source location tab, add a location where you want to store your libraries. E.g. I added a "link" and just typed in the name "libraries". Which felt a bit counter intuitive, maybe it can be do...
68,679,894
68,680,537
Boost - the child process remains as a zombie
I have wrote simple code that runs child process as detached: boost::process::child childProcess ( "sleep 10", boost::process::std_in.close(), boost::process::std_out.close() ); childProcess.detach(); After the child program finishes, command "top" in ubuntu shows me this entry: root 8935 0.0 0.0 ...
The zombie process remains because a SIGCHLD signal is generated to the parent process when the child process terminates, but the parent process doesn't handle this signal (by reading the child process' status information). Assuming the parent process needs to keep running, you can either (in the parent process) : wai...
68,680,070
68,680,975
Difference in memory used between declaring integer iterator inside and outside a nested for-loop
Code 1: int solution(vector<vector<int>>& arr){ int ans, m = arr.size(), n = arr[0].size(); // it is given that m is atleast 1 for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ // do something // i and j are only used for iterating over the array } } return ...
As Andreas Brunnet suggested I tried compiling both codes in godbolt.org and as HolyBlackCat said the assembly code for both the codes is the same. Here's the code used and the corresponding assembly code (the compiler option is x86-64 gcc 11.2). Code: #include <vector> int sum(std::vector<std::vector<int>> arr) { ...
68,681,229
68,681,265
c++ [Error] no match for call to '(Lion) (int&, int&, int, int)'
Given the following code : #include <iostream> #include <algorithm> #include <queue> using namespace std; int ch[25][25]; class State{ public: int x; int y; int dis; State(int x, int y, int dis){ this->x = x; this->y = y; this->dis = dis; ...
Did you mean to reassign simba instead of calling it as a function? (poor Simba ) simba = Lion(i,j,2,0);
68,681,258
68,681,385
Unexpected behaviour when scaling projection matrix in OpenGL
Here is my vertex shader: #version 330 core layout (location = 0) in vec3 vertexPos; uniform mat4 viewMatrix_; uniform mat4 projectionMatrix_; uniform mat4 modelMatrix_; void main() { gl_Position = projectionMatrix_*viewMatrix_*modelMatrix_*vec4(vertexPos, 1.0); } I am trying to scale my points by scaling the mod...
glm::mat4 model = glm::mat4(1.0f)*scale does not result in a valid scaling matrix. A valid scaling matrix would contain the scaling value on the first three elements of the diagonal, but have a value of 1.0 in the last diagonal element, e.g.: s 0 0 0 0 s 0 0 0 0 s 0 0 0 0 1 while your code produces a matrix where all ...
68,681,532
68,682,791
using namespace fltk is not working in my FLTK program
#include <FL/Fl.H> #include <FL/Fl_Box.H> #include <FL/Fl_Window.H> int main() { using namespace fltk; FI_Window window(200, 200, "Window title"); FI_Box box(0, 0, 200, 200, "Hey, I mean, Hello, World! "); window.show(); return Fl:: run(); } Above is basic FLTK program from the book Programming pr...
The line using namespace fltk; is valid only with the experimental/alpha, and dormant/discontinued, 2.0 version of FLTK. It is odd that you were told to add this line, since the rest of your code uses the naming scheme from the current, stable 1.3 version. Remove this line from your code.
68,681,544
68,681,926
C++ Typedef inside classes using private members
I tried to customize some types inside a class by using private members, which are used to set the size of customized containers. But I received: error: ‘CoverMatrix’ does not name a type error: ‘Board’ does not name a type How do I properly manipulate it? #include <vector> #include <array> #include <string> #include ...
You already use using correctly to set up the Matrix type. You really should just keep doing that with the other types too: using CoverMatrix = Matrix<int, _BOARD_SIZE* _BOARD_SIZE* _MAX_VALUE, _BOARD_SIZE* _BOARD_SIZE* _NUM_CONSTRAINTS>; using Board = Matrix<int, _BOARD_SIZE, _BOARD_SIZE>; But if you for some r...
68,682,776
68,682,845
OpenGL Not Seeing Triangle
I can't seem to see a red Triangle. OS: macOS on a M1 Mac // I did also do the core profile thing Code: #define GL_SILENCE_DEPRECATION #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <string> static unsigned int CompileShader(unsigned int type, const std::string& source) { unsigned int ...
Vertex array objects (VAOs) aren't optional in Core contexts like they are in Compatibility contexts. You need to generate and bind a VAO before setting up your vertex attributes and drawing: GLuint vao = 0; glGenVertexArrays( 1, &vao ); glBindVertexArray( vao ); ... glEnableVertexAttribArray(0); glVertexAttribPointer(...
68,682,873
68,682,996
C++ run-time template constant
I was trying to create a user-defined container type with using and private members in the class, which are not compile-time constants. The is not valid and complained by the compiler. Those private member constants will only be initialized at runtime. Is there such a remedy for this kind of scenario? #include <vector>...
The first issue you get, compiling this, with a placeholder class Board{}; is something like: Compilation failed For more information see the output window x86-64 clang 12.0.1 - 405ms :23:37: error: invalid use of non-static data member '_BOARD_SIZE' using CoverMatrix = Matrix; What this tells you is that the compile...
68,683,030
68,750,118
How to "flag" the equivalent of "export" to the compiler pre-modules?
Imagine I've got the following files: simulate.h: #ifndef SIMULATE_H #define SIMULATE_H #include "my_data_type.h" MyDataType Simulate (); #endif simulate.cpp: #include "simulate.h" // include lots of other things // define lots of functions and new classes to solve sub-problems // finally we define the "Simulate" f...
As Jarod42 pointed out in the comments, we can used unnamed/anonymous namespaces, whose contents are unreachable from other translation units (N3797: 7.3.1.1): An unnamed-namespace-definition behaves as if it were replaced by inline /*opt*/ namespace unique { /* empty body */ } using namespace unique; namespace uniqu...
68,683,273
68,683,543
Access efficiency of C++ 2D array
I have a 2D array a1[10000][100] with 10000 rows and 100 columns, and also a 2D array a2[100][10000] which is the transposed matrix of a1. Now I need to access 2 columns (eg. the 21th and the 71th columns) of a1 in the order of a1[0][20], a1[0][70], a1[1][20], a1[1][70], ..., a1[9999][20], a1[9999][70]. Or I can also a...
You can benefit from the memory cache if you access addresses within the same cache line in a short amount of time. The explanation below assumes your arrays contain 4-byte integers. In your first loop, your two memory accesses in the loop are 50*4 bytes apart, and the next iteration jumps forward 400 bytes. Every memo...
68,683,416
68,683,923
Can spaceship operator be used in fold expressions?
None of the compilers I tried accept such code: template <int ...a> bool foo() { return (a<=> ... <=>0); } But for any other <=,>=,==,!=,<,> it compiles. cppreference is clear here - there is no <=> on the list of binary operators we can use for fold expression. Is this an intentional omission in the C++ standard, or a...
This is intentional. The problem with fold-expanding comparison operators is that it works by doing this: A < B < C < D. This is only meaningfully useful in circumstances where operator< has been overloaded to mean something other than comparison. This is why an attempt was made to stop C++17 from allowing you to fold ...
68,683,535
68,684,110
Unrecognized \001\000 at the end of string..?
I use a NRF24L01 Module to communicate with 2 arduino.. I send this: const char hello[32]; memcpy(hello, "World", 5); now, I receive on the other side this: "World\001\000\000\000" how can I clean my string or what's that? thanks, daniel
You are not copying the string literal's null terminator, so you would need to specify 6 instead of 5: memcpy(hello, "World", 6); Except that hello is an array of const characters, so you actually can't write to it, only initialize it. Your memcpy() is undefined behavior. Use this instead: const char hello[32] = "Worl...
68,684,634
68,690,615
error: expected primary-expression before ‘...’ token on gcc
I was getting this compile error on gcc 10.3 : <source>:15:22: error: expected primary-expression before '...' token 15 | void g() { a.f<Cs...>();} | ^~~ <source>:15:22: error: expected ';' before '...' token 15 | void g() { a.f<Cs...>();} | ^~~ ...
the solution is to use use 'template' keyword to treat 'f' as a dependent template name like so : template<typename ...Cs> void g() { a.template f<Cs...>();}
68,684,918
68,685,069
Getting incorrect result with cusolverDnDpotrfBatched
I want to find the Cholesky decomposition of a 3x3 matrix using cusolverDnDpotrfBatched, but I am not getting the zeros that should be present in a lower triangular matrix. Here is the matrix for which I want to compute the cholesky decomposition [1 2 3; 2 5 5; 3 5 12]. Is it supposed to be this way? What am I missing?...
I am not getting the zeros that should be present in a lower triangular matrix. Perhaps you may wish to read the documentation: If input parameter uplo is CUBLAS_FILL_MODE_LOWER, only lower triangular part of A is processed, and replaced by lower triangular Cholesky factor L. Remark: the other part of A is used as...
68,685,133
68,685,941
Must aggregate field destructor be available for the code creating the aggregate in C++?
Please consider the following example with an aggregate struct B with the field of type U. The field's destructor is private, but available to the aggregate due to friend declaration, and not available for calling from main function: class U { ~U() {} friend struct B; }; struct B { U v{}; }; int main() { ...
Access to the destructor is indeed required by the standard. Quoting from N4868 (closest to the published C++20), [dcl.init.aggr]/8 says: The destructor for each element of class type is potentially invoked from the context where the aggregate initialization occurs. [ Note: This provision ensures that destructors can ...
68,685,525
68,686,141
std::multimap equal _range and C++20 std::views::values do not work nicely together
I have the following code, it works, but C++20 version does not look much better than C++17 version. My guess issue is that multimap equal_range returns a pair and ranges can not figure out that is a pair of valid iterators. Is there a way to write this in a shorter nicer way? #include <iostream> #include <map> #includ...
The problem is that equal_range returns a pair<It, It>, which is (unfortunately) not itself a range. This is one of the more unfortunate legacy API decisions in my opinion - since we have this excellent name but it does something... less than great. You used to be able to take a pair<It, It> and easily convert it to a ...
68,686,037
68,686,294
implementing typelist replace operation using variadic templates
I'm trying to implement a ReplaceAll metafunction for variadic template version of typelists (inspired by Modern C++ Design) and so far I could achieve the desired outcome with the following code: template <typename... Elements> struct Typelist {}; // // helper metafunction to set "Head" of typelist // template <type...
You might simplify your code and get rid of the recursion with template <typename TList, typename T, typename U> struct ReplaceAll; template <typename ... Ts, typename T, typename U> struct ReplaceAll<Typelist<Ts...>, T, U> { using Result = Typelist<std::conditional_t<std::is_same_v<Ts, T>, U, Ts>...>; }; Demo
68,687,040
68,687,419
I can't find any error that will lead to this result
I am new to C++ and want to test out how much I actually learned so I made this simple cRaZyTeXt generator. But there's a weird bug I can't find any way to solve. Codes are here: #include <iostream> #include <string> #include <algorithm> #include <windows.h> char convertToUppercase (char x) { int asciiCode {static...
For starters variable length arrays as for example the declaration of this array char userInputArray [userInput.size()]; is not a standard C++ feature. There is no need to use auxiliary arrays to perform the task. You could change the original object userInput of the type std::string itself. This variable length array...
68,687,067
68,687,553
Memory-mapped C++ objects non hardware members
I am developing a driver for a piece of memory mapped hardware using C++ and I defined a class that represents this device. It looks something like this: class device { method1(); method2(); private: device_register reg1; device_register reg2; } The class has two files: device.cpp and device.h. The member variables ...
You should create a separate POD (Plain Old Data) struct for the registers, because a non-POD class/struct could ruin your memory mapping even without adding extra data members. In POD types, the offset of the first data member is guaranteed to be 0, which is what you need. In non-POD types this contract is not always ...
68,687,304
68,688,850
Does designated initializer of sub-aggregate require curly braces?
In the following program, aggregate struct B has the field a, which is itself an aggregate. Can C++20 designated initializer be used to set its value without surrounding curly braces? struct A { int i; }; struct B { A a; }; int main() { [[maybe_unused]] B x{1}; //ok everywhere [[maybe_unused]] B y{.a = {1}}; ...
TLDR; GCC is right, everyone else is wrong because they're pretending that designated initializer-lists act like equivalent non-designated initializer-lists all the time. To understand what is happening here (and why compilers disagree), let's look at your first example: B x{1}; Since we're using braces, the rules of...
68,687,752
68,687,796
How do I get a value from the default constructor to the console?
I want to output data from the default constructor, that is, 0, 0 and 0. The compiler swears if the call constructor is not initialized when calling #include <iostream> #include <string> class Date { public: Date() : day(0), month(0), year(0) {} Date(unsigned d, unsigned m, unsigned y) : day(d), month(m), year...
To initialize a class on the stack with the default constructor you leave off the parenthesis, Date dt; std::cout << dt << std::endl; return 0; also, the std::cin.get() will never be run as it's after the return 0;
68,687,820
68,688,907
is it possible to overload std::chrono::duration_cast?
I have a device that reports time as integer seconds and fractional seconds in clock ticks. For this particular device, the clock operates a 256MHz. I've defined a custom resolution that I use in duration and time_points: using Res = std::chrono::duration<uint64_t, std::ratio<1, 256'000'000>>; (unless it is pertinent,...
I agree you hit overflow. But it isn't because system_clock::rep is int. Indeed your system_clock::rep is int64_t, and yes it does overflow for this operation. Your system_clock::period is nano. And the conversion factor to convert nano to std::ratio<1, 256'000'000> is 32/125. And 32 * 1628286679505051812 overflows...
68,687,828
68,687,970
Find kth largest element using quick select algorithm
#include <bits/stdc++.h> using namespace std; class Solution { public: int partition(vector<int> &nums, int low,int high,int pivotElement) { int pivotPoint=low; for(int i=low;i<=high-1;i++) { if(nums[i]<=pivotElement) { swap(nums[i],nums[pivotPoint...
The swap in partition changes the value of the local variable pivotElement, which will not be propogated back to the caller. (You'd get the same effect with nums[pivotPoint] = pivotElement;.) You need to pass pivotElement by reference, and pass nums[high] directly in order for nums[high] to be updated: int partition(ve...
68,687,977
68,688,066
Referencing my own object: When is it allowed and when is it not?
It looks like as if I can sometimes reference my own object and sometimes not - for example: #ifndef TILE_H #define TILE_H #include "position.h" #include <vector> #include <tuple> using std::vector; using std::pair; namespace Game { class tile { public: tile(int x, int y, int value); void savePosition(); ...
A function declaration does not require that its argument types be complete. struct A; void f(A); // fine That requirement is only applied at the function definition struct A; void f(A); // fine // void f(A) { } // not fine struct A { }; void f(A) { } // fine There is a special exception for class member functions: ...
68,688,447
68,688,473
Custom clone of unique_ptr doesn't return correct type
I have these 2 classes: class Operation { public: virtual std::unique_ptr<Operation> clone() = 0; }; class Plus : public Operation { public: std::unique_ptr<Operation> clone() override { return std::make_unique<Plus>(*this); }; }; I have this function, that checks the type ...
Your template parameters are backwards. You are setting Base to Plus, and T is deduced as Operation. You are thus calling std::is_base_of<Plus, Operation>::value which is always false since Plus is not a base of Operation. The opposite is true, Operation is a base of Plus. So swap the template parameters around: te...
68,688,892
68,689,171
Is it legal to cast a pointer to a partially constructed object to a pointer to a base class?
That is, is something like this always legal? struct Derived; struct Base { Base(Derived*); }; struct Derived : Base { Derived() : Base(this) { } }; Base::Base(Derived *self) { if(static_cast<Base*>(self) != this) std::terminate(); } int main() { Derived d; // is this well-defined to never call terminate? } A...
This is fine: [class.cdtor]/3 says To explicitly or implicitly convert a pointer (a glvalue) referring to an object of class X to a pointer (reference) to a direct or indirect base class B of X, the construction of X and the construction of all of its direct or indirect bases that directly or indirectly derive from B ...
68,689,343
68,691,192
Binary search of range in std::map slower than map::find() search of whole map
Background: I'm new to C++. I have a std::map and am trying to search for elements by key. Problem: Performance. The map::find() function slows down when the map gets big. Preferred approach: I often know roughly where in the map the element should be; I can provide a [first,last) range to search in. This range is alwa...
There is a reason that std::map::find() exists. The implementation already does a binary search, as the std::map has a balanced binary tree as implementation. Your implementation of binary search is much slower because you can't take advantage of that binary tree. If you want to take the middle of the map, you start wi...
68,689,528
68,768,588
Is it safe to separate your templated class' declaration and definitions on different header files?
I'm trying to create a library for a school work, and I've been wondering if it is safe to declare a templated class on the main header file containing the class definition and method declarations, but then separating the method definitions in a different header file? Because I have been able to do this in my example b...
This is indeed a better approach because it makes your code look simple and better. Moreover, it is the main reason why header file is used. Your main header file will simply tell that what functions/classes are you using and without even viewing your code, anyone can guess if you are working correctly or not. There wo...
68,689,546
68,689,879
cannot find -lboost_filesystem and -lboost_system
I am using boost::filesystem in my sample program, but getting linking error. Here is the sample program: #include<boost/filesystem.hpp> using namespace std; int main() { string fromPath = "/home/anurag/testfile"; string toPath = "/home/anurag/testfile"; boost::filesystem::copy_file(fromPath,toPath); ...
-lboost_filesystem causes the linker to look for a file named libboost_filesystem.a or libboost_filesystem.so as your file is called libboost_filesystem-gcc61-mt-s-1_64.a you need to pass -lboost_filesystem-gcc61-mt-s-1_64 to the linker
68,689,700
68,692,445
Why Can't Read The File(doesn't display the data)?
*i Want to get from the user his address and store it in file.dat then display these data For Example: First Name: joooooosh Last Name: Mikeeeeee Governorate: Gize City: 6 October132 Area: 4th District ...
If opening iFile fails then the call to read will also fail and the body of the while loop will never execute. You should check the file opens successfully before using it: ifstream iFile("shippingAddresses.dat", ios::binary); if (!iFile) { std::cout << "open failed\n"; return; } while (iFile.read((char *)this,...
68,689,801
68,748,448
C++ pointer to pointer in openCL 2.1
So Right now I'm trying to pass a pointer of a pointer into an OpenCL 2.1 Kernel using Shared Virtual Memory and from what I've read this should be possible however when I attempt to build the kernel i get the following error: kernel parameter cannot be declared as a pointer to a pointer __kernel void MyKernel...
Maybe your compiler defaults to OpenCL 1.2, where this is not allowed. From the OpenCL 1.2 restrictions: "Arguments to __kernel functions in a program cannot be declared as a pointer to a pointer(s)". In OpenCL 2.1, it should theoretically be possible. However, it is still better to use a linearized 1D array as this al...
68,689,873
68,689,923
What does "owning" mean in the context of programming?
cppreference uses it to describe std::string_view: std::basic_string_view (C++17) - a lightweight non-owning read-only view into a subsequence of a string. devtut and sodocumentation use it to describe std::string_view as well: C++17 introduces std::string_view, which is simply a non-owning range of const chars, i...
You can own a resource, i.e. anything that there is a limited amount of. This is usually memory or system handles. Whatever owns the resource is responsible for releasing it when done using it. std::unique_ptr and std::shared_ptr are examples of an owning wrapper. It releases their memory when it goes out of use. Same ...
68,690,035
68,690,092
How to access private class members with out being in the in class
I want to change the data in the private members but the delete_Data() function is outside the class so how to get the members without being declared in the class and erase them using the delete_Data() functionthe only way it works for me it to declare delete_data()function in the class on public section but our teach...
Usually✝, the member functions and the friends of the class can access the private members of a class, via an instance of the class. Therefore, in your case, make the delete_Data function as friend function. class data { private: std::string name; int id; public: // ... friend void delete_Data(data& ob...
68,690,285
68,693,254
Path between two points inside a Boost Geometry polygon
I'm trying to find the "path" to connect two points in a c++ boost polygon. I have a polygon like that namespace bgm = bg::model; using Point = bgm::d2::point_xy<double>; bgm::polygon<Point> poly; bg::read_wkt("POLYGON((" + points_poly + "))", poly); And i have randoms points in the polygon. And i would like to know ...
It's pretty unclear what the actual question is, so here's what asnwers directly to your question: Poly poly{{ {-4, 14}, {17.75, 13.99}, {17.75, 7.95}, {10, 8}, {10, 2}, {16, 2}, {16, -8}, {22, -8}, {13.97, -13.17}, {6, -8}, {12, -8}, {12, -2}, {-0.99, -2.06}, {-0.9, -7.95}, {-...
68,691,268
68,691,327
Confused about the cout operator behavior with string and int
I ran this particular code using namespace std; int main() { cout<<(3 + "Hello World"); return 0; } The output is llo World I am pretty confused why I am getting this output, can anyone please care to explain.
"Hello World" is an array. When you use the value of an array, it implicitly converts to a pointer to first element - i.e. pointer to the character 'H' in this case. When you add an integer N to a pointer, the result is a pointer to the N'th next sibling element of the array. In this case, "Hello World" + 3 is a pointe...
68,691,430
68,692,796
pthread_mutex_lock_full assertion failed error
I have been programming an pthread application. The application has mutex locks shared across threads by the parent thread. For some reason, it throws the following error: ../nptl/pthread_mutex_lock.c:428: __pthread_mutex_lock_full: Assertion `e != ESRCH || !robust' failed. The application is for capturing high speed ...
In GLIBC 2.31, you were running the following source code of pthread_mutex_lock(): oldval = atomic_compare_and_exchange_val_acq (&mutex->__data.__lock, newval, 0); if (oldval != 0) { /* The mutex is locked. The kernel will now take care of everything. */...
68,691,471
68,691,517
Inline Lambda variable vs Inline function vs Inline template function with automatic type deduction
Suppose I want declare an inline function which will take an argument of arbitrary type. I think it can be done by the following ways. ////// inline auto const myfunc = [&](const auto& val){return something(val);}; ////// inline auto myfunc(const auto& val) { return something(val); } ////// template<class T> inline...
They all 3 define something sightly different. Hence, answer to 2 is: Choose the one that does what you want. 1) I'll levave to you, because you can easily try them out to see if they compile. 3) isn't that relevant, because choosing between them is a matter of what you actually need, not of style. inline auto const my...
68,691,527
68,692,014
How to create a multi dimensional std::array using a template?
How can I create a multi dimensional std::array of type Type with (of course) known initial constexpr dimensions with some smart variadic template "MDA". The number of dimensions shall be variable. In the end I want to be able to write: MDA<int,3,4,5,6> a4d{}; and the result should be equal to std::array < std::array ...
Certainly possible with use of helper class templates, C++11 (except the static assert part) #include <array> template<typename T, std::size_t Head, std::size_t... Tail> struct MDA_impl{ using type = std::array<typename MDA_impl<T, Tail...>::type, Head>; }; // Base specialization template<typename T, std::size_t N...
68,691,533
68,691,602
How to make a scoped variable global in C++?
I am working on a large project and require to make a scoped variable global so it can be accessed throughout the whole class. A simple scenario of where this might be used is to make the integer x global. class a { public: a() { int x; } void print() { std::cout << x << std::endl; ...
Make a member variable out of it and your class templated, not the constructor: template<typename FunctionType> class thread { private: template<typename StoreFunctionTypeTemp> class FunctionTypeClass { StoreFunctionTypeTemp Variable; }; FunctionTypeClass<FunctionType> FunctionTypeDataStore...
68,691,598
68,694,410
draw with the mouse on QQuickPaintedItem
I have this code class cCanvas : public QQuickPaintedItem .. .. void cCanvas::paint(QPainter *ppainter) { ppainter->setPen(QPen(colorValue())); ppainter->drawLine(0, 0, rand() % 255 ,100); } QML MultiPointTouchArea { onPressed { canvas.update(); } } It works, but when drawing each new line, th...
Qt does not keep a cache of what was painted, so you only see what was painted last. A possible solution is to save the line instructions in a QPainterPath: #ifndef CCANVAS_H #define CCANVAS_H #include <QPainterPath> #include <QQuickPaintedItem> class CCanvas : public QQuickPaintedItem { Q_OBJECT Q_PROPERTY(Q...
68,691,684
68,692,019
class(with static member) initialization in c++
I was trying to understand friend functions and I found myself writing the following code though I have understood the friend functions, this code leaves me with new questions: how does the class initialise here when I havn't instantiaied any object I know static member is shared by all objects of the class and is i...
how does the class initialise here when I havn't instantiaied any object You've initialised the variable in its definition: int base::base_i = 5; // <-- the initialiser The language implementation takes care of the rest. at what point does the variables base_i and derived_i get assigned to respective values from...
68,691,800
68,691,839
Sorting visualization - how to solve circular dependency?
I'm writing sorting visualization. I want it to handle events and update screen while the algorithm is running. I have a Controller class which has SortContext attribute. I want SortContext's sort method to take reference to the controller so it can use methods update and isAppRunning but I get an error: Controller ha...
Forward declare Controller class in SortContext.hpp and include SortContext.hpp in Controller.hpp: #include "SortContext.hpp" class Controller { private: SortContext context; View view; std::vector<Sortable> data; bool algorithmRunning = false; void handleEvents(); public: Controller(); void update(...
68,692,264
68,692,392
Recursive template instantiation exceeded error in dtor, but not in ctor. Why?
Try clang++ and g++, same result for both. fatal error: recursive template instantiation exceeded maximum depth template<class T> struct Bar { ~Bar() { if (ptr) { delete ptr; } } Bar<Bar<T>> * ptr{nullptr}; }; int main() { Bar<void> obj; } But ctor version compiles without error: template<class T> struct Ba...
What's the problem with dtor version? Think about what a declaration like Bar<void> obj; means. That object needs have its destructor called when main returns. So the destructor ~Bar<void> will be instantiated. What does the instantiated destructor contain? A delete expression. You may reason that it's under a nulli...