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 |
|---|---|---|---|---|
70,293,642 | 70,293,907 | std::forward through an example | I would like to go over an example using std::forward because sometimes I can make it work and some other times I can’t.
This is the code
void f(int&& int1, int&& int2){
std::cout << "f called!\n";
}
template <class T>
void wrapper(T&& int1, T&& int2){
f(std::forward<T>(int1), std::forward<T>(int2));
}
int m... | The whole problem stems from the forwarding references using same symbols as rvalue ones, but not being the same.
Take the following code:
template<typename T>
void f(T&& t)
{
//whatever
}
In this case T&& is a forwarding reference. It is neither T&& in the sense of rvalue-reference (reference to temporary), nor is it... |
70,294,467 | 70,295,128 | How would one succinctly compare the values of and call the functions of many derived classes' base class? | I have a 2d physics engine that I've been programming in C++ using SFML; I've implemented a rough collision detection system for all SandboxObjects (the base class for every type of physics object), but I have a dilemma.
I plan to have many different derived classes of SandboxObjects, such as Circles, Rects, and so on,... | Your problems are caused by your desire to use a polymorphic approach on non-polymorphic containers.
The advantage of a SandboxObject* m_primaryObjectPointer is that it allows you to treat your objects polymorphicaly: m_primaryObjectPointer -> roughtHitBox() will work regardless of the object's real type being Circle,... |
70,294,901 | 70,302,190 | More efficient way to do binary search in c++? | I am doing a question on Binary Search using C++, but I was wondering if there is a more efficient way to implement it.
My code is as follows:
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) {
return mid;
} else if ... | I am a proponent of binary search without comparison for equality, so that every reduction step takes a single comparison (you perform a single comparison for equality in the end, when the interval has shrunk).
The idea of comparison for equality is that you can terminate the search earlier when the key is found. If th... |
70,294,980 | 70,295,241 | Declaring a random pointer and storing numbers on the next 5 addresses, but its not outputting the numbers from on the addresses, what is the problem? | I wanted to see if it was possible to store numbers on the addresses that come after variable a's address.
//declariing a variable
int a=0;
// declaring a pointer
int *str;
//assigning 'a' adress to the pointer
str =&a;
//storing numbers on next 5 adrdess starting from 'a' adress
for(int i =0; i<5;i++){
cout<<"in... | You are attempting to write to memory that you do not own.
Repeated from comment, if a was an array: int a[5] = {0};, then the expression str = &a[0]; would point to memory your process owns, allowing the follow-on code to populate the elements of the array via eg str[0], str[1]....
I am a new to C++, so forgive the C ... |
70,295,567 | 70,298,375 | How to execute code after application closure? | for a self-built installer I need a way to execute code after closing of an application itself.
Application structure
Main application: The installer is started from it when needed, it closes itself in the process.
Installer: This is also located in the folder of the main application and therefore also accesses all dl... | If your problem are the DLLs shared by the installer and main application, then you can do this: Before you run the installer, your main application can copy all the needed DLLs and the installer EXE from your main application folder to a temporary folder and run it from there. Your installer must then only wait until ... |
70,295,685 | 70,296,467 | What should be preferred, moving or forwarding arguments | Below is simplified example of the templated List, where are two append_move() and append_forward() functions that have the same goal, take the arguments and emplace them in to the container List. The first append_move() function takes arg1 passed by value and then moves it to the emplace_back() function. The second ap... | Forward or move
If T's destructor can't be optimized out and produces visible side-effects, e.g.
struct Loud { ~Loud() { std::cout << "destructor\n"; } };
then
List<Loud> list;
Loud const loud;
list.append_forward(loud);
calls one less destructor than
list.append_move(loud);
because the latter constructs one more ob... |
70,295,725 | 70,295,891 | Explicit instantiation of a deleted function template in C++ | If a function template is marked as deleted, is it allowed to explicitly instantiate it as in the example:
template<class T>
int foo(T) = delete;
template int foo(int);
Clang and GCC allows it, while MSVC prints the error:
error C2280: 'int foo<int>(int)': attempting to reference a deleted function
Demo: https://gcc... | Clang and GCC are right. MSVC is probably referring to the following rule ([dcl.fct.def.delete]/2):
A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.
An explicit instantiation definition is a declaration, so it is allowed.
Although, to be fair, it's not cle... |
70,295,856 | 70,342,990 | How do I run a minimal XLA C++ computation? | I'm using the XLA C++ API, and I've managed to run a simple addition, but I've no idea if I'm doing it right. There seem to be an awful lot of classes that I've not used. Here's my example
auto builder = new XlaBuilder("XlaBuilder");
auto one = ConstantR0(builder, 1);
auto two = ConstantR0(builder, 2);
auto res = one +... | I suspect I didn't actually run that computation through XLA. Here's a different approach based on a sample harness in the XLA source code
XlaComputation computation = res.builder()->Build().ConsumeValueOrDie();
ExecutionProfile profile;
Literal lit = ClientLibrary::LocalClientOrDie()
->ExecuteAndTransfer(computati... |
70,295,942 | 70,296,439 | Is there a way to check if a memory address is between two other addresses? | Let's say that, "hypothetically", I had this code:
//two separate arrays of the same object that for the purposes of this question we will assume are not adjacent in memory
ObjectName* m_objects0 = new ObjectName[10];
ObjectName* m_objects1 = new ObjectName[10];
//and a pointer to a single object
ObjectName* m_pObject... | You can check if a given pointer is (in)equal to any other pointer using the == and != operators.
However, you can check if a given pointer is <(=) or >(=) another pointer only when both pointers are pointing within the same object/array, otherwise the behavior is undefined.
So, while m_pObject is pointing at an elemen... |
70,296,117 | 70,405,942 | How to return an array from C/C++ to Idris? | I want to return an array of arbitrary rank from C/C++ to Idris. I've typed the C++ array as a void*, and correspondingly have an AnyPtr in Idris. In Idris, I've defined such an Array type as a nested Vect:
Shape : {0 rank: Nat} -> Type
Shape = Vect rank Nat
Array : (0 shape : Shape) -> Type
Array [] = Int
Array (d ::... | Note: Assumes the array shape is accessible in Idris.
To get an array
We can return an AnyPtr which points to the beginning of the array, then write a function that recurses over the array getting the elements at each point.
For example (warning - not well tested),
-- we index with Int not Nat because we can't use Nat ... |
70,296,400 | 70,296,598 | c++ initialize char array member of a class with a string | i have a class which has several members of char arrays, and i want to initialize this class with an array of strings which are the values of the char arrays.
class Product {
public:
char productId[20];
char productName[50];
char price[9];
char stock[9];
Product(vector<string> v) : productId(v[0]),... | The code at the bottom will work. But is this a good idea? Probably not. You are better of just storing std::string in your Product type directly:
#include <cassert>
#include <iostream>
#include <vector>
#include <string.h>
class Product {
public:
std::string productId;
...
Product(std::vector<std::string> v) ... |
70,296,480 | 70,296,507 | Compile fails for chained overloaded subscript operator[] | I am trying to create a thin wrapper around some parsing libraries (JSON, YAML, etc.) which will allow me to use a unified syntax regardless of the file-type/parser I am using. I want the wrapper to leverage templating so I don't have to do any dynamic checks at runtime to check which library I am using (this is a part... | Change
const Wrapper<K> operator[](const char* key);
to
const Wrapper<K> operator[](const char* key) const;
or - better still - make const and non-const versions of operator[].
Wrapper<K> operator[](const char* key);
const Wrapper<K> operator[](const char* key) const;
Your current operator[] returns a const object, ... |
70,297,309 | 70,298,305 | QT moc class can not find the original file, despite it being in correct directory | I'm trying to build qt project but I keep getting error about no existing header in moc object moc_SerialPortManager.cpp. I moved with bash to that directory and used cd cmd with the path written in mock object and it leads to the correct directory. Does anybody have a slightest idea how to resolve it? At this point it... | Note that the layout of your repository differs from your local filesystem:
.../debug/.moc/
vs.
.../debug.moc/
Therefore the relative path steps up one level too much and results in a non-existing path.
It is generally considered bad practice to put automatically generated files (i.e. moc files) under version control... |
70,297,417 | 70,297,966 | printing class object using variadic templates | I am trying to understand folding and variadic templates.
I designed a very naive Tuple class. I can create a tuple object, but I would like to print the object. It seems odd that this problem hasn’t been touched almost anywhere (at least I haven’t found any resource so far.
This is the code
#include <iostream>
#includ... | Just use recursion:
// this is the implementation of my own tuple using variadic templates
template<class... T>
class Tuple {};
template<class T, class... Args>
class Tuple<T, Args...> {
private:
T first;
Tuple<Args...> rest;
friend std::ostream& operator<<(std::ostream& out, const Tuple& tuply) {
out << t... |
70,297,524 | 70,297,837 | C++ std::function to take functions with sub class parameter | [Update] Reason for this question:
There are many existing lambdas defined as [](const ChildType1& child), all in a big registry. We want to register new lambdas like [](const ChildType2& child) in the same registry. If we define the function wrapper using Parent, for the many existing lambdas we need to change them to... | Why isn't this allowed ?
This is not allowed by the language because it might lead to inconsistencies.
With your definition of Wrapper, the following code should be legitimate:
Wrapper f;
Parent x;
... // Initialize f with a legitimate function dealing Parent
f(x);
Now imagine two classes:
class Child1: public Par... |
70,297,628 | 70,297,941 | What do the following GCC flags mean? | What do the following GCC flags mean: -D_LNX64i, -I, -ldl -lm. I was asked to compile this file and the Internet is drawing a very scary blank
| GCC flags are described in the documentation of the compiler. The full GCC documentation is available online.
Alternatively, you can use the man g++ command to access the man-page which is an abbreviated manual for the command. This also works for other programs, libraries, shell commands. Man-pages are also available ... |
70,297,668 | 70,297,824 | C++ Iterator for C Linked Lists: to use range-based for loops | I am working with legacy C code and the new code is written in C++. To use the C++ standard library, I wrote a simple Iterator for the legacy LinkedList as shown below after reading through Bjarne Stroustrup's blog post on Adaptation.
My question is:
I want to create another Iterator for another struct say struct Toke... | Iterators are pseudo-pointer types. That means they themselves are regular.
struct Iterator {
LinkedList *current;
LinkedList &c;
};
Here you mix references and pointers. This is a serious anti-pattern, as what does assignment do? There is no sensible answer.
I would remove the c member entirely.
Next you need ... |
70,297,939 | 70,298,049 | Is there a way to convert a function pointer to an std::function without specifying return type and argument type? | I have a function pointer that I need to pass to a function that expects a std::function. The function that takes the std::function is templated and uses the std::function's arguments to deduce a parameter pack, meaning an implicit conversion won't work.
I could construct the std::function myself, but the function bein... | I suggest:
template<typename Func>
auto make_function(Func ptr)
{
return std::function<std::remove_pointer_t<Func>>(ptr);
}
and then simply pass "make_function(my_func)".
(Thanks toRemy Lebeau for suggesting use of "auto")
|
70,298,477 | 70,300,661 | Partial ordering of cv qualifiers vs pointer/reference in template specialization | Say I have a class template with some specializations
template<typename T> struct A {};
template<typename T> struct A<T const> {};
template<typename T> struct A<T &> {};
Which specialization has the precedence, when I instantiate A<const int&>?
I ran a test with GCC, and it picks the int& specialization. I assume this... | X& and const Y can’t ever be decompositions of the same type, since references can’t be const-qualified. (Given using R=T&;, const R is the same type as R, but that doesn’t mean that it has that qualifier to match anything.) As such, no ordering is needed, since the two specializations are disjoint.
|
70,299,233 | 70,301,150 | How to do a task in background of c++ code without changing the runtime | I was trying to create a bank system that has features for credit,deposit,transaction history etc. I wanted to add interest rate as well so I was thinking of adding it in after 10 seconds of delay but When I am using delay(like sleep()function). My whole program is delayed by 10 seconds. Is there a way for interest to ... | If you need just single task to be run then there exists std::async, which allows to run a task (function call) in a separate thread.
As you need to delay this task then just use std::sleep_for or std::sleep_until to add extra delay within async call. sleep_for shall be used if you want to wait for certain amount of se... |
70,299,281 | 70,299,550 | Binary tree doesn't inserting | I have to write a collection - binary tree, using polymorphism. Its' roots must be objects of abstract class. I have class Node and Btree, but function "add" doesn't work correct. What am I doing wrong..? Help pls
class Node {
public:
Node() {
o = nullptr;
left = nullptr;
right = nullptr;
... | One problem is here:
void insertNode(Node *node, Node *elem) {
if (node == nullptr) node = elem;
else {
...
}
}
The first time you try to add a node, node is equal to root, and so it is equal to nullptr. So this function sets node equal to elem, and then quits. But node is a local variable, it belongs to the f... |
70,299,385 | 70,299,772 | Undefined symbols for architecture arm64 in MacOS | Below error occurs while I was writing two functions xxxx as part of uni work. The IDE I'm using is Visual Studio Code.
The problem was that when I tried to compile a single file in the folder code/myIO, it threw an error:
(I've replaced the folder's path with ($). I promise the problem wasn't there)
cd ($) && clang++ ... | You have a declaration without a definition.
utilities.h has:
class _Tp {
// [...]
public:
// [...]
static const int INT = 1, SHORT = 2, LONG = 3, LONGLONG = 4,
FLOAT = 10, DOUBLE = 11, LONGDOUBLE = 12;
That declares _Tp::INT etc. with initializers, but does not define them. If you ODR-use these values the... |
70,299,514 | 70,300,894 | Why is the compiler looking for a copy assignment operator when the move assignment operator is needed? | #include <utility>
class A {
int* ptr;
public:
A() {
ptr = new int[10];
}
A(A&& rhs) {
this->ptr = rhs.ptr;
rhs.ptr = nullptr;
}
~A() {
if (ptr) delete[] ptr;
}
};
int main() {
A a1;
A a2;
a2 = std::move(a1);
}
GCC 11 complains that the copy a... | Your explanation is not exactly correct. The compiler wasn't looking particularly for operator=(A&&). It was simply looking for any operator= that could be called for that assignment.
Now, the move assignment operator operator=(A&&) doesn't exist at all. However, the copy assignment operator operator=(const A&) does ex... |
70,299,547 | 70,305,792 | Can ";" be added after "#define" And whether variables can be used in it | A topic has the following code, which is required to indicate the location of the error.
#include<iostream>
#define PT 3.5;
#define S(x) PT*x*x
void main() {
int a = 1, b = 2;
std::cout << S(a + b);
}
I think ";" caused this problem ,and deleted ';' the post compilation test can get the correct results.Bu... | Macros are just text substitution, so you can do pretty much anything you want, as long as the result of the substitution is valid code. So the literal answer to "Can ';' be added after #define" is yes, but the result might not work.
#define calc(x) ((x) * (x));
void f() {
int g = 3;
int h = calc(g);
}
The re... |
70,299,626 | 70,299,650 | Is it OK to pass reference to a pointer as a function argument? | I had the understanding that in c++ & and * cancel each other i.e int *&p is essentially equal to p as its value at address of integer p.
Now is it valid to pass reference to a pointer in view of above i.e say i am trying to pass reference to a pointer as an argument in a function as below?
void func(int* &p)
Won't th... | You are correct that the & address-of operator and the * indirection operator cancel each other out when used inside an expression.
However, when used inside a declaration, these operators have a very different meaning. Inside a declaration, * means "pointer" and & means "reference". Therefore, when used inside a decla... |
70,299,936 | 70,300,054 | How can we access an unnamed namespace outside the file it is created in? | I was reading online about namespaces, and read about unnamed namespaces. I read that unnamed namespaces are only accessible within the file they were created in. But when I tried it on my own, it didn't work like that. How is that possible?
Here is what I did:
file1:
#include <iostream>
using namespace std;
namespace... |
Can we access the unnamed namespaces outside the file they were created?
Depends on which "file" you're referring to. If you refer to the header file, then yes you can access the unnamed namespace outside, since the unnamed namespace is available to the entire translation unit that includes the header.
If you refer t... |
70,300,317 | 70,300,476 | c++: A function pointer as a parameter. But the function being pointed is declared with Parent class, actual function is given with Child class | Its like a riddle. So lets explain one by one.
I have a driver function(fD) which receives a function pointer and calls it multiple times in while loop.
The function pointer(fP) has a parameter of class A.
There are 3 child classes of class A, class B,C,D.
I want fP to be able to receive all child classes B,C,D in pla... | I think this is what you may want to do:
class A {};
class B : public A {};
class C : public A {};
class D : public A {};
void fD(A& instance, void (*fP)(A&))
{
for (int i = 0; i < 10; i++)
{
fP(instance);
}
}
void PointedFunction(A& a)
{
/* Do Something with the A family */
}
int main()
{
... |
70,300,420 | 70,301,045 | How to delete a pointer stored within a node? | I'm trying to set up a binary tree comprised of nodes that hold pointers to objects, but in my "clear tree" function I come across a read access violation when trying to free memory at the pointer within the node. Why is there no exception thrown when I free memory at the root pointer, but there is at the int pointer w... | I would suggest starting with making Node responsible for its own content:
struct Node {
Node(int *val) : val(new int(*val)) { }
int* val = nullptr;
Node* right = nullptr;
Node* left = nullptr;
~Node() { delete val; }
};
Having done this, we can simplify the code for Empty (and Insert) a bit by let... |
70,300,680 | 70,300,808 | Codeforces 761 B "Dasha and Friends" solution | I am trying to solve problem 761 B "Dasha and Friends" on codeforces, and I have been stuck on it for a while now. It seems to be an easy problem but I just can't figure it out. Here is the official hint for the problem as given on the codeforces tutorial page:
Let's add distances between pairs of adjacent barriers of ... | Runners have distinct start points, so you cannot compare positions relative to start points.
But distances between obstacles are the same, so comparison of sequences of these distances is valid.
The first problem is segment around start position - but we can get it's length by subtracting last_barrier from L+first_bar... |
70,301,135 | 70,318,644 | Skia-for-Aseprite libs: how to compile for a DEBUG-build project in Visual Studio? | I'm building static C++ libs off of github. Specifically, the Skia-for-Aseprite libs (link is to the github page). I'm following the windows compilation instructions written up in the git repo's readme. The instructions have you compile the libs using LLVM/CLANG and the Ninja build system. Afterwards they work just... | I've found a solution! Apparently this solution is applicable to any LLVM DEBUG-built library to be used in Visual studio.
The line in my question that triggered the compile (which started with "gn gen") ends with:
extra_cflags=[""-MT""]"
To get the compiled library recognizable as DEBUG-mode in visual studio, the "-M... |
70,301,363 | 70,303,734 | C++: How to enforce the templated type to implement a certain operator(s)? | There was a similar question from 9 years ago (C++11) and maybe the newer standards provide this.
I would like to make sure that the templated class I am writing can be instantiated only if the type used implements certain operators, for example <.
template <typename T>
class XX {
private:
T foo;
public:
bool c... | This is a good use case for using C++20 concepts:
template <typename T>
requires requires (const T& x, const T& y) { x < y; }
class XX {
private:
T foo;
public:
bool continiumTransfunctioneer(const T& zoo) const { return zoo < foo; }
};
Demo.
|
70,301,690 | 70,301,879 | Evaluate the value of an arithmetic expression in Reverse Polish Notation. what is the error in this code , only one test case is giving me wrong ans | link to problem:
https://www.interviewbit.com/problems/evaluate-expression/
last test case [ "500", "100", "20", "+", "40", "*", "+", "30", "-" ] is giving me wrong ouput . although in dry run it is giving correct ouput
int Solution::evalRPN(vector<string> &a) {
stack<char> s;
for(int i =0;i<a.size();++i){... | I think the issue is that you have declared stack for a char while you are pushing integers into it, try changing your code to use
stack<int> s;
|
70,302,112 | 70,303,913 | Wrapper generator SWIG (C++/Perl): How to access "blessed" objects in a 1d vector<double>in Perl? | I have written a C++ library to extract simulation data (= simple vectors with (x,y) or (x,y,z) components) from electronic design automation (EDA) tools. More concrete, this data represents electrical signals for different points in time.
The C++ library offers several methods. Two important ones are:
std::vector<std:... | You need to write an output typemap for std::vector<std::vector<double>> to convert to a proper Perl array of arrays. Here is an example:
VecVec.i:
%module VecVec
%typemap(out) std::vector<std::vector<double>> {
AV *array = (AV *) newAV();
auto vec_ptr = &$1;
std::vector<std::vector<double>>& vec = *vec_ptr... |
70,302,229 | 70,302,291 | Vector of subclasses | I need to do 4 classes. Superclass robot, two subclasses r1 and r2 and class line. Classes robot, r1 and r2 has one static member l_obiektow which are used to display number of objects and two virtual methods praca which is used to display type of an object and clone which is used to make copy of an object. Class line ... | This is a serious bug:
virtual wsk clone()const{
r1 tmp=r1(*this);
return &tmp; // returning pointer to a local object
}
You are returning a pointer to a local object on stack. After clone() returns, tmp will be destroyed.
Dont use raw owning pointers. Use smart pointers instead, ex. unique_ptr ... |
70,302,283 | 70,302,729 | how to calculate the average of each string | I'm having a hard time converting the ASCII counterpart of each char in string,
my objective is to convert the average of each word
for example:
if the user input "love" the code will return 54,
the thing is this code is inside a loop and if the user input for example;
Word no.1: "love"
Word no.2: "love"
the code shoul... | You need to set sum = 0; for each word you do calculations on.
There are also a number of other small issues that I've commented on in this example:
#include <cctype>
#include <iostream>
#include <string>
int main() {
int numofinput = 2;
for(int x = 1; x <= numofinput; x++) {
std::cout << "Word no. " ... |
70,302,566 | 70,307,322 | Change grid lines or border for a single cell in a wxGrid | I trying to set up the cells in a wxGrid so that some of them have a thicker or thinner border. I figured out how to do it for entire rows or columns (i.e. overriding wxGrid::GetColGridLinePen() and wxGrid::GetRowGridLinePen()), but I cannot figure out how to change the border of just a single cell.
I think it should i... | You do indeed need to use a custom renderer to customize the appearance of individual cells and the grid sample is the right place to look. There are, of course, a lot of things going on there, but search for MyGridCellRenderer for an example of using a custom renderer -- it's really not difficult, you just derive from... |
70,302,746 | 70,303,579 | Remove an array from a setlist if count above x | I am currently using an std::set<uintptr_t> list to store unique pointers in it. This list gets bigger with the time and when this list reaches x amount of entries it should delete the first entry, the other entries should move down one and make room for a new entry.
For example:
if (list.count >= 20)
{
list.remove... | You can get the iterator of your first element in your list with list.begin()
if (list.count >= 20)
{
list.erase(list.begin()); //remove the first entry from the list
}
|
70,302,865 | 70,302,917 | std::ios_base::sync_with_stdio(false), advantages, disadvantages? | What is the difference between std::ios_base::sync_with_stdio( false );
Vs std::cout.sync_with_stdio( false ); and std::cin.sync_with_stdio( false );?
Which one should I use supposing my code does not use any of the C streams from <cstdio> and only uses C++ streams from <iostream>?
I want to know:
what are the advanta... | sync_with_stdio is a static function.
so
std::cout.sync_with_stdio(false);
is in fact
std::cout, std::ios_base::sync_with_stdio(false);
|
70,302,896 | 70,302,981 | How to conditionally init const char* arr[] with ternary operator | TLDR;
How to conditionally init a const char* [] ?
const char* arr[] = (some_condition ? {"ta", "ta"} : {"wo", "lo", "lu"});
error: expected primary-expression before ‘{’ token (...)
error: expected ‘:’ before ‘{’ token (...)
error: expected primary-expression before ‘{’ token (...)
error: invalid conversion from ... | As a workaround, you can create 2 different arrays, and switch between them:
const char* arr1[] = {"ta", "ta"};
const char* arr2[] = {"wo", "lo", "lu"};
auto arr = some_condition ? arr1 : arr2;
Another possibility is to use vectors:
std::vector<const char*> varr;
varr.push_back("arg1");
if (use_optional) varr.push_bac... |
70,304,181 | 70,312,449 | Can I reinterpret_cast some byte range of a POD C-Array to std::array<char,N>? | I want to use fixed contiguous bytes of a long byte array s as keys in a std::map<std::array<char,N>,int>.
Can I do this without copying by reinterpreting subarrays of s as std::array<char,N>?
Here is a minimal example:
#include <map>
int main() {
std::map<std::array<char,10>,int> m;
const char* s="Some long co... | No—there is no object of type std::array<char,10> at that address, regardless of the layout of that type. (The special rules for char do not apply to a type that happens to have char subobjects.) As always, it is not the reinterpret_cast itself whose behavior is undefined, but rather the access through that non-objec... |
70,304,444 | 70,305,024 | How to remove duplicates elements in nested list in c++ | I'm trying to solve one np-complete problem in C++. I can solve this problem in Python but running time is relatively slow, so that's why I switch to C++. In one part of the problem I need to clean duplicate elements from my list.
I have a list the type is list<list<int> > in c++. My list contains duplicate elements fo... | I know this solution is not rational, but I offer to use set<list<int>>:
#include <iostream>
#include <list>
#include <set>
using namespace std;
template<class Type>
void showContentContainer(Type& input)
{
for(auto itemSet : input)
{
for(auto iteratorList=itemSet.begin(); iteratorList!=itemSet.end(); +... |
70,304,691 | 70,304,873 | Force file to be compiled as C, using a directive from the file itself | I have some old code files in my C++ project, that need to be compiled as C code - the entire codebase is set to compile as C++.
I am using Visual Studio, but I'd rather avoid setting this per-file from the project properties, and would rather use some kind of #pragma directive (if possible).
I have searched around, bu... | "By default, CL assumes that files with the .c extension are C source files and files with the .cpp or the .cxx extension are C++ source files."
So rename the files if nessesary and put the new c files to your projekt.
If neded set the compiler options:
Set compiler
|
70,305,126 | 70,305,211 | C + + cannot find the thread it created on ubuntu 18 | I write a simple c++ code. In my code, I create two threads, then I name the two threads TCPCall30003Proc and TCPCall30004Proc, but I can not find them using top command with option -H. My os is ubuntu 18.
#include <pthread.h>
#include <thread>
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <stdlib.h... | From the pthread_setname_np manual page:
The thread name is a meaningful C language string, whose length is restricted to 16 characters, including the terminating null byte ('\0').
[Emphasis mine]
You names are 17 characters, including the null-terminator.
If you check what pthread_setname_np returns it should return... |
70,305,286 | 70,305,456 | Why this weired c++ template syntax is compiled successfully? | I Recently came across this c++ weired syntax used with function and compiled successfully.
I could not able to make sense out of it , what this really does.
How "*member" does not gave me undefined error or something else, because its not declared anywhere else.
Can anyone let me how to call this function?
template<cl... | When you wrote
META POS:: *member
this means that member is a pointer to a member of class POS that has type META.
Now coming to your second question,
Can anyone let me how to call this function?
One possible example is given below:
#include <iostream>
#include <string>
struct Name
{
std::string name;
N... |
70,305,378 | 70,305,613 | C++ Loop through a set/list and remove the current entry | Hey I loop through a list of integers, check each one by one if it equals number x and if so remove it from the list.
I tried it like that:
std::set<uintptr_t> uniquelist = {0, 1, 2, 3, 4};
for (auto listval : uniquelist)
{
if (listval == 2)
{
uniquelist.erase(listval);
}
}
//... | #include <iostream>
#include <set>
using namespace std;
void showContentSet(set<int>& input)
{
for(auto iterator=input.begin(); iterator!=input.end(); ++iterator)
{
cout<<*iterator<<", ";
}
return;
}
void solve()
{
set<int> uniqueSet={0, 1, 2, 3, 4};
cout<<"Before, uniqueSet <- ";
sh... |
70,305,706 | 70,349,466 | Is there a way to use hidden friends when using (recursive) constraints? | Suppose one has a class for which one wants to define hidden friends, e.g. heterogeneous comparison operators:
#include <concepts>
template <typename T> struct S;
template <typename C> constexpr bool is_S = false;
template <typename T> constexpr bool is_S<S<T>> = true;
template <typename T>
struct S {
using type... | Here's a possible solution: defining the operator in a non-template empty base class:
class S_base
{
template <typename V, typename U>
requires
is_S<V> && (!is_S<U>) && std::equality_comparable_with<typename V::type, U>
friend constexpr bool operator==(const V &v, const U &u) { return v.data == u;... |
70,305,745 | 70,306,683 | Do bitwise operations with negative numbers cause ub? | Is it implementation-defined or undefined behaviour to do things like -1 ^ mask and other bitwise operations like signed.bitOp(unsigned) and signed.bitOp(signed) in C++17?
| Before the various bitwise operations in C++17, the two operands undergo the "usual arithmetic conversions" to make them have the same type. Depending on how the two types differ, you can get a signed or unsigned type. Those conversions dictate whether you have well-defined behavior or not.
If the "usual arithmetic con... |
70,305,888 | 70,305,979 | How can you identify a string with a char pointer? | I am learning c++ from a book, but I am already familiar with programming in c# and python. I understand how you can create a char pointer and increment the memory address to get further pieces of a string (chars), but how can you get the length of a string with just a pointer to the first char of it like in below code... | This behavior is explained within the docs for std::strlen
std::size_t std::strlen(const char* str);
Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character. The behavior is undefined ... |
70,306,575 | 70,307,043 | Why is failbit set when I enter EOF? | I'm currently learning how while (cin >> num) work and I found out that there are two steps.
First one is the operator>> function return a istream object with error state, and the second is bool converter that convert istream object into bool depend on its state.
But I find it confusing that in the bool convert functio... | eofbit is set when a read operation encounters EOF while reading data into the stream's buffer. The data hasn't been processed yet.
failbit is set when the requested data fails to be extracted from the buffer, such as when reading an integer with operator>>. While waiting for digits to arrive, EOF could occur. eofbit ... |
70,306,885 | 70,306,957 | how do I declare leastfreq in scope? | Here in the code, I have created a function to calculate the least frequent element. Whenever I run the program it says leastfreq was not declared in the scope.
Can someone tell me how to solve this error and what is this error about?
Error : "error: 'leastfreq' was not declared in this scope"
#include<iostream>
using ... | Solution 1: Put the function leastfreq's definition before main() as shown below:
#include<iostream>
using namespace std;
//leastfreq defined before main
int leastfreq(int a[],int arrsize){
int currentct,leastct=0;
int leastelm;
for(int j=0;j<arrsize;j++){
int temp = a[j];
for(int i=0;i<arrsize;i++){... |
70,306,896 | 70,306,961 | Pass Object by reference to store internally | I am trying to code a c++ example of two clases, one storing a reference to an object of the other class for an arduino.
My minimal code so far is not working out quite, hope for any pointers (smirk) to the solution here:
main.cpp:
#include <Arduino.h>
#include <ClassA.h>
#include <ClassB.h>
void setup() {
// put yo... | try replacing this
void setup() {
// put your setup code here, to run once:
ClassA clA();
ClassB clB(clA);
};
with this
void setup() {
// put your setup code here, to run once:
ClassA clA;
ClassB clB(clA);
};
why:
when you do
ClassA clA();
you are not creting an instance of the class A but instead
is int... |
70,307,151 | 70,307,790 | Is GCC's implementation of std::invocable incorrect or still incomplete? | I tried using std::is_invocable in the following code snippet available on godbolt.
#include <type_traits>
struct A {
void operator()(int);
};
struct B {
void operator()(int, int);
};
struct C : A, B {};
int main()
{
static_assert(std::is_invocable<A, int>() == true);
static_assert(std::is_invocable<B, int... | GCC is actually correct here. If we follow the rules in [class.member.lookup] we first have
The lookup set for N in C, called S(N,C), consists of two component sets: the declaration set, a set of members named N; and the subobject set, a set of subobjects where declarations of these members were found (possibly via u... |
70,307,203 | 70,307,312 | How to tell the difference between two clients? | I have a client 1 send some data to the server and I want to the server transfer that data to client 2 instead of client 1. Is there any way to tell the server we have to different client sockets, if client 1 send data don't send back to client 1 but send to client 2?
When the server accept the client 1, I try put in i... | Your current architecture starts a thread for each client:
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ClientSession, (void*)ClientSocket, 0, &threadID);
and then the main thread keeps a list of all client sockets, in a local variable:
list<SOCKET> a;
a.push_back(ClientSocket);
then, whenever a thread receives,... |
70,307,445 | 70,307,522 | How to pass class method as an argument to another class method | I'm learning C++, and I was wondering how to pass class method as an argument to another class method. Here's what I have now:
class SomeClass {
private:
// ...
public:
AnotherClass passed_func() {
// do something
return another_class_obj;
}
AnotherClassAgain... | The type of a member function pointer to SomeClass::passed_func is AnotherClass (SomeClass::*)(). It is not a pointer to a free function. Member function pointers need an object to be called, and special syntax (->*) :
struct AnotherClass{};
struct AnotherClassAgain{};
class SomeClass {
private:
// ...
... |
70,307,529 | 70,308,252 | C++ custom template with unordered_map | I am trying to create a custom template, and have such code:
template <typename T>
struct Allocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
T *allocate(size_type n, const void *hint=0);
T *allocate_at_least(size_type n);
void deallocate(T *p, size_... | It needs to have a default constructor and a constructor that is like a copy constructor but parametrized on a non-T type. The following compiles.
template <typename T>
struct Allocator {
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
T* allocate(size_type n, const v... |
70,307,855 | 70,307,954 | Iterating by reference on a C++ vector with foreach | Does it make any sense to do something like:
void my_fun(std::vector<int>& n)
{
for (int& i : n)
{
do something(i);
}
}
compared to a normal foreach loop without the reference? Would the value be passed by copy otherwise?
| It does what you think it does assuming that the signature of do_something is void do_something(int& i).
If you don't put the ampersand in the range-based for-loop you'll get a copy.
|
70,308,389 | 70,335,582 | Segmentation fault with c++17, but not c++11, with Apache Avro | UPDATE: So I found a post talking about Avro using an older standard c++11/14 here. I really don't understand what the commenter was talking about to make changes, but it was obvious that something in the Boost library, or the fact that avro wasn't using the boost library was the issue.
so I found the GenericDatum.hh f... | So with the help of @RichardCritten I was able to figure out how to fix my issue.
As Richard mentioned in his comment above, I was linking to a pre-built library, which was built with c++11. What I ended up doing was looking through the build script and ultimately in the CMakeLists.txt file, I changed the CMAKE_CXX_STA... |
70,308,752 | 70,309,907 | How to calculate position of a moving object on a line | So basically I'm making a pool game (sort of) on c++. I'm still thinking about the theory and how exactly to make it before I start coding and I'm a bit stuck. So the ball starting coordinates are given and also an input is given on how much power is going into the shot and the direction of the shot with coordinates.
E... | You probably want to work in terms of orthogonal components, basically thinking of the displacement of the ball in terms of deltaX and deltaY instead of finding a line it will travel. Conveniently, you are already in rectangular coordinates and can compute your changes in x and y followed by scaling them by your power ... |
70,309,243 | 70,310,570 | How to detect which (C++) language standard was selected in the Project->General Properties->C++ Language Standard | I'm developing with Visual Studio 2019, and would like to be able to compile my C++ program conditionally based on the language standard chosen (C++20, C++17, etc.) from Project Properties -> General Properties -> C++ Language Standard.
What gets defined when I set it C++20, for example, so that I can use it as:
#ifdef... | This should work:
#if (__cplusplus >= 202002L)
// C++20 (or later) code
#elif (__cplusplus == 201703L)
// C++17 code
#else
// C++14 or older code
#endif
|
70,309,251 | 70,309,492 | Why can't a const mutable lambda with an auto& parameter be invoked? | #include <type_traits>
int main()
{
auto f1 = [](auto&) mutable {};
static_assert(std::is_invocable_v<decltype(f1), int&>); // ok
auto const f2 = [](auto&) {};
static_assert(std::is_invocable_v<decltype(f2), int&>); // ok
auto const f3 = [](auto&) mutable {};
static_assert(std::is_invocable_v... | There are two interesting things here.
First, a lambda's call operator (template) is const by default. If you provide mutable, then it is not const. The effect of mutable on a lambda is solely the opposite of the effect of trailing const in normal member functions (it does not affect lambda capture, etc.)
So if you loo... |
70,309,370 | 70,309,504 | Why template chooses T equals int when implicity passed uint16_t? | I have next snippet
class Mapper { //not templated!
...
template<class T>
static QList<quint16> toPduValue(T value)
{
constexpr quint8 registersPerT = sizeof(T) / sizeof(quint16);
return buildPduValue((registersPerT < 1) ? (quint16) value : value);
}
template<class T>
static QList<quint16> buildPduValue(T va... | The type of your ternary expression is int. You can verify this by trying to compile this code and looking carefully at the error message:
#include <stdint.h>
char * foo = (2 < 3) ? (uint16_t)2 : (bool)1;
The error message will be something like:
error: invalid conversion from 'int' to 'char*'
You could just apply ... |
70,309,418 | 70,311,922 | How can an object be destructed more times than it has been constructed? | I have a class whose constructor is only called once, but its destructor is called three times.
void test_body()
{
std::cout << "----- Test Body -----" << "\n";
System system1;
Body body1({1,1,1}, {2,2,2}, 1, system1);
system1.add_body(body1);
std::cout << system1.get_bodies()[0].get_pos() << "\... |
How can an object be destructed more times than it has been constructed ?
It can't. You are simply not logging every constructor that is being called.
For instance, bodies.emplace_back(std::move(body)) constructs a new Body object using the Body(Body&&) move constructor, which you have default'ed and are not logging... |
70,310,112 | 70,310,494 | How to make a vector of sf::sound | I use the SFML library and more specifically the audio part of SFML. I would like to store multiple sf::Sound, so it occurred to me to make a class that handles sounds and to make a vector of sf::Sound.
However, when I try to play a sound, only the last element of the list of my vector can be played, the rest does not ... | When you copy SFML sound objects they stop playing. That's what happens when you relocate objects in an std::vector. I would recommend storing them in pointers as with
using SoundPtr = std::shared_ptr<sf::Sound>;
std::vector< SoundPtr > m_sound;
|
70,310,189 | 70,310,877 | Are STL vectors pass by reference/address? | I was solving a recursion problem. While solving, I got stuck in a position where I am unable to figure this out:
#include<bits/stdc++.h>
using namespace std;
vector<int> Search(int arr[],int in, int n, int t, vector<int> &v){//v passed as ref.
if(in == n){
return v;
}
if(arr[in] == t){
v.p... | In the case of passing by reference you are pushing into the same vector that you pass in.
However when you pass by value you are pushing into a copy of the vector. But then you are returning the vector which returns the local copy, then you are assigning that (eventually) to the vector v in main. That's what makes it ... |
70,310,612 | 70,310,748 | Open 2 distinct sockets to 1 common remote endpoint using Boost::asio | I am trying to test sending data from 2 distinct network adapters on the same machine to a common remote endpoint, but I keep getting "bind: invalid argument" AFTER the first bind comes through. What am I missing? I have searched, tried to modify the code, but I was not able to find any lead and I keep getting the same... | socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_1]), 0));
...
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_2]), 0));
You are trying to bind the same socket1 twice. Likely you mean socket2 in the second statement.
|
70,310,867 | 70,310,937 | Way for class template to deduce type when constructing an instance with std::make_unique? | Let's say we have a class template Foo, that has one type template parameter that it can deduce from an argument in its constructor. If we use std::make_unique to construct an instance of Foo, is there a way for Foo's constructor to deduce the template arguments as it would have if its constructor was called normally? ... | You can leverage a helper function to wrap the ugly code into a pretty wrapper. That would look like
template <typename... Args>
auto make_foo_ptr(Args&&... args)
{
return std::make_unique<decltype(Foo{std::forward<Args>(args)...})>(std::forward<Args>(args)...);
}
|
70,311,161 | 70,320,023 | C++ : How to get actual folder path when the path has special folder names | I am trying to find a way to convert a path like this: "%APPDATA%\xyz\Logs\Archive" to this: "C:\Users\abcUser\AppData\Roaming\xyz\Logs\Archive".
I am on Windows platform. I use Unicode character set. I can use C++17 if required. I can use boost libraries if required.
In my search so far, I came across the SHGetKnownFo... | The Win32 API that expands environment variable references of the form %variable% in strings is ExpandEnvironnmentStrings.
|
70,311,357 | 70,311,401 | C++ Function that accepts array.begin() and array.end() as arguments | I want my function to be able to take array.begin() and array.end() as arguments. As far as I understand, the begin/end functions return a pointer to the first/last element of the array. Then why does the following code not work? How should I write the code instead?
#include <iostream>
#include <array>
template<class ... |
As far as I understand, the begin/end functions return a pointer to the first/last element of the array
No. begin and end return iterators. The standard library works with iterators. Iterators are a generalization of pointers.
Iterators behave like pointers and you use them like pointers (e.g. *it to access the eleme... |
70,311,461 | 70,320,987 | C++ how to accept arbitrary length list of pairs at compile time? | I'm looking to build a compile-time read only map and was hoping to back it with a std::array or std::tuple where each element is a std::pair. For ease of use, I would like to avoid having to annotate every entry at construction, and I'd like it to deduce the number of elements in the map i.e.:
constexpr MyMap<int, std... | If I am understanding correctly, the size of map is known and fixed? If so, why not use a regular c-style array constructor? Unfortunately, there is no way to make the compiler deduce the type of direct initialization lists (ex: deduce {1, "value"} to std::pair<int, std::string_view>) So, you have to specify the type f... |
70,311,515 | 70,311,571 | Can I make a function that returns a different type depending on a template argument, without using function parameters? | This is almost what I want and it works:
int abc(int) {
return 5;
}
float abc(float) {
return 8.0;
}
int main() {
std::cout << abc(1) << "\n";
std::cout << abc(1.0f) << "\n";
}
But I don't want to pass dummy parameters into the function. I want to have some sort of function and then use it like this... | No need to define functors as in Mayolo's answer. You can simply specialize a function template:
#include<iostream>
template<typename T>
T foo();
template<>
int foo() {
return 5;
}
template<>
double foo() {
return 8.0;
}
int main() {
std::cout << foo<int>() << "\n";
std::cout << foo<double>() << "\n... |
70,311,678 | 70,311,766 | Why are the paired elements in my vector outputting wrong? | For context, I am working on a reward system program for a store. I have a file which contains a list of items with the points the customer earns underneath the name of each item. Here is what the file contains:
rolling papers
1
lighter
1
silicone pipe
5
glass pipe
8
water pipe
10
I am trying to read from the file int... | Try changing the inFS >> points for another std::getline(inFS, points_str) (notice you need a std::string points_str{};); then you can do a make_pair(item, std::stoi(points_str)). [Demo]
#include <iostream> // cout
#include <string> // getline, stoi
int main()
{
std::string item{};
std::string points{};
... |
70,312,179 | 70,312,271 | Why is my simple C++ Windows.h window so laggy? | I'm in the process of exploring options for creating windows applications in C++, and today I tried "Windows.h". It was working pretty well (apart from the copious boilerplate code) until I tried rendering text to the window. Compiling times jumped up to like 20 seconds, and the window was extremely laggy. Does anyone ... | It's slow because you are creating a window every time your window fields a message
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
... |
70,312,426 | 70,312,475 | From a json object/file, how can I derive the values belonging to keys within an array while storing them as a string within a vector? |
Json object/file sample:
{
"ADMIN_LIST" :[
{
"name" : "Luke",
"age" : 36,
"id_hash" : "acbfa7acrbad90adb6578adabdff0dcbf80abad43276d79b76f687590390b3ff429"
},
{
"name" : "Sasha",
"age" : 48,
"id_hash" : "97acbfa7acrbad90adb6578adabd0dcbf80abad43276d79b76f687590390b3ff4... | I would use a well-known library, like https://github.com/nlohmann/json.
Here is an example of how you can access array elements by key: accessing elements from nlohmann json
|
70,312,614 | 70,312,654 | Is there a way that one function can use the variables of another function without any argument passing in C++? | If I have 2 functions like follows:
template <typename T>
void A(int n)
{
T a[n]; // need to use this array of variables in function B without any passing
// assignment of values to a[n] variables and rest of code for function A
}
void B()
{
// need to use a[n] array here without passing
}
Can the static ar... | No. Functions have a scope, names of automatic variables are inaccessible outside of that scope, and other functions are outside of that scope.
Is it called function forwarding or perfect forwarding in C++?
No, what you're asking about is not related to forwarding. Forwarding is passing of arguments which is the oppo... |
70,312,636 | 70,312,696 | How to get length of the buffer which is just received from socket? | I am using the #include <sys/socket.h> library socket connection with server and using vector of type char for receiving the data from the socket connection which as shown below:
struct sockaddr_in serv_addr;
int sock, valread;
sock = 0;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
p... | Always inspect return-values in C-style APIs!
C-style APIs are directly callable from most other programming languages, including C++. Because portable C doesn't support thrown exceptions C-style library APIs are designed indicate error conditions typically through return-values (e.g. returning NULL or a negative value... |
70,313,146 | 70,313,285 | Why Removing the default constructor is giving error in the compilation of code in c++? | #include <iostream>
using namespace std;
class BankDeposit {
int principal;
int years;
float interestRate;
float returnValue;
public:
BankDeposit() { } //This is line number 12
BankDeposit(int p, int y, float r); // r can be a value like 0.04
BankDeposit(int p, int y, int r... | BankDeposit bd1, bd2, bd3;
This line where you are creating an object of a class requires a constructer which should be a default constructer as you have not passed any parameters.
Edit : Just saw the comments under the question they have already explained it, furthermore this question can be easily resolved by readin... |
70,313,328 | 70,313,357 | class B derived from an abstract base class A, and how can i use singleton in class B? | below is the demo code:
class A {
public:
A(){}
virtual void method()=0;
//....
virtual ~A(){};
}
class B : public A{
static A * ptr;
//....
public:
//....
static A* GetInstance() {
if (ptr == nullptr)
ptr = new B(); // error, currently B is an abstract class, i... | You have to implement your method1 inside class B.
This is not a problem of Singleton. The problem is, that you cannot create an instance of an abstract class. Your class B is abstract, because not all pure virtual methods are implemented in class B.
Or do the following:
class AImplement : public A
Inside AImplement, y... |
70,313,613 | 70,313,965 | how to call another class's member function? | I have two class, class A, Class B, in class B has a static function like below:
class A {
public:
void method(){ B::method(); }
};
class B {
public:
static int method() {
cout << "method of b" << endl;
}
};
int main()
{
class A a;
a.method();
}
this code build error, because in cla... | Take a look at the modified code. Inline comments explain the changes:
class A {
public:
// only declare the method
void method();
// Do NOT define it here:
// { B::method(); }
};
class B {
public:
static int method() {
std::cout << "method of b" << std::endl;
return 0;
}
}... |
70,313,617 | 70,749,357 | Why is there latency in this C++ ALSA (Linux audio) program? | I am exploring sound generation using C++ in Ubuntu Linux. Here is my code:
#include <iostream>
#include <cmath>
#include <stdint.h>
#include <ncurses.h>
//to compile: make [file_name] && ./[file_name]|aplay
int main()
{
initscr();
cbreak();
noecho();
nodelay(stdscr, TRUE);
scrollok(stdscr, TRU... | The latency in the above loop is most likely due to delays introduced by the ncurses getch function.
Typically for realtime audio you will want to have a realtime audio thread running and a non-realtime user control thread running. The user control thread can alter the memory space of the real time audio thread which f... |
70,313,665 | 70,313,765 | To search an element using Binary Search | I tried the following code for searching an element in the array using binary search without using the function, but it does not work as it stops just after asking the Number I am searching for in the array. Not able to figure out, As exactly where I am mistaken.
Using Visual Studio Code.
int main()
{
int arr[10],... | You have initialized h = n-1 before initializing n. Hence, we have Undefined behaviour.
#include <iostream>
using namespace std;
int main()
{
int arr[10], n, num , mid, l, h, i;
cout<<"Enter the number of elements in the array\n";
cin>>n;
cout<<"Enter the elements of the array\n";
for(int i=0;i<n... |
70,313,749 | 70,314,056 | Combining static_cast and std::any_cast | Is there any safe std::any_cast and static_cast combination?
I'm trying to perform the following:
#include <any>
#include <iostream>
int main( )
{
auto x = std::make_any< int >( 5 );
#if 0 // doesn't work
std::cout << std::any_cast< short >( x );
#else // works, but requires knowing the initial type
std::c... | The only way to get a value out of std::any is any_cast<T> where T has the same typeid as the value inside (you can inspect it with .type() method).
If you need other semantics, e.g. "take a value iff it's convertible to int", you have to use something else for type erasure. For example, you can write one yourself.
|
70,313,870 | 70,314,894 | How to reduce the float rounding error when converting it into fixed-point in C++? | I have a float variable which is incremented 0.1 in each step. I want to convert it into 16-bit fixed value where it has 5-bits fractional part. In order to do that I have the code snippet below:
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main() {
bitset<16> mybits;
strin... |
How to reduce the float rounding error when converting it into fixed-point in C++?
Rearrange the calculation of the fixed-point encoding to round the result to an integer and so that all arithmetic in it is performed exactly until a single division just before the rounding, as with mybits = bitset<16>(std::round((x*1... |
70,314,268 | 70,314,600 | DirectWrite: IDWriteFontFamily::GetFontCount | When I try to get the count of fonts in a font family by using DirectWrite, I get the wrong result. For example, when I look at the system font folder, Arial font family has 9 fonts but, GetFontCount returns 14. What is that surplus number 5? How that happens? Is that a bug or is there something I dont know or that the... | DirectWrite simulates "oblique" fonts (that are not in the physical files).
For Oblique, the slant is achieved by performing a shear
transformation on the characters from a normal font. When a true
italic font is not available on a computer or printer, an oblique
style can be generated from the normal font and used to... |
70,314,298 | 70,314,532 | Does deleted destructor change aggregate initialization in C++? | The code as follows
struct B {
~B() = delete;
};
B * b = new B{};
fails to compile in the latest MSVC with the error:
error C2512: 'B': no appropriate default constructor available
note: Invalid aggregate initialization
At the same time both GCC and Clang do not see anything wrong in the code, demo: https://gcc.... | Neither definition of the notion of aggregate in C++ Standards refers to the destructor.
For example the definition of an aggregate in C++ 20 (9.4.2 Aggregates) sounds the following way
1 An aggregate is an array or a class (Clause 11) with
(1.1) — no user-declared or inherited constructors (11.4.5),
(1.2) — no privat... |
70,314,376 | 70,466,322 | Enable/disable perf event collection programmatically | I'm using perf for profiling on Ubuntu 20.04 (though I can use any other free tool). It allows to pass a delay in CLI, so that event collection starts after a certain time since program launch. However, this time varies a lot (by 20 seconds out of 1000) and there are tail computations which I am not interested in eithe... | There is an inter-process communication mechanism to achieve this between the program being profiled (or a controlling process) and the perf process: Use the --control option in the format --control=fifo:ctl-fifo[,ack-fifo] or --control=fd:ctl-fd[,ack-fd] as discussed in the perf-stat(1) manpage. This option specifies ... |
70,314,562 | 70,314,610 | Printing variables of different derived class objects inside a single vector | So I have this simple code with one base class and 2 derived classes. Each derived class has it's own variable and the base class has an id variable which should be shared with all the elements I create from the derived classes.
After creating 2 objects and adding them in a vector, I can only print their IDs. Is there ... | One of the possible solutions is using virtual functions like in the following example. Take a look for the Print() methods below...
class Item
{
public:
int id;
Item(int id) { this->id = id; }
virtual void Print(std::ostream& os) { os << id << " "; }
};
class ItemTypeA : public Item
{
public:
int a;... |
70,315,018 | 70,315,124 | The advantage of std::visit over if-else | I have figured out that std::visit can be used the following way:
std::visit([](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, int>)
std::cout << "int with value " << arg << '\n';
else if constexpr (std::is_same_v<T, std::string>)
... |
Is there any other advantage of using std::visit that I am not seeing?
Yes. With std::visit you can use the built-in function overload resolution instead of matching against all of the types manually:
template<typename... Fs> struct Overload: Fs... { using Fs::operator()...; };
template<typename... Fs> Overload(Fs...... |
70,315,149 | 70,441,589 | Inverting slider effect | I'm trying to invert the value of the myrange slider. When POS = 0, myrange slider should be at max and when POS = 100, myrange slider should be at minimum. When I use the slider it jumps to high values like: 10089. (number is an int controlled by a rotary encoder. When I use the encoder, the script works flawless, so ... | Rotated the slider 180 degrees with CSS.
.slider {
-webkit-appearance: none;
width: 50%;
height: 15px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
-ms-transfo... |
70,315,432 | 70,317,033 | Does libc++ counting_semaphore have deadlock issue? | libc++ counting_semaphore::release:
void release(ptrdiff_t __update = 1)
{
if(0 < __a.fetch_add(__update, memory_order_release))
;
else if(__update > 1)
__a.notify_all();
else
__a.notify_one();
}
Notifies only if internal count was zero before inc... | The conditional if (0 < ...) is a problem, but it's not the only problem.
The effects of release are stated to be:
Atomically execute counter += update. Then, unblocks any threads that are waiting for counter to be greater than zero.
Note the words "any threads". Plural. This means that, even if a particular update v... |
70,315,693 | 70,315,777 | allocate memory to unknown type c++ | I am doing a chess project with cpp.
My board is a metrix of pointer to Piece, and when I construct it I allocate memory to different type of pieces ( Rook, King, Bishop ...).
(for example: this->_board[i][j] = new King())
I want to deep copy the board.
My Idea is to itterate through the board, and for every piece I wi... | You can use virtual function. For example,
class Piece
{
public:
virtual Piece* clone() = 0;
};
class King : public Piece
{
public:
virtual Piece* clone()
{
return new King(*this);
}
};
and then deep copy with other->_board[i][j]->clone().
|
70,315,711 | 70,317,623 | Trapezoidal decomposition of polygon in C++ | I'm dealing with a polygon "fracture" problem which is to decompose a polygon with (or without) holes into trapezoids.
I've found something similar implemented in Python here:
https://deparkes.co.uk/2015/02/05/trapezoidal-decomposition-polygons-python/.
Is there a way to do it in C++?
Given a list of point(x, y) (std:... | I don't know of a library that does this, but here's a rough outline of an algorithm to do this, it's an instance of a scan-line or line-sweep algorithm.
The idea is that you imagine a line parallel to your slice direction sweeping across your data. As this happens you maintain a set of active edges. Each time your lin... |
70,316,138 | 70,316,168 | When I run the code down below it prints "4294967295" and not '-1', Why? | So I made this code for a school exercise and When i Run this code i would like it to show -1, but instead it shows 4294967295 and i don't understand why.
#include <iostream>
class Integer
{
unsigned i;
bool positive;
public:
Integer(unsigned i, bool positive = true)
: i(i)
, positive(posi... | Your + operator is not designed correctly. In every case, you omit the second argument to the constructor of Integer (whose name is positive), so every integer you make there will have positive set to true, and hence (a1+a2) is always positive (i.e. positive is true).
|
70,316,698 | 70,316,874 | Extern C++ compiled fn in asm | I'm following an OS dev series by poncho on yt.
The 6th video linked C++ with assembly code using extern but the code was linked as C code as it was extern "C" void _start().
In ExtendedProgram.asm, _start was called like:
[extern _start]
Start64bit:
mov edi, 0xb8000
mov rax, 0x1f201f201f201f20
mov ecx, 500... | there is a confusion between symbols:
The name of your function start will be mangled to _Z6_startv at compilation which means that the symbols that the linker (and your asm code) can use is _Z6_startv. mangling is what c++ compilers normaly do, but extern "C" tell the compiler to treat the function as if declared for ... |
70,316,744 | 70,317,080 | Output parameters with arrays in one function with Arduino and C ++ | I have a problem with the initialization with various parameters in my function.
It works if I have created an array int params [] = {...}. However, it doesn't work if I want to write the parameters directly into the function.
declaration (in the .h)
void phase_an(int led[]);
in the .cpp
void RS_Schaltung::phase_an(in... | There are several ways of making a function accepting a variable number of arguments here.
However, in your current code there is a problem: when you pass a native array of unknown size as argument of a function (e.g. void f(int a[])), the argument will be managed a pointer to an array, and there is no way inside this... |
70,316,798 | 70,316,959 | std::regex_replace bug when string contains \0 | I maybe found a bug in std::regex_replace.
The following code should write "1a b2" with length 5, but it writes "1a2" with length 3.
Am I right? If not, why not?
#include <iostream>
#include <regex>
using namespace std;
int main()
{
string a = regex_replace("1<sn>2", std::regex("<sn>"), string("a\0b", 3));
co... | This does seem to be a bug in libstdc++. Using a debugger I stepped into regex_replace, until getting to this part:
// std [28.11.4] Function template regex_replace
/**
* @brief Search for a regular expression within a range for multiple times,
and replace the matched parts through filling a format string.
... |
70,316,895 | 70,317,310 | Variadic template calling assert() | I have this code:
#ifdef _DEBUG
#define MY_VERY_SPECIAL_ASSERT(x, ...) assert(x && __VA_ARGS__)
#else
#define MY_VERY_SPECIAL_ASSERT(x, ...)
#endif
which does precisely what it's supposed to. But, in an effort to continue learning forevermore, I'm trying to abide by the constexpr variadic template guideline from the c... | T is a bool, namely it is the result of evaluating the expression E1 with
static_cast<decltype (E1)> (false) != E1;
You're getting the error because std::string has no implicit conversion to bool.
constexpr void MY_VERY_SPECIAL_ASSERT(T x, const std::string &msg) {
// assert(x && static_cast<bool>(msg)); // won't ... |
70,317,123 | 70,317,193 | How to call a function by its name (will be changed by user input) in C++? | I wonder if there is a way to call a function from user's input.
I tried fixed typing directly, but want to make it different by user's input.
If I have functions like this ->
int Step001();
int Step002();
I want to use it by just typing numbers
[output]
type step number >
[input]
1
> calling function by {"step00"+... | I'd build a key value store pointing strings to functions.
#include <cassert>
#include <functional>
#include <iostream>
#include <map>
static int Step001() {
std::cout << "a\n";
return 1;
}
static int Step002() {
std::cout << "b\n";
return 2;
}
int main() {
static const std::map<std::string, std::functio... |
70,317,591 | 70,355,911 | Can not set android clang compilers for Qt Android on Ubuntu | I installed Qt Android 5.15.2 on Ubuntu but there is problem with the compilers. This is what I have set:
And here is what QtCreator detects as compilers:
The first error is displayed here in the Qt version tab:
and also in the Kit tab I see this errors no matter which compilers I set from the available:
Why I got ... | The problem is that you are trying to use a x86 compiler for Android. You need to install the specific compiler from the Android SDK/NDK. So the good news is that you might be only missing one step (step 2 below)
I tried to install from the Ubuntu stock packages. That was impossible to get to work.
I was able to set it... |
70,317,720 | 70,317,756 | Windows C++: absolute memory address to read system time from? | I'm trying to find system time without needing any function/system calls. I seem to remember Windows having an absolute address that a giant struct sits in, which is constantly updated with various system info including time...but google isn't giving me anything...did I imagine this or is it a thing?
| KUSER_SHARED_DATA @ 0x7FFE0000 (its evolution) but the documented functions just read from there anyway so all you gain is the possibility of your application breaking in the next version of Windows.
|
70,317,996 | 70,318,107 | Can't you just make a constexpr array by making a constexpr function that returns one? | I want to construct an array value at compile time and have seen multiple sources online suggesting using a struct with a constexpr constructor:
template<int N>
struct A {
constexpr A() : arr() {
for (auto i = 0; i != N; ++i)
arr[i] = i;
}
int arr[N];
};
int main() {
constexpr auto... |
Can't you just make a constexpr array by making a constexpr function that returns one?
No, you cannot return an array from a function whether it's constexpr or not.
You can however return instance of a class that contains an array as a member. Your A is an example of a such class template, and so is std::array. Both ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.