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
63,108,448
63,108,532
c++17 error message: "reference to non-static member function must be called" when using a macro on a vector
I'm learning c++ and was playing around with macros. I tried defining push_back as pub, and it gave me this error: error: reference to non-static member function must be called vect.pub(1); Here's my code: #include <vector> using namespace std; typedef vector<int> vi; #define pub push_back; int main(){ vi vect; ...
#define pub push_back; //... vect.pub(1); This expands to the following, which is invalid syntax due to the extra ;. vect.push_back;(1); So drop the ; and #define pub push_back.
63,108,450
63,108,890
How do I pass a variable to derived class from base class?
I'm trying to pass down the input values of variables from the base class Watch to the derived class Repair. I have tried to insert getter and setter function inside the Watch class but it doesn't work. Please help! For example, I insert "antique" as the watch variable but it doesn't pass down to the watch variable ins...
Summary You don't need both the Watch w; and Repair r; variables - just use r for everything You're not assigning to the variable watch - instead you're comparing it using operator==() Comment on design First of all, I wouldn't recommend using inheritance for this. While it can be done, inheritance is used to model a...
63,108,570
63,109,021
bool class template generic copy and move constructor
I was trying to implement a copy constructor for a class template that allows for all instantiations to converted from one version of the class template to the other. This lead to the following code #include <memory> #include <iostream> template<bool binary> class Bar { private: friend class Bar<!binary>; std:...
From https://en.cppreference.com/w/cpp/language/copy_constructor A copy constructor of class T is a non-template constructor whose first parameter is T&‍, const T&‍, volatile T&‍, or const volatile T&‍, and either there are no other parameters, or the rest of the parameters all have default values. Hence you can't de...
63,108,657
63,110,209
Cursor remains at the end when I try to give user input in getline
The following is the the code for asking a name and then returning a statement which has your name in it. #include <iostream> #include <string> int main(){ std::string name; std::cout << "What is your name:\n"; std::getline(std::cin, name); std::cout << "Your name is " << name << ".\n"; return 0...
The usual way to handle this sort of thing is the use the editline or GNU readline linrary (which is a C libary): #include <stdio.h> #include <editline/readline.h> #include <editline/history.h> int main() { const char *name = readline("What is your name:"); printf("Your name is %s.\n", name); return 0; } ...
63,108,726
63,116,663
CMake and make looking for libjawt.so file in the wrong place
I have a C++, Java, and CMake project but I am, at the moment, unable to compile it. I encounter the following error. make[2]: *** No rule to make target '/usr/lib/jvm/default/jre/lib/amd64/libjawt.so', needed by 'build/Ygor'. Stop. From what I've read online that means the compiler cannot find that file, either it's...
By calling the line: find_package(JNI) CMake provides several JNI cache variables that allow you to specify the location of the associated libraries (if not found or found libraries are not correct). You can run cmake from the command line on your project to see a list of the cache variables: cmake -LA This is also e...
63,108,984
63,109,145
C++ initializer list members still calling default constructor?
I'm having a problem initializing a shared_ptr member of a class I'm working on. I have two classes, A and B: class A { int _x; int _y; public: A(int, int); }; A::A(int x, int y) { _x = x; _y = y; } class B : public A { std::shared_ptr<A> _a; public: B(std::shared_ptr<A>); }; B::B(std::shared...
Since B is derived from A, every B is an A. That means to construct a B, you must also construct an A. However, you do not tell B's constructor how to construct an A, so the default constructor is used. If you want B to be derived from A and only hold a shared_ptr to A, then A must not do anything you don't want B to d...
63,109,411
63,110,174
Meta-program to remove adjacent duplicates from compile time vector
I have been trying to write a meta-function to remove adjacent duplicates from a compile time vector defined as template <int...> struct Vector; Eg. If the input is: Vector<1, 2, 2, 3, 3, 4, 5, 5> Output should be: Vector<1, 2, 3, 4, 5> But if input is: Vector<1, 2, 2, 3, 4, 4, 1, 5> output should be: Vector<1, 2, ...
You don't need the template template parameter template<int...> class Vector. When first two elements are equal, one of them should be retained: template <template<int...> class Vector, int First, int... Last> struct uniq<Vector<First, First, Last...>> { using type = typename uniq<Vector<First, Last...>>::type; ...
63,109,475
63,109,565
Stuck in infinite loop while trying to find nth root of x
double power(double base, int exponent){ //Just for context, a double is larger than a long long int //Also method programmed to assume non-decimal, non-negative input for root double answer = base; if(exponent == 0){ return 1.0; } else if(exponent > 0){ ...
One problem is that to check for epsilon the code should be while (fabs(error) > epsilon) { ... improve ... } you are instead checking the next approximation against epsilon (also without fabs). The other problem is that output stream uses a fixed number of decimals when printing floating point values, if you want...
63,110,068
63,110,166
C++ destructor called before lifetime of scope
I have a question about triggering a destructor for an object prematurely. I have an dynamically allocated array of pointers to dynamically allocated Word objects. The name of the array is words_. words_ is a class attribute of another class called Dictionary. In my Dictionary class, I have a function where I access ea...
Word curr_word = *curr_word_ptr; defines a local Word, that only lives in the local scope, your function. When the function exits, it is destroyed. Note it is a copy of the initial Word that is destroyed, not the original. If you want handy syntax so you don't have to dereference all over, or make a copy, use a referen...
63,110,069
63,110,346
How can I create an Window without menu, bar, frame, 3D effect...etc with exact same size of another window?
Currently I am trying to create WaterMark window which be generated on Window of designated process. Below Example is the execution of program with notepad.exe designated. However if you look close enough, you would find out that WaterMark Window's size isn't actually same as that of original Window. I am adjusting Wi...
You can get the window size with GetWindowRect. You have to know the window handler, though. To know the window handles here is a small code (you can find the whole thing here.) (Not compiling code.) EnumWindows (&Enum, (LPARAM)&_windows); BOOL CALLBACK Enum (HWND hwnd, LPARAM lParam) { WINDOWPLACEMENT place; ...
63,110,896
63,111,227
Capture lambda by value
I defined a lambda in struct Baz that capture the instance of struct by value. So I expect if modifying happened to members of struct in body of lambda it does not appear outside of lambda but it appears. Also I define a lambda in a function (outside of struct)that capture struct by copy it does as I expect. Could y...
s isn't a captured variable it is a member variable of the captured this pointer. Due to this sometimes surising behaviour c++20 has deprecated the capture of the this pointer when using [=] captures. If you want to capture a copy of s you need to do that explicitly: struct Baz { auto foo() { return [s...
63,111,226
63,115,621
VK_NULL_HANDLE is always 0; Why not nullptr?
In most cases, you can get away with assigning VK_NULL_HANDLE to any handle defined by VK_DEFINE_HANDLE(object) or VK_DEFINE_NON_DISPATCHABLE_HANDLE(object), but std::exchange() fails to set this value in almost all cases. In most situations I have to call std::exchange(m_dispatchableHandle, nullptr) and std::exchange(...
Templates in C++ require precise type, not just compatible one, to properly instantiate. As such C's NULL (defined as 0) might be a problem. 0 might also be a problem as it is int, not uint64_t, which is the ABI of Non-dispatchable Handles (which can be stored in 64 bit pointer to get some type safety out of C). This i...
63,111,352
63,111,424
Initalizing a cpp class with new
I have created a Vector3 class: class Vector3{ public: float x, y, z; }; I can do this: Vector3 v; v.x = 0.0f; v.y = 0.0f; v.z = 0.0f I want to initialize it like this: Vector3 v = new Vector3(0.0f, 0.0f, 0.0f);
I suppose you are asking how to write a constructor that initializes the members: class Vector3{ public: float x, y, z; Vector3(float a,float b, float c) : x(a),y(b),z(c) {} Vector3() : x(0.0f), y(0.0f), z(0.0f) {} }; Now you can write Vector3 v(0.0f, 0.0f, 0.0f); Vector3 v2; Do not use new to create ...
63,111,369
63,152,156
How get a local time with same time format on windows?
I have a c++ class code which return a local time: SYSTEMTIME sm; GetLocalTime( &sm ); but sm.wHour always returns an hour in 24 format, it doesn't concern my windows os time format settings!! (ie. use 24 or 12 time format). How can I get a local time hour according to my windows os time format settings?
Just found GetDateFormatA is outdated, you should use GetDateFormatEx Simple example: #include <windows.h> #include <iostream> #include <io.h> #include <fcntl.h> int main() { _setmode(_fileno(stdout), _O_U16TEXT); const int len = 50; LPWSTR date = new WCHAR[len]; GetDateFormatEx(LOCALE_NAME_USER_DEFAU...
63,111,429
63,111,581
memset and struct with getters/setters
I have a simple pod struct, for example: struct T { int x; float z; } I want to make a data private and add getters/setters. Can I use memset on that struct ? memset(obj, 0, sizeof(T));
I want to make a data private and add getters/setters. Can I use memset on that struct ? Yes, you can use memset as long as the class is trivially copyable, and the object isn't a potentially overlapping subobject. P.S. Memsetting float with zero bytes isn't technically guaranteed by C++ to set it to value zero, alth...
63,111,531
63,111,759
Heap corruption after second use of strcat
This is driving me nuts because I'm not seeing what bonehead mistake I'm making here. In the following snippet (note this is just a test snippet is from a larger method), I'm basically just attempting to copy a string that's retrieved from a SQL method, and then if the user specifies in the method an additional number ...
You may be misunderstanding how the strdup function works. In the following line: pLocalArray[uRow] = _strdup(buff); which is called to initially allocate memory for pLocalArray[uRow], the amount of space allocated will be the actual length of the buff string, interpreted as a nul-terminated character array; this ...
63,111,664
63,111,774
Counting elements in array template
I wrote a template for a 2D array and devise a method that counts how many elements are in the array. However, the method doesnt return anything. template <class T, int row, int column> class array2d { private: typedef T value; //typedef value * iterator; std::vector<T> array; public: array2d() : array...
T& is a very bad choice of return type. You get UB from returning reference to local object and what if I use your array2d with double type? Can I use array2d with non-arithmetic type? Return std::size_t instead. std::size_t length(){ return array.size(); }
63,112,299
63,112,581
How to understand Singleton in c++?
Please tell me why the singleton code below works? Every time When Singleton::instance() is called, an INSTANCE will be created, so are two INSTANCE supposed to be created in the following code? #include <bits/stdc++.h> using namespace std; class Singleton { private: Singleton() = default; public: ...
You should read about the static keyword. It can have different meaning and here you have two of them: static Singleton& instance() // ^ ---------------------------- (1) { static Singleton INSTANCE; // ^ ------------------------- (2) return INSTANCE; } The first static declares the method...
63,112,631
63,112,911
Accessing private data with reinterpret_cast
This seems to compile and access the private data successfully. Is this well-defined behavior? #include <iostream> #include <string> using std::string; class foo { string private_data = "Hello World"; }; int main() { foo f; auto* pprivate_data = reinterpret_cast<string*>(&f); std::cout << *pprivate_d...
No, the behavior is undefined. For such a reintepret_cast to have meaning, the two objects must be interconvertible [basic.compound] 4 Two objects a and b are pointer-interconvertible if: they are the same object, or one is a union object and the other is a non-static data member of that object ([class.union]), or on...
63,112,792
63,113,100
Unions or references as struct members
Is there any guarantee that references to sibling members will be optimized out? Motivation: struct using_union { union { std::uint32_t i; std::uint8_t by[ 4 ]; } data; }; struct using_alias { // shorter notation, no need for .data.i or .data.by std::uint32_t i; std::uint8_t (...
There is no such guarantee. Be careful about strict aliasing, std::uint8_t[4] is not one of the allowed aliasing types for reinterpret_cast. Also, there is no reason for a workaround at all since if you leave out the name of the union, its members are moved to the outer namespace, i.e the following works: #include <cst...
63,113,363
63,113,469
Runtime error: signed integer overflow: 2 * 2147483647 cannot be represented in type 'int'
I am trying to run the following code: int across(vector<int> &nums, int l , int m, int h){ int i = l, j = m +1; int count = 0; unsigned long long int n; unsigned long long int prev; while(i <= m && j <=h){ n = 2* nums[j]; prev = nums[...
In C++, the type of the left-hand side of an assignment (=) does not affect the type of right-hand side. n = 2* nums[j]; Here the expression is 2* nums[j], and since both 2 and nums[j] are of type int, the result is still of type int. The type of n plays no role. Cast at least one of the arguments to long long ...
63,113,374
63,113,754
C++ Vector Initialization List vs. Assignment
In C++ what is the technical difference between following two ways of initializing a vector? vector<int> v_1 {0, 1, 2}; vector<int> v_2 = {3, 4, 5}; The first one is an initialization list. What is the second one? I appreciate hints on correct terminology and referring to documentation and different standard...
vector<int> v_1 {0, 1, 2}; This is direct-list-initialization, a form of direct-initialization. An object v_1 is constructed with the provided values. vector<int> v_2 = {3, 4, 5}; This is copy-list-initialization. In this case there is no difference from direct-list-initialization. There is still a minor sema...
63,113,517
63,113,567
How to separate while loops?
I tried to make a loop within the range of 3 numbers, but then on my 2nd statement it would already have updated the first variable due to the 1st while statement. Is there a way to separate the two statements so that it would take the digit of the inputted number instead of the updated one? cin >> num1 >> num2 >> num3...
Save it in a temporary: cin >> num1 >> num2 >> num3; const auto t0 = num1; while(num1 <= num2){ cout << num1 << " "; num1++; } cout << endl; num1 = t0; while(num1 <= num3){ if(num1%2 != 0){ cout << num1 << " "; } num1++; }
63,114,181
63,114,309
Get std::variant types at compile time
Suppose we have defined somewhere: using mytype_t = std::variant<int, float>; I want to retrieve all possible types that coud be stored by mytype_t. I have checked the reference. There is no member types defined that I can use (something like: mytype_t::value_types). I am trying to do something like this: using myvect...
You do not need a special member for that, because the information is all right there in the type: #include <variant> #include <iostream> #include <vector> #include <type_traits> template <typename T> struct foo; template <typename...V> struct foo< std::variant<V...>> { using type = std::variant< std::vector<V> ...
63,114,237
63,151,239
C++ - No matching function for call to 'getaddrinfo'
Here is my code: const char portNum = TCP_PORT; const unsigned int backLog = 8; // number of connections allowed on the incoming queue addrinfo hints, *res, *p; // we need 2 pointers, res to hold and p to iterate over memset(&hints, 0, sizeof(hints)); // for more explanation, man socket hints.ai_family = AF_UN...
The getaddrinfo() function requires a const char *service second argument. If this 'service' is a port number, then it should be specified in string form. Thus, you should define your TCP_PORT macro as follows: #define TCP_PORT "8080" Then, you will also need to change the type of the portnum variable to be a pointer ...
63,114,275
63,114,529
OpenMP reduction clause does not work for a big long int for loop count
There is a following piece of code: #include <iostream> #include <fstream> #include <limits> #include <chrono> #include <omp.h> const long int N=1000000000L; class Counter { public: Counter():n(0),N(0){} void operator()() { if(n==INT_MAX) { #pragma omp atomic update ++N; #pragma omp atomic wri...
You have a race condition in the check: if(n==INT_MAX) { // Nothing prevents another thread to read n here and enter the same branch #pragma omp atomic update ++N; #pragma omp atomic write n=1; } Hence, two threads may both decide to reset n and increment N concurrently. Besides that, you would als...
63,114,587
63,116,427
C++ make placement new aligned storage initializable using constexpr
This is a really important question to me as it's a bottleneck right now and I'm trying to investigate possible ways to solve my problem: I need to constexpr construct a std::function-like class that I am using that is quite simple. However, it's using aligned storage so that we can configure a pointer-sized number of ...
Using C++20 and if you increased the constraint on the type Callable to be trivially_copyable you could use bit_cast. You would also have to define a union containing a member of type aligned_storage <size, alignment> for all possible object size. Unfortunately, I don't think there is a constexpr implementation of bit_...
63,114,625
63,115,074
Macro to define javascript constructor keyword
I have many classes which are like this: struct A_Insert { Data &d; A_Insert(d) : d(d){} // ... } struct A_Query { Data &d; A_Query(d) : d(d){} // ... } struct B_Insert { Data &d; B_Insert(d) : d(d){} // ... } struct B_Query { Data &d; B_Query(d) : d(d){} // ... } ...
Inheritance: struct DataReference { Data &d; DataReference(Data& d) : d(d) {} }; struct A_Insert : DataReference { using DataReference::DataReference; ... };
63,114,668
63,114,808
C++ function for container
I want to write a C++ function like: template <T<int> > void printIntegers(T<int> ints) { for (int i: ints) printf("%d ", i); } Because I want T<int> to be either vector<int> or list<int> or any other STL container. How should I write the template parameter?
Don't overthink it. template <typename Container> void printIntegers(const Container& container) { static_assert(std::is_same_v<typename Container::value_type, int>); for (const auto& el : container) { printf("%d ", el); } } Or even just: template <typename Container> void printThings(const...
63,114,889
63,114,913
When are local static objects created?
Chapter 6.1.1 of the book C++ Primer says the following: Each local static object is initialized before the first time execution passes through the object’s definition. Local statics are not destroyed when a function ends; they are destroyed when the program terminates. To check this, I ran the following code: #inclu...
When are local static objects created? As your book says: "before the first time execution passes through the object’s definition". More precisely, the standard's wording is: Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control p...
63,115,479
63,118,820
How can I make a sizer expand to the whole wxNotebook page?
I have a wxNotebook with two added pages. Each page uses a wxFlexGridSizer to manage the various widgets on each page. The first page has three columns of widgets, the second page only two. The first page is wider than the second page. The notebook is resized to the size of its widest page (the first one). However, on ...
You just need to make 2 small changes. First with the flex grid sizer on the second page you need to call AddGrowableCol(1). This means that the second column can expand. (The indicies start at 0, so column 1 is the second column.) Second, you need to use slightly different sizer flags when adding the spin control d...
63,115,694
63,115,830
C++20 [[no_unique_address]]'s bug in GCC?
C++20 introduces the new attribute: [[no_unique_address]] which indicates that the data member need not have an address distinct from all other non-static data members of its class. So I try to use this new attribute to implement my own vector which make the allocator as the class member: #include <memory> template <t...
So is this a GCC bug? Possibly. internal compiler error doesn't imply a bug in the compiled code. Whether the code is correct or not, ICE can be a compiler bug, or it can be a broken installation.
63,115,808
63,116,323
MISRA 5-2-1 rule requires postfix-expressions?
The rule 5-2-1 in MISRA-2008 states that Each operand of a logical && or || shall be a postfix-expression. Exception: Where an expression consists of either a sequence of only logical && or a sequence of only logical ||, extra parentheses are not required. And here are the examples, right from the document itself: if...
All primary-expressions are postfix-expressions. In these examples, the only postfix-expression that's not a primary-expression is is_odd(y). The grammar for postfix-expressions is: postfix-expression: primary-expression postfix-expression [ expr-or-braced-init-list ] postfix-expression ( expression-listopt ) simple-...
63,115,900
63,116,423
c++20 ranges view to vector
Now that the C++20 ranges implementation is actually here and released under GCC 10.2, I would like to know how to convert a ranges view back to an actual container, like a vector. I've found this question ( Range view to std::vector ) that asked the same thing for the pre-release version but I would like to know if si...
Easiest thing to do would be to use range-v3, which has a conversion operator exactly for this. From the examples: using namespace ranges; auto vi = views::for_each(views::ints(1, 10), [](int i) { return yield_from(views::repeat_n(i, i)); }) | to<std::vector>(); // vi == {1,2,2,3,3,3,4,4,4,4,5,5,5,5,5...
63,116,021
63,116,718
Are OpenGL functions actually context-specific?
I know that I must pass glfwGetProcAddress function to gladLoadGLLoader function after context was initialized. GLFW documentation says that this function returns the address of the specified function for the CURRENT context. Based on this information, if I want to draw something on another context, I must type glfwMak...
Technically yes: function pointers retrieved from an OpenGL context are valid only for that specific context. However, for most practical purposes, you can ignore this. If two contexts can share objects, then they almost certainly share function pointers. If you want to account for those cases where function pointers c...
63,116,165
63,116,445
Qudpsocket readyread() don't work in try-catch block
I wanna get message by UDP protocol. If I create object to work with QUdpsocket in try-catch block, signal readyread() don't work. But if I created UDPworker's object out of try-catch block - all OK. What I did uncorrect in exceptions and Qt combo? Is it about implementation QUdpsocket? main.cpp #include "mainwindow.h"...
You are creating MyUDP inside a try block, not catching any error an getting out of the try/catch scope, so MyUDP is begin destroyed: try { MyUDP m_UDP; // Created in the stack, valid only inside the try block } catch (...) { } //m_UDP is already destroyed and undefined here I should add that you are using QO...
63,116,185
63,117,283
Using boost geometry to find intersection of line segments
I am trying to use the boost geometry method intersects with my own point class, successfully registered with the boost geometry library. The boost documentation ( https://www.boost.org/doc/libs/1_73_0/libs/geometry/doc/html/geometry/reference/algorithms/intersection/intersection_3.html ) says that I can use a vector o...
You're asking "whether a intersects b". However, your third argument suggests you wanted instead to ask for "the intersection": Live On Coliru #include <boost/geometry.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <boost/geometry/geometries/segment.hpp> #include <iostream> namespace bg = boost:...
63,116,250
63,116,687
A issue about the order of explicit instantiation and explicit specialization
#include <iostream> template<typename T> void func(T){} template void func<int>(int); template<> void func<int>(int){ } int main(){ } Consider the above code, Clang and GCC both complain such code is ill-formed, as the below outcome noted. explicit specialization of 'func<int>' after instantiation However, I only...
It's a bit fragmented, but the relevant rule here is [temp.spec]/5 For a given template and a given set of template-arguments, [...] both an explicit instantiation and a declaration of an explicit specialization shall not appear in a program unless the explicit instantiation follows a declaration of the explicit spec...
63,116,519
63,116,581
Self modifying vector of std::function segfault
I'm trying to define a vector of function. When the functions are called they can add or remove items from the vector. Ultra simplified it's something like the code below. #include <functional> #include <vector> int main() { using F = std::function<void()>; std::vector<F> v; v.push_back([&v]{ puts(...
but I still don't understand what is wrong with that code and why it doesn't/shouldn't work. When the vector reallocates, the objects stored inside it are destroyed after having been copied. So, lambda that is being executed has been destroyed, and when you attempt to access the captured reference v of the destroyed ...
63,116,725
63,117,282
C++: Recursive locks - are there any drawbacks?
The background: I have a few threads that should access shared data. One of the threads might lock a Mutex, and within the mutual exclusion block, some functions (of the same thread) might call the very same lock again. -I don't want to create many Mutexes -I don't want to give up locking (obviously) -I'd rather not ch...
are there any drawbacks? Slight performance penalty - measure if you care. any other way to solve You could give funcB a bool should_lock = true argument, or lots of variations on the theme, e.g. have one overload that locks a mutex then calls another overload that expects a reference to an already locked mutex (pe...
63,117,498
63,117,702
Implement assert without preprocessor in C++20
C++ knows assert() which allows runtime checks that compile to nothing in dependence of NDEBUG. I would like to replace that macro using compiler-code and avoiding the preprocessor. I need to do the following: Break or terminate if expressions evaluates to false Log the code line where the assert is called Discard the...
I suppose you are talking about the case when you disabled debugging and you want the function to be a noop. I see 2 options: You can use a macro. Macros can be misused, but they have their place and "passing an expression" without evaluating it is a case for a macro. Alternatively, pass a callable that returns the res...
63,117,583
63,126,634
Crosscompilation use boost from mounted directory
I am trying to cross compile a ROS package for a Jetson nano (aarch64) using my x86_64 PC. I am using the toolchain provided by nvidia (GCC Tool Chain for 64-bit BSP). I have been following this article for guidance As the compiler needs boost binaries from the aarch64 system, I have mounted the nano's /usr/include/boo...
Got it solved by mounting the whole /usr/include instead of /usr/include/boost. Compiler might have needed other files/ directories in /usr/include to look up Boost . ├── gcc-4.8.5-aarch64 #<cross compiler> │ └── install │ ├── aarch64-unknown-linux-gnu │ ... ├── opt #<ROS source files f...
63,118,147
63,118,329
Using typedef types in definition
I have a class as follows, template<size_t N> class A { typedef int(*ARRAY)[N]; array getArray(); ARRAY array; }; Then how can I use the type ARRAY in the definition? I have tried this template<size_t N> ARRAY A<N>::getArray() { return array; } But, it tells me that ARRAY is not defined.
ARRAY is depended name, therefor you need to use the typename keyword before it, outside the class scope. template<size_t N> typename A<N>::ARRAY A<N>::getArray() //^^^^^^^^^^^^^ { return array; } or using trailing return template<size_t N> auto A<N>::getArray() -> ARRAY // ^^^^^^^^^^^^^ { return...
63,118,477
63,118,541
What does 5%10/2 mean?
5%10/2 I know that the % sign shows the remainder, so the operation should give 2.5 because the remainder of 5%10 is 5. So then 5/2 is 2.5. But it gives me 2.
In C and C++, there's a difference between integer and floating-point division. When you divide 2 integer values, you get the result rounded down, so you get 2.5 instead of 2. If you want 2.5, you should cast one of the operands to a float or just use a float/double literal: std::cout << ((double) (5 % 10) / 2) << std:...
63,118,550
63,119,255
What does boost::geometry::intersection return
The documentation for boost::geometry::intersection( https://www.boost.org/doc/libs/1_73_0/libs/geometry/doc/html/geometry/reference/algorithms/intersection/intersection_3.html ) says the function returns a bool. However the docs do NOT say what the return value indicates. I guessed it would return true if an interse...
The return value is true indicating no errors. E.g. deep down the call chain: template <typename RobustPolicy, typename GeometryOut, typename Strategy> static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, RobustPolicy const& robust_policy, GeometryOut& geometry_out, ...
63,118,632
63,119,234
how to calculate the difference at the 3 digit after decimal point
I'm trying to check if a given number is 2 or 3 digit after the decimal point, I tried a few methods but non but one was good: the first one is - bool Is2DecimalPlaces(double num) { double value = num * 100; auto ans = (value == std::floor(value)); return ans; } but on input 10.12 and 10.13 it gives...
As mentioned in the first comments, due to accuracy reasons you can't rely on floating point arithmetic to calculate the number of decimals of a floating point number. Therefore, I'd advise you to work in another way (I assume those numbers are coming from some source, be it a database, a file or a user input)? Then us...
63,118,774
63,118,852
Using --a vs a-1 in recursion
I was trying to calculate a factorial using recursion like this: #include <iostream> using namespace std; int factorial(int a) { if(a == 0) { return 1; } return a*factorial(--a); } int main() { int a; cin >> a; cout << factorial(a) << endl; return 0; } and it wasn't workin...
In your first code sample, the following line has undefined behaviour: return a * factorial(--a); This is because there is nothing in the C++ Standard that dictates whether or not the 'old' or 'new' (decremented) value of a is used to multiply the return value of the factorial function. Compiling with clang-cl gives t...
63,118,830
63,119,122
Check if variable is equal to any one of these values
In c++, is there a way to see if a variable is equal to one of the values? Right now I have to do if (fExt == "zip" | fExt == "7z" | fExt == "gz" | fExt == "tar") { //do something } However, is there a more efficient way?
Example with a set: if (std::set<std::string>{"zip", "7z", "gz", "tar"}.count(fExt)) { std::cerr << "yes" << std::endl; } Note that std::set::count() returns 0 or 1 and provides effectively the same functionality as std::set::contains() which unfortunately is only introduced in C++20. This is not too bad as it ma...
63,118,847
63,118,905
How is an int function able to return long long variable?
int reverse(int x) { if(x==0) return 0; int y = abs(x); long long result = 0; while(y > 0) { result *= 10; result += y % 10; y /= 10; } if(result > INT_MAX || result < INT_MIN) return 0; if(x<0) { ...
The return value will silently be truncated if the value exceeds the range of int. Your compiler likely has warnings you can enable that tells you this. You should enable them (and also ask it to turn warnings into errors IMHO).
63,119,302
63,120,083
Why do separate arrive and wait exist in C++20 barrier?
C++20 std::barrier has arrive_and_wait method, which is what pretty much every synchronization barrier implementation has. But it also has separate arrive and wait. Why do these functions exist?
OK, so you've got a bunch of threads that have to do some kind of synchronized tasks. These tasks are grouped into phases: the tasks from one phase will use data produced by tasks from a previous phase, and all previous phase work must be done before any next-phase work can start. Let us call any work that requires dat...
63,119,421
63,119,477
How I can get a pointer to the key in an unordered_map when I am iterating over it?
coming from a C mindset I have very little experience with the c++ standard library and I wonder if anyone knows how I can get a pointer to the key in an unordered_map when I am iterating over it? To be more specific, I am trying to do something like this: std::unordered_map<std::string, int> my_map; std::string *the_s...
std::unordered_map stores key as const, its element's type is std::pair<const Key, T>; the_string_i_care_about should be pointer to const too. e.g. std::unordered_map<std::string, int> my_map; const std::string *the_string_i_care_about; for(auto& itr : my_map) { if (itr.first == "pick me!" ) { the_string_i_...
63,120,078
63,160,873
How to adjust Window Rectangle based on determined size of Client Rectangle
I have a window that I know the content size determined and I want it to be centered and also size will change when a menu option is picked. I am confused about how should I use the GetWindowRect(), AdjustWindowRect() and MoveWindow() functions together even though I read the documentation, if more experienced members...
After @IInspectable's comment. I created the below method which does both centering and resizing properly for various client sizes of menu options BOOL MainWindow::AdjustWindow() { //use required fields to set rectangle of client area RECT clientToWindowRect; clientToWindowRect.left = GetScreenCenter().x - ...
63,120,091
63,139,313
Unable to assign value to global variable through function (shared library injection on Linux)
I am messing with shared library injection and managed to make it work. But it didn't take long until the first issue showed up. If you take a look at the following code blocks, you'll see that the only difference between them is that on the first one, the value returned from the "test" function is assigned to a local ...
As pointed by yugr, "C++ global constructors run after C constructors (i.e. functions marked with attribute((constructor))". With that in mind, I thought about a way around this: creating a C thread that would run on the background AFTER the C++ stuff loaded using PThread. Then I did this to test out: //main.cpp (share...
63,120,299
63,121,937
What is the value for white in this png filter?
I have this short code in C++ : png_set_filler(png, 0xFF, PNG_FILLER_AFTER); This colored the transparent pixels in black. I think that 0xFF means black. What is the value for white ? Thanks
That function takes packed (alpha-less RGB) values and adds an alpha channel. png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE); The filler is the value to put in the unpacked alpha channel. The final param is either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, which places the filled channel before or after the RGB values...
63,120,330
63,120,830
Problem with std::uniform_real_distribution<T> and std::numeric_limits<T>::max() for T == long double under Valgrind
I have problem with following code: #include <cassert> #include <limits> #include <random> int main() { using T = long double; std::mt19937 engine{ std::random_device{}() }; const auto max = std::numeric_limits<T>::max(); const auto res = std::uniform_real_distribution<T>(0., max)(engine); assert(res < max);...
The problem here is that Valgrind doesn't fully support long double. The manual reads: Valgrind has the following limitations in its implementation of x86/AMD64 floating point relative to IEEE754. There is no support for 80 bit arithmetic. Internally, Valgrind represents all such "long double" numbers in 64 bits, and ...
63,120,346
63,120,418
Using lambdas in local scope in c++
Is it OK to declare lambdas in local scope like this: // reference to method is just a call back function. void(*referenceToSomeMethod)(); // store call back function void foo(void(*pointerToMethod)()) { referenceToSomeMethod = pointerToMethod; // save reference to method } int main() { referenceToSomeM...
Lambdas with empty brackets are equivalent with function pointers and will be copied by value in the same way. Answer yes.
63,120,441
63,120,697
pass array argument to main function index start at 1 c++
In "Accelerated C++: Practical Programming by Example", it says Now that we understand pointers and character arrays, we can understand how to pass arguments to the main function. Most operating systems provide a way to pass a sequence of character strings to main as an argument, if the main function is willing to acce...
The value of argc cannot be negative, but it can be 0, which means no arguments were passed to the program. However, from the reference If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (ntmbss) ([multibyte.st...
63,120,505
63,121,302
why building a set from vector is O(N)
As we know that set is implemented using red-black trees so inserting an element will be a task of O(log N) complexity. But if we are given a vector of n distinct integer so making a set out of it should by NlogN task. But in many places, I found it is given as O(N). Can someone please help me to resolve this. Thanks i...
If the vector is already sorted, then constructing the set is indeed O(N) (but in general not!). From cppreference: template< class InputIt > set( InputIt first, InputIt last, const Compare& comp = Compare(), const Allocator& alloc = Allocator() ); Range constructor. Constructs the container with the co...
63,120,680
63,123,040
How to lock multiple locks where some are shared and some are not in C++
Let's suppose I have some threadsafe class. It uses a std::shared_mutex for protection against concurrent access. Read only operations use a std::shared_lock, while write operations use std::scoped_lock. Now, in the case of the copy assignment operator both the assignee's and the object's being assigned mutexes must be...
In very same way you should be using function std::lock for multiple mutexes. Let me give you an example: std::mutex m; std::shared_mutex sm; std::unique_lock ul(m,std::defer_lock); std::shared_lock sl(sm,std::defer_lock); std::lock(ul,sl); Function std::lock simply applies try_lock()/unlock() until it ...
63,121,375
63,122,077
Manage HTTP response (uint_8 decimal vector) and use http parser to read JSON values
I am working in Simulink on a TCP connection between client (my computer) and server. Through standard Ethernet blocks, I send an HTTP request like the following: GET /status HTTP/1.1 Host:... Accept: application/json To send it, I convert it with the uint8('GET /status...') command. The server responds, always with a...
I used https://github.com/nlohmann/json. Very easy to use library. Please note that the capacity of the message body in boost library is limited to 8k. I had to write my own handlers (which in the end came out faster and more reliable). Yes, a little presumptuous, but I threw out all the extra checks and other heavy th...
63,121,776
63,121,915
Simplest syntax for string interpolation in c++
I'm used to easy-to-read syntax for string interpolation like this in c# or JavaScript, so when I started learning c++ I expected that it will have a similar feature, but when googling for string interpolation in c++ I couldn't find anything like that. In c# strings are interpolated like this: $"My variable has value {...
From c++20 you can use the <format> header to do something like this: auto s = std::format("My variable has value {}", myVariable); which is quite similar to how it's done in c# or JavaScript.
63,122,031
63,122,168
Safe to use object constructed earlier in a thread
Suppose my code is like the following: struct Foo { Foo() : x(10) {} int x_; } void WillRunInThread(const Foo* f) { cout << "f.x_ is: " << f->x_ << endl; } struct Baz { Baz() : foo_(), t_(&WillRunInThread, &foo_) {} Foo foo_; std::thread t_; } int main(int argc, char** argv) { Baz b; b.t_.join(); } ...
It's a mistake to think in terms of implementation details like "this variable may be stored in a register" or "the compiler may want to reorder these instructions". Stick to what the standard tells you. There is a synchronization point when a thread starts (C++17 [thread.thread.constr]/6): The completion of the invoc...
63,122,084
63,122,119
Get type of a std::variant member at a given index during compile time
I have defined the following variant: std::variant<int, bool, MyType, int> myVar; The type of the member at index 2 is MyType. How to get this during compile time? (so that I can use it in a constexpr context etc..)
Use std::variant_alternative Provides compile-time indexed access to the types of the alternatives of the possibly cv-qualified variant, combining cv-qualifications of the variant (if any) with the cv-qualifications of the alternative. using T = std::variant_alternative_t<2, decltype(myVar)>;
63,123,192
63,123,262
Pass inherited arguments to base class constructor, then do something in derived class constructor
Consider the following: I derive a class Child from another class Parent. Parent has a ton of overloaded constructors. The Child class does not need any more parameters for construction. But once the base class constructor has been called, I want to do some more stuff during object construction. So my question is: Usin...
One way you could do this is to make a variadic template constructor in the derived class that passes all of its arguments to the base class. Then you can do whatever additional stuff you want in the body of that constructor. That would look like struct Base { Base (int) {} Base(int, int) {} //... }; str...
63,123,206
63,123,268
While loop with inner while loop: O(n) or O(n^2)?
#include <unordered_map> using namespace std; int lengthOfLongestSubstring(string s) { unordered_map<char, int> ht; int max = 0; int i = 0; int j = 0; while (i < s.size() && j < s.size()) { if (ht.find(s...
It's: Strictly speaking: O(2n), as in the worst case, you iterate two times of the size of input; Speaking in the Asymptotic Language: O(n), because constant factor is disregarded.
63,123,355
63,123,424
Perfect forwarding with a specific type
When writing a threadsafe std::stack wrapper I made the following two overloads for push: void push(const value_type& value) { auto guard = std::scoped_lock{_mutex}; _stack.push(value); _cv.notify_one(); } void push(value_type&& value) { auto guard = std::scoped_lock{_mutex}; _stack.push(std::move(...
You can assert it: template<typename T> void push(T&& value) { static_assert(is_same_v<remove_reference_t<T>, value_type>); // ... } You could alternatively use is_convertible instead of is_same so it works more naturally.
63,123,373
63,123,518
What is a noop coroutine?
The C++20 standard defines a "noop coroutine" in [coroutine.noop]. What is it? And how is it different from a function whose body is { co_return; }? UPDATE Thank you for the links to the proposal and to the standard. To summarize from these references, a "noop coroutine" is one for which the resume() (or operator()) an...
This was proposed here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0913r1.html Basically, the idea is that Having such a coroutine handle allows library writer to perform either symmetric or asymmetric control transfer based on runtime considerations. Following code illustrates this idea (from the same ...
63,123,631
63,123,852
C++ Templated function specialization with template
I have a templated function meant to work with STL containers. However, I'd like to specialize this function for a templated class. How might I go about doing this? I'm stuck on C++11. Edit: Updated code example. It appears to work when F is a POD like int, but is broken in the below code example where F is a class. #i...
You can't partially specialize a template function. But your overload should works. I've modified your MyClass class to make it compile but, in the following example, the overload version is in charge. #include <iostream> template <typename C, typename F> struct MyClass { template <typename ... Ts> MyClass (Ts ...
63,123,839
63,257,089
C++ Class Inheritance, Undefined Reference
I'm creating a class hierarchy of two dimensional shapes. The base class is a Quadrilateral, Trapezoid and Parallelogram inherit Quadrilateral, Rectangle inherits Parallelogram, and Square inherits Rectangle. I'm attempting to test my classes, so I can correct any errors I find, but I'm receiving a compiling error. Thi...
The issue here was with the compiling command given. The -o flag allows you to name the outputted executable. Because you didn't prove a name, it is taking the first file provided in *.o and overwriting it, using it as the file name. Because it was overwritten, it breaks the compilation of the other files. The solution...
63,123,891
63,124,090
Disable Copy constructor of template class
How can I disable the copy constructor of a template class. E.g.: template<typename T> struct X { T property; constexpr X(const T property): property(property) { } friend std::ostream& operator<<(std::ostream& out, const X& x) { return out << "{ " << x.property << " }"; } }; The Problem: If I ...
You can use a template helper function template<typename T> X<T> helper(const T& x) { return x; // This will invoke the construtor } then when using helper(x1); the type T will be correctly found to be X<int>.
63,124,120
63,124,153
what is difference between passing by reference and address in array?
What is the difference between passing by reference and passing by address (using pointer) notation? Is int arr[] = int* arr ?? I have added three samples of codes, I think the first 2 samples are passing by address and the last one is passing by reference. void fun(int *arr, unsigned int n) { int i; for (i=...
is int arr[] = int* arr ?? In short: In a function parameter declaration: Yes. Otherwise: No. Explanation: int[] is an array of unknown bound of integers. int* is a pointer to an integer. A function parameter is never an array. Any function parameter declared to be an array will be adjusted to be a pointer to elem...
63,124,275
63,124,466
How to implement split function to split words from a line?
I would like to implement a function, that takes string as a line of input (via getline()) and separate (split) words in a vector. I have tried this: vector<string> split(const string &s) { vector<string> ret; int j = 0, i = 0; // j=="start word boundary", i=="end word boundary" while (i != s.size()) { ...
You have a typo here: if (!i) { ret.push_back(s.substr(j, i - j)); } You are only adding a substring if the end index is 0, but this means you never add a substring to the vector. Instead, you need to add a substring if the end index is not 0: if (i) // if (i != 0) { ret.push_back(s.substr(j, i - j)); } Here'...
63,124,443
63,178,579
boost::interprocess::interprocess_condition::timed_wait() compiler error
I'm trying to create some objects in shared memory (which will be a future question) but for now I've getting a compiler error (boost 1.53.0 using g++ 4.8.5 on RHEL 7.8) that I can't figure out. Event.h #include <boost/interprocess/sync/interprocess_condition.hpp> #include <boost/interprocess/sync/interprocess_mutex.hp...
I added a scoped_lock inside the do...while() replacing the Mutex in the timed_wait() and wait() calls. This solved my compiler issues.
63,124,971
63,125,038
Unrolling nested loops c++
I'm trying to unroll a nested loop that stores data in a 2D dynamic memory allocation in C++. Although, I'm not quite sure how to do it. Here is my original loop before unrolling: int steps[1]; Ipp32f* vectx = ippiMalloc_32f_C1(size0, size1, &(steps[0])); for (int i = 0; i < size0; i++){ for (int j = 0; j < size...
You are not taking in account operator precedence *((Ipp32f*)((Ipp8u*)vectx + (steps[0] * j + 1) + (sizeof(Ipp32f) * i+1))) = datax[i+1]; ^^^^^^--here ^^^--and here you should add () *((Ipp32f*)((Ipp8u*)vectx + (steps[0] * (j + 1)) + (sizeof(Ipp32f) * (i+1)))) = da...
63,125,202
63,129,196
Can I allow tkinter's mainloop() and GLUT's glutMainLoop() run concurrently?
I am writing a python tkinter application that interfaces with a C++ library that I am also writing. The C++ library contains a class that wraps some of GLUT's functions. My main function (python) looks something like this: import sys import tkinter as tk import myCustomCppLibrary #This sets up the GLUT bindings. myCu...
You can't mix GLUT with other windowing frameworks. At least not without going through a lot of pain. But one has to wonder: What is there in GLUT that you must use it? With a little extra module you can create an OpenGL context within TkInter Tkinter OpenGL context in Python
63,125,528
63,125,672
std::stoull but with string_view
Is there a std::stoull which takes a basic_string_view? I don't want to construct a string just to call std::stoull, especially since it takes it by const &. If none exists, what is an efficient way to convert a std::basic_string_view to unsigned long long?
If you're looking for more efficiency, C++17 introduced lower-level conversions in <charconv> (live example): #include <charconv> #include <iostream> #include <string_view> using namespace std::literals; int main() { const auto str = "2048"sv; unsigned long long result; auto [ptr, err] = std::from_chars(...
63,125,808
63,125,895
Why when enter two char[] , the first one will become the same as the last one?
using namespace std; int main() { char b[50]; cin >> b; char* a[50]; a[0] = b; cin >> b; cout << endl; a[1] = b; cout << a[0] << "\t" << a[1] << endl; cout << strlen(a[0])<<"\t"<<strlen(a[1]) << endl; } input and output abc 123456 123456 123456 6 6
char* a[50] is an array of pointers to strings. char b[50] is a string (an array of characters) So this char b[50] = "x"; char* a[50]; a[0] = b; a[1] = b; Is the same as char b[50] = "x"; char* a0 = b; char* a1 = b; In both cases, both pointers point to the same string (b). If you change what is in that string, then...
63,125,871
63,132,772
Translate CLI ImageMagick to Magick++: threshold and depth
I am converting a system call to Magick++ in my code, but I am having some trouble converting the threshold and depth. The original: convert /foo/bar.ppm -crop WxH+X+Y -threshold 50% -depth 1 /foo/out.ppm My current C++ version is: Magick::InitializeMagick(*argv); Magick::Image img; img.read("/foo/bar.ppm"); Magick::I...
Mark Setchell's comment is correct. Maigck::Image.threshold's argument must be scaled by the QuantumRange (provided by a C macro definition). temp_img.threshold(QuantumRange * 0.5); This scaling is expected for most arguments that are a percent ratio.
63,125,890
63,126,057
(C++): Problem storing and accessing user login data
This is simplification of my classes (a "gang-management" game logic): class Player { private: string nickname, password; Gang my_gang; //this player's gang class instance public: //generic functions... } //PlayerContainer is a database of all possible players, each player has a specific gang assigned class...
list<Player>::iterator it; for (it = player_list.begin(); it != player_list.end(); ++it) { if (it->get_nickname() == nick && it->get_password() == pass) { return true; } else { //breaks the loop and lets the function return false; } ...
63,126,062
63,126,111
C++ "undefined reference" error when working with custom header file
I am working with my own custom header file for the first time in C++. The goal of this program is to create a dice class that can be used to create an object oriented dice game. When I go to run my program (made of three files (header/class specification file, class implementation file, and finally the application fi...
You should compile both app.cpp and Die.cpp at the same time: g++ app.cpp Die.cpp
63,126,196
63,126,254
How to save a text file directly without using QfileDialog box?
This is my sample UI, the white box is a textbox which will have some items, my main question is that when i click "Save/Refresh" qpushbutton, i want to save all of the qtextbox text into a textfile/sample_name.xml into a designated folder, but i dont wanna go through Qfiledialog box and having to decide/browse a loc...
You will have to provide a static path within the function that listens at your Save button. Your listener function would be of a similar format: void save(){ //assuming content of textbox has been stored in variable 'content' ofstream myfile; myfile.open ("path_to_file", ios::trunc); myfile << content; myfil...
63,126,437
63,129,346
Will checking if the number is even (of course > 2) before checking if it is a prime number increase the performance?
Well, the question explains it all, still I will elaborate with some code. In a nutshell: Which of the 2 codes is better? : Code 1: check for num==2 and num==1 ;) if(num%2) { checkPrime(num) //function definition not needed } else { //not prime } Code 2: check for num==2 and num==1 ;) if(isPrime(num)) { ...
For a simple isPrime() function I use something like the following pseudocode: isPrime(num) // Negatives, 0, 1 are not prime. if (num < 2) return false endif // 2 is the only even prime. if (num MOD 2 == 0) return (num == 2) endif // Try odd divisors. limit = 1 + sqrt(num) for (i <- 3 to li...
63,126,476
63,126,620
How to use std::uniform_int_distribution<T>::param()?
I would like to be able to reset the lower and upper bounds of a std::uniform_int_distribution<T> object after it has been created, and it seems the param function in the class allows this functionality. See https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution/param (2). But it's not clear to me ho...
It's not very clear from the documentation, but here it is: auto d = std::uniform_int_distribution<int>{1, 10}; d.param(std::uniform_int_distribution<int>::param_type{11, 24}); Here's how you can find this information in the docs: std::uniform_int_distribution Member types param_type: the type of the parameter set,...
63,126,844
63,126,951
std::bind not binding to a library `typedef` ed function
I am trying to use std::bind with a library that typedefs function. #include <iostream> #include <string> #include <functional> typedef void (*GDBusReturnFunction) (void* user_data); class Test { void reply(void* user_data) { std::cout << "Hello" << std::endl; return; } void test_reply() {...
The std::bind returns a unspecified type (i.e. a function object of unspecified type), template< class F, class... Args > /*unspecified*/ bind( F&& f, Args&&... args ); //^^^^^^^^^^^^ which can not be copied to a function pointer type. You need to use either std::function or a templated call function. Nevertheless, ...
63,126,903
63,126,989
Reasoning behind calculating the number of sub-arrays with odd sum
I am solving a question on LeetCode.com: Given an array of integers arr. Return the number of sub-arrays with odd sum. As the answer may grow large, the answer must be computed modulo 10^9 + 7. For arr = [1,3,5], the output is 4. One of the highly upvoted solutions is like this: int numOfSubarrays(vector<int>& arr)...
First of all, we need to understand some basic properties of parity. If a is even, then the parity of a + b is the same as the parity of b. If a is odd, then the parity of a + b is the opposite of the parity of b. In the code that you've posted, odd is the number of subarrays ending at the current element which have od...
63,127,061
63,127,083
Overloading operator= for char*
Don't be hard with my first question here. When I use char array this way: char s[50] = "Some string"; it's works. But this way: 2) char* s2 = new char[50]; s2 = "Another string"; Compiler doesn't agree to put const char to char*. A know the way to do it right. And I know how to use string also. But our teacher asks...
The C++ standard does not allow you to overload operators where none of the operands have a class or enumeration type. Therefore, you cannot overload operator= for char* because it is prohibited by the C++ standard. Operator overloading does not allow you to override the behavior of the built-in operator.
63,127,238
63,128,972
How can i pass an element to be able to evaluate within a certain specialization?
I am trying to make a CHIP-8 emulator that generates most of the instructions at compile time. So i have a constexpr array like this: constexpr uint16_t hardCodedROM[] = { 0x8001, 0x8002, 0x8003, 0xA0F0, 0xB0FE }; And I have a specialization for each item of the array like this: template<uint16_t instruction> stru...
If code is always known at compile time, make it a template parameter: template<std::uint16_t code> static void Task() { constexpr unsigned char submask = code & 0x000F; // ... } and then don't forget the template disambiguator: [&]<std::size_t...p>(std::index_sequence<p...>) { (Opcode<(hardCodedROM[p] & 0...
63,127,415
63,132,390
getting include error on external libraries C++ code in Visual Studio on mac os
I am new to c++ programming. coding in visual studio code. I have downloaded PCL library and Eigen library from Homebrew on mac os. both installed successfully. But when I include it library my current script, I always get no such file. Thank you.test.cpp: #include <pcl/visualization/pcl_visualizer.h> also edited c_cp...
See http://https:/stackoverflow.com/questions/9755261/c-include-libraries "C++ include libraries" post by the user "nos" which I believe should solve your issue.
63,127,731
63,127,908
Linux equivalent of Process.Start()
On Windows in C#, I can launch an external program from within my code by calling Process.Start(), which starts the process and returns its ID. This is important because I am not forking my own process, and I might have to kill the process later. I have looked at exec(), fork() and many other things under Linux in C++ ...
The way to start a new process on Linux is by using fork and exec. This you can wrap in your own System class that holds the PID and provides methods to kill the process etc. An example of such a class is QProcess from the Qt library.
63,127,761
63,128,179
Difference between Cygwin and Command prompt when running an c++ application through command line
I have a C++ application that I am trying to run using the Windows command prompt by moving into the application directory and then call appl.exe with some arguments. The application gets launched(not yet closed), but the control returns to the command prompt. Now when I do the same on Cygwin terminal, it waits for the...
Terminals in Windows like CMD and PowerShell launch applications in non-blocking mode (usually called the headless mode, if I'm not wrong. And it holds good for all executable files). There's nothing to bother until your application is running fine. Cygwin, on the contrary, provides a Linux-like functionality, and thus...
63,127,788
63,129,566
QPlainTextEdit display slow performace
I created a special file viewer tool in Qt to display text data around 1-30 MBytes. I used QPlainTextEdit in readonly mode with disabled word wrapping to display the text. I have a 20MByte example file and the call of QPlainTextEdit::setPlainText() takes about 6.5 seconds which is not acceptable by me wanting to use th...
I am not sure how helpful my answer will be (most of it is based on personal experience). Can it be improved with this editor type? You can not improve performance of setPlainText(), but you can try to improve your highlighting mechanism which will result in better performance. QPlainTextEdit::setPlainText() is a sim...
63,127,914
63,138,909
How to send a parameter to QAbstractVideoFilter in qml?
I want to have multiple camera that processing by unique filter and all camera filter have to access to unique Array in memory(should not passing copy of Array to each filter). Do you have any idea? my solution is to send the Array by parameter to QAbstractVideoFilter, but dont know how to do that and how it possible ?...
You will need to reimplement QAbstractVideoFilter::createFilterRunnable, which will return your custom filter class inherited from QVideoFilterRunnable. This allows you to declare and implement any interface, parameters and communication in your class, which will affect video filtering/processing. So, you'll have two o...
63,128,197
63,129,222
How to prevent some action in app using winapi?
I would like to prevent some action in my app using winapi for example I would like to block moving my window app. How can I do this? I try this: if( pWindowsMessage->message == WM_MOVING ) { return 1; } else if(pWindowsMessage->message == WM_MOVE) { return 1; } But it doesn't w...
You can block messages in different areas by handling WM_NCLBUTTONDOWN messages. And According to WM_NCHITTEST,we can handle events in different regions. Here is a sample: #include <Windows.h> #include <cassert> #include <cstdlib> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInsta...
63,129,072
63,129,567
Similar solutions but different answers
I am facing difficulty while solving a problem where we have to check whether a string is a subsequence of another string or not. A man with name M is allowed to marry a woman with name W, only if M is a subsequence of W or W is a subsequence of M. A is said to be a subsequence of B if A can be obtained by deleting som...
Your code produces the wrong result with input AA BAB because it fails to account for the fact that you need to have two A in the second string. You might be able to fix it by changing pos=j; to pos=j+1; but I'm not certain. There really is no similarity between your code and the editoral code however. Even with my sug...
63,129,097
63,130,593
Open GL version 2.1 instead of 4.1 in Mac OS 10.15
I'm new to Mac, so I'm not very conversant with the get arounds with this OS. I wrote a simple Open GL program in Xcode and it ran without issues. However, when I checked the versions using the following code cout<<glGetString(GL_VENDOR)<<endl; cout<<glGetString(GL_RENDERER)<<endl; cout<<glGetString(GL_VERSION)<<endl; ...
GLUT is ancient and doesn't support common macOS features such as HiDPI or mouse scrolling. You probably want to look into using the GLFW library instead (see here for what you need to do for a 4.1 context). However if you really want to use GLUT, you need to add glutInitContextVersion(4, 1); glutInitContextProfile(GLU...
63,129,243
63,130,110
How can I compile and run C++ on Mac using Xcode?
I'm new to C++ and trying to compile and run C++ code to no avail. Please help! Below is a screenshot of my code in Xcode. But Run is not available. I've also tried to compile and run in Atom after installing g++ compiler and got errors. Help!
You need to create new project. In Xcode: Select: "File" / "New" / "Project" (window pops up) Choose "macOS" in top tabs Select "Command line tool" Press "Next" button Provide: "product name", for example "my awesome app" "Organization name" (you can type here your name) "Organization id" (something like reversed hos...
63,129,262
63,130,013
How to change pointer from base to derived class inside a function
I would like to create some kind of factory function, but instead of returning a pointer to a certain class object, I would like to pass a pointer to the base class to a function as an argument. What makes it even more cumbersome, the function accepts the void pointer. Here is the code I have tried. #include <iostream>...
If you do not want run time polymorphism via virtual functions, you can use std::variant instead. This enables you to use unrelated objects without a common base class, it did not need to enable RTTI which means it will fit also for small embedded systems and it still type safe as std::variant keeps the information whi...
63,129,777
63,129,866
LNK1104 cannot open file boost_thread-vc140-mt-gd-1_61.lib
I am using Microsoft Visual Studio Professional 2017, Version 15.9.25 Visual C++ 2017 - 00369-60000-00001-AA984 ASP.NET and Web Tools 2017 - 15.9.04012.0 ASP.NET Core Razor Language Services - 15.8.31590 ASP.NET Web Frameworks and Tools 2017 - 5.2.61435.0 When I compile the project I'm getting: 1>LINK : fatal error LN...
Open the project properties, right click Project in Solution Explorer From the Configuration Properties click on the Platform Toolset and change the setting to Visual Studio 2013 (v120) Click on the OK button. Clean project and rebuild.
63,129,799
63,129,937
remove_if without the need of move and copy semantics
Here is what a typical vector remove-erase operation looks like : auto toErase = std::remove_if(vec.begin(), vec.end(), [val](obj_t const& obj) { return obj.myval == val; } ); // This actually moves objects around ! vec.erase(toErase, vec.end()); This works fine in the majority of cases, but I am faced with the c...
If object is non-movable/copyable how do you expect to rearrange objects in the vector? Vector is a contiguous container - so you cannot erase an element in the middle without shifting the ending. To resolve the issue, either make the object movable/copyable, wrap it in unique_ptr (thus making it movable), or use one o...
63,130,177
63,130,448
How to rotate the object about an angle using qml qt3d (qt)?
I want to rotate the object in the window screen. I am using Qt/QML/Qt3D. I write some code here to add a button in the object window display screen. With the help of this button I could rotate the object in the display screen about (90 and 180) degrees. QML source code: import QtQuick.Controls 2.2 import QtQuick.Dialo...
Here is one example of how to do this in Qt (not Qt3D): https://doc.qt.io/qt-5/qml-qtquick-item.html#rotation-prop Rectangle { color: "red" x: 25; y: 25; width: 50; height: 50 rotation: 30 // ! } Also you can rotate around other axis, here is information about it: https://doc.qt.io/qt-5/qml-qtquick-rotation....