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 main(){
int int1 = 20;
int int2 = 30;
int &int3 = int1;
wrapper(int1, int2);
}
I am passing int 1 and int 2. These are lvalues. They are silently converted to &int1, &int2. These are converted using &&. But reference collapsing keeps them just &int1, &int2.
f takes && parameters
If I pass simply int1 and int2 as they are I am passing &int1, &int2. This does not work.
So I pass std::forward(int1) std::forward(int2).It should be the same as using static_cast<T&&>. Because of this, thanks to referencing collapsing I can pass to every function f (theoretically even one that accepts only l-value references).
My code does not compile and my logical reasoning has probably some contradictions.
candidate function not viable: no known conversion from 'int' to 'int &&' for 1st argument
void f(int&& int1, int&& int2){
How on earth did I get a simple int after using all these ampersands?
Additional question: My compiler asks me to use wrapper<int &> instead of only wrapper(some parameters). Can I just leave it like in my code, or I need to manually put wrapper<int &> (this is what my compiler is asking me to add). Why do I need <int &> int this case?
| 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 T&. Compiler deduces that at compile time. Notice though, it does not have type specified either, it's a template paremeter. Only in case of those parameters the forwarding reference semantics applies (another way of writing it down is a auto&& in lambdas, but the deduction works the same way).
Thus when you call int x= 3; f(x); you're effectively calling f(int&). Calling f(3) calls effectively f(int&&) though.
void g(int&& arg)
arg is and rvalue reference to int. Because the type is specified, it's not a template argument! It's always an rvalue reference.
Thus, for your case
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 main(){
int int1 = 20;
int int2 = 30;
int &int3 = int1;
wrapper(int1, int2); //call wrapper(int&, int&);
//Then f(std::forward<T>(int1), std::forward<T>(int2));-> f(int&, int&), because they are lvalues! Thus, not found, compilation error!
}
Live demo: https://godbolt.org/z/xjTnjcqj8
|
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, but I want a way to check if the roughHitbox of each SandboxObject collides with another.
When the program starts, it allocates memory for, let's say, 10,000 Circles
int circleCount = 0;//the number of active Circles
constexpr int m_maxNumberOfCircles = 10000;//the greatest number of circles able to be set active
Circle* m_circles = new Circle[m_maxNumberOfCircles];//create an array of circles that aren't active by default
like so.
and every time the user 'spawns' a new Circle, the code runs
(m_circles + circleCount)->setActive();`
circleCount++
Circles that aren't alive essentially do not exist at all; they might have positions and radii, but that info will never be used if that Circle is not active.
Given all this, what I want to do is to loop over all the different arrays of derived classes of SandboxObject because SandboxObject is the base class which implements the rough hitbox stuff, but because there will be many different derived classes, I don't know the best way to go about it.
One approach I did try (with little success) was to have a pointer to a SandboxObject
SandboxObject* m_primaryObjectPointer = nullptr;
this pointer would be null unless there were > 1 SandboxObjects active; with it, I tried using increment and decrement functions that checked if it could point to the next SandboxObject, but I couldn't get that to work properly because a base class pointer to a derived class acts funky. :/
I'm not looking for exact code implementations, just a proven method for working with the base class of many different derived classes.
Let me know if there's anything I should edit in this question or if there's any more info I could provide.
| 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, Rectangle, or a Decagon.
But iterating using m_primaryObjectPointer++ will not work as you expect: this iteration assumes that you iterate over contiguous objects in an array of SandboxObject elements (i.e. the compiler will use the base type's memory layout to compute the next address).
Instead, you may consider iterating over a vector (or an array if you really want to deal with extra memory management hassle) of pointers.
vector<SandboxObject*> universe;
populate(universe);
for (auto object:unviverse) {
if (object->isActive()) {
auto hb = object -> roughtHitBox();
// do something with that hitbox
}
}
Now managing the objects in the universe can be painful as well. You may therefore consider using smart pointers instead:
vector<shared_ptr<SandboxObject>> universe;
(little demo)
|
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 (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
} else {
return binarySearch(arr, mid + 1, r, x);
}
} else {
return -1;
}
}
| 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 the key is found at depth d, this takes 2d comparisons. The average number of comparisons is twice the average depth of the tree, and is 2 Log2(N) - 1 for a perfect tree (early termination only spares one comparison).
This is to be compared to Log2(N) without equality test. Not counting that when the key is not found, the full depth of the tree is always traversed ! Testing for equality seems a false good idea.
|
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<<"input number %i: ";
cin>>*(str+i);
}
//outputing numbers stored on next 5 addresses starting from 'a'
for(int j =0; j<5;j++)
cout<<"content: "<<*(str+j);
but when i try to store numbers on the next 2 addresses it works fine:
//declariing a variable
int a=0;
// declaring a pointer
int *str;
//assigning 'a' adress to the pointer
str =&a;
//storing numbers on next 2 adrdess starting from 'a' adress
//for(int i =0; i<5;i++){
cout<<"input number %1: ";
cin>>*(str+1);
cout<<"input number %2: ";
cin>>*(str+2);
//}
//outputing numbers stored on next 2 addresses starting from 'a'
//for(int j =0; j<5;j++)
cout<<"content1: "<<*(str+1);
cout<<"content2: "<<*(str+2);
| 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 approach, but see the following commented code describing the differences, i.e. to create array space, then use a pointer to point to the space...
int main(void)//minimum signature of main includes void
{
int a[5] = {0};//array of 5 int
// declaring a pointer
int *str;//int pointer
char in;
char buf[20];
//assigning 'a' address to the pointer
str =&a[0];// point pointer to array
//storing numbers on next 5 address starting from 'a' address
for(int i =0; i<5;i++)
{
//cout<<"input number %i: ";//see comment below code
cout<<"input number: ";
cin >> in;
a[i] = in - '0';//use char to convert input to digit value
}
//outputting numbers stored on next 5 addresses starting from 'a'
for(int j =0; j<5;j++)
{
sprintf(buf, "content is: %d\n", a[j]);//using stdio.h
cout << buf;
}
return 0;
}
An aside:
Some of your stdout streaming calls, eg.
cout<<"input number %i: ";
appear to use format specifiers.
C++ streams don't use format-specifiers like C's printf()-type functions; they use manipulators. reference
|
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 dll files. When an update is available, a zip file is first downloaded and then unpacked into the temp folder. Afterwards, all files are moved from there to the shared application directory.
The problem
The problem is that the updater can only update a few dll files at runtime that are not used by itself, because some are write-protected due to the installer's access.
A solution
Moving the files from the temp folder to the shared application folder must happen after closing the installer. But I don't know how to realize that.
Thanks a lot!
| 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 the main application gets closed and then replace all its files in the main folder. And once your update is finished, delete this temporary copy of the installer with its DLLs.
Note that if you want to overwrite files in Program Files folder, your installer will have to be run with elevated privileges. Google for "runas" command... you will need it when starting your installer with QProcess.
But there may be also other problems. If your first installation was with normal installer, it typically creates some entries in registry and also generates list of files for later uninstall. And if your new versions will contain different files than originally installed version, then your subsequent uninstall may malfunction or may leave some files existing on users' computers. And you certainly do not want this.
And yet another potential problem. You may have running several instances of your application. In that case quitting one instance will still leave the other instances running and hence their files will not be replacable by the installer - it will fail.
So as you can see, these are quire serious aspects to take into account.
How I do it in my software and I suggest you try it too? I prepare one installer file (.exe) with InnoSetup (freeware!). This can be used for first installation as well as for automatic updates. Then if I create a new version and put it on the server, the running main application detects it, downloads the new installer and runs this installer (of course it asks the user if it should proceed). The installer then asks for elevated privileges, asks to close the running application (it usually is closed automatically when starting the installer) and overwrites the existing installation. All this is standard functionality built in the installer created by InnoSetup. And correctly updates the uninstall instructions... It took me several days to set up everything to my needs but it works well. The only "drawback" is that it is not completely silent, it shows some dialogs. But this is no real issue for me. Maybe it is better for the users to see what is happening on their computer...
|
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 append_move() function uses autodeduction of arg1 and then forwards it to the emplace_back() function.
Does the append_forward() function have any advantages over the append_move() function and which function should be preferred?
#include <deque>
#include <string>
#include <utility>
template<typename T>
class List
{
public:
void append_move(T arg1, std::string arg2)
{
list.emplace_back(std::move(arg1), std::move(arg2));
}
template<typename X>
void append_forward(X&& arg1, std::string arg2)
{
list.emplace_back(std::forward<X>(arg1), std::move(arg2));
}
private:
std::deque<std::pair<T, std::string>> list;
};
| 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 object => has to call one more destructor. So, forwarding is more preferable.
However, it makes the API less pretty:
another_list.append_move({"some", "arguments"}); // works and pretty
//another_list.append_forward({"some", "arguments"}); // doesn't compile
another_list.append_forward(Foo{"some", "arguments"}); // works
Overload by hand
So, unfortunately, providing hand-written overloads seems to be the best solution (for the user of your code) out of these three:
void append_overload(T&& t); // TODO actually implement
void append_overload(T const& t) { append_overload(T{t}); }
Emplace
However (once again), if you care about all of this, consider emplacing:
template<typename... As> void append_emplace(As&&... args) {
list.emplace_back(std::forward<As>(args)...);
}
// works and pretty as long as you don't need to pass-construct two arguments
another_list.append_emplace("some", "arguments");
Other overloads
Besides, if you have more append_* overloads, note that forwarding/emplacing versions are less prioritized because of being templates. The choice is yours.
|
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.godbolt.org/z/49hfqnr4f
Which compiler is right here?
| 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 clear what "refers" means in this context, so there is some room for language lawyering. But it's clear that, in general, the mere instantiation of a template to produce a deleted function definition is allowed. [temp.inst]/3.2 also mentions the implicit instantiation of deleted member functions that occurs when class templates are implicitly instantiated. If instantiating a templated entity to produce a deleted function definition were ill-formed, it wouldn't be possible to use class templates like std::atomic that have a deleted copy constructor. Your program merely does explicitly what happens implicitly under those circumstances.
|
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 + two;
ValueInferenceMode value_inf_mode;
auto value_inf = new ValueInference(builder_);
auto lit = value_inf
->AnalyzeConstant(res, value_inf_mode)
->GetValue()
->Clone();
// I'm using `untyped_data` because I can't express arbitrary array types.
// I guess I could use `data<int32>` in this simple case
auto data = lit.untyped_data();
std::cout << ((int32*) data)[0] << std::endl; // prints 3
| 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(computation, {}, nullptr, &profile)
.ConsumeValueOrDie();
data = lit.untyped_data()
|
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 = nullptr;
If I wanted to iterate over every object in m_objects0 until I reached the end, then "jump" to the start of m_objects1 to iterate over it, how would I check if the address of m_pObject sits between the start and end addresses of either array? (my only info being the start and end addresses of each array) Is it even feasible?
The only way I can think of accomplishing it is to somehow convert an address to an int.
| 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 element in m_objects0, you can't check if it is (not) pointing at an element in m_objects1 using address ranges.
However, you can do something like this instead:
ObjectName* m_objects0 = new ObjectName[10];
ObjectName* m_objects1 = new ObjectName[10];
...
ObjectName* object_ptrs[] = {
m_objects0, m_objects0 + 10,
m_objects1, m_objects1 + 10
};
for(int i = 0; i < 4; i += 2)
{
ObjectName* m_pObject = object_ptrs[i];
ObjectName* m_pObjects_end = object_ptrs[i+1];
while (m_pObject != m_pObjects_end)
{
...
++m_pObject;
}
}
...
Online Demo
Which, you could generalize a bit further (ie, if you needed more than 2 arrays) using something this instead:
#include <vector>
#include <utility>
ObjectName* m_objects0 = new ObjectName[10];
ObjectName* m_objects1 = new ObjectName[10];
...
std::vector<std::pair<ObjectName*,ObjectName*>> object_ptrs;
object_ptrs.emplace_back(m_objects0, m_objects0 + 10);
object_ptrs.emplace_back(m_objects1, m_objects1 + 10);
...
for(auto &p : object_ptrs)
{
ObjectName* m_pObject = p.first;
ObjectName* m_pObjects_end = p.second;
while (m_pObject != m_pObjects_end)
{
...
++m_pObject;
}
}
...
Online Demo
|
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 :: ds) = Vect d (Array ds)
but I don't know how to convert the AnyPtr to the Array. I've got as far as
%foreign "C:libfoo,eval"
prim__eval : AnyPtr
export
eval : Array shape
eval = prim__eval -- doesn't type check
EDIT I fixed the element type to Int because it simplified the question without losing the important details.
| 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 in FFI
%foreign "C:libfoo,index_int32"
indexInt : AnyPtr -> Int -> Int
%foreign "C:libfoo,index_void_ptr")
indexArray : AnyPtr -> Int -> AnyPtr
%foreign "C:libfoo,get_array"
getArray : AnyPtr
%foreign "C:libfoo,get_int32"
getInt : Int
rangeTo : (n : Nat) -> Vect n Nat
rangeTo Z = []
rangeTo (S n) = snoc (rangeTo n) (S n)
build_array : (shape : Shape {rank=S _}) -> AnyPtr -> Array shape
build_array [n] ptr = map (indexInt ptr . cast . pred) (rangeTo n)
build_array (n :: r :: est) ptr =
map ((build_array (r :: est)) . (indexArray ptr . cast . pred)) (rangeTo n)
eval : {shape : _} -> Array shape
eval {shape=[]} = getInt
eval {shape=n :: rest} = map (build_array (n :: rest)) getArray
with
extern "C" { // if we're in C++
int32 index_i32(void* ptr, int32 idx) {
return ((int32*) ptr)[idx];
}
void* index_void_ptr(void** ptr, int32 idx) {
return ptr[idx];
}
int32 get_int32();
void* get_array();
}
To pass an array
You can create an array of the appropriate size in C/C++, return a pointer to that array, then do the same as above, recursively assigning each element of the Idris array to the C/C++ array.
|
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]), productName(v[1]), price(v[2]), stock(v[3]) { }
};
with this code i get an error that say no suitable conversion function from "str::string" to "char[20]" exist
| 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) : productId{std::move(v[0])} {}
};
There is a problem with this code though; where do you check the vector has all required elements? Better to make an interface that specifies the four strings a Product is made up of separately:
class Product {
public:
std::string productId;
...
Product(std::string pid, ...) : productId{std::move(pid)}, ... {}
};
But in case you insist on a C/C++ amalgamation;
#include <cassert>
#include <vector>
#include <string.h> // strcpy
class Product {
public:
char productId[20];
char productName[50];
char price[9];
char stock[9];
Product(const std::vector<std::string> &v) {
assert(!v.empty()); // really; v.size() == 4
::strncpy(productId, v[0].c_str(), 19);
productId[19] = '\0';
// ...etc.
}
};
|
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 partly academic pursuit).
The important part of the wrapper structure is here:
template<typename K> struct Wrapper
{
K node; // Element that is wrapped
Wrapper() {};
Wrapper(K impl) : node(impl) {};
Wrapper(const Wrapper<K>& other) : node(other.node) {};
const Wrapper<K> operator[](const char* key);
//... Other stuff
}
My problem is that I am experiencing compile time errors when I attempt to chain multiple [] operations together.
The operator[] overload can be found here:
// Returning by value since I am creating an object that goes out of scope.
// This is okay because the parsing is read only.
template<> const Wrapper<to_wrap> Wrapper<to_wrap>::operator[](const char* key)
{
// It is safe to assume that node[key] produces a to_wrap type.
return Wrapper<to_wrap>(node[key]);
}
With some examples of how it would be called:
template<typename T> bool configure(T config)
{
Wrapper<T> root(config);
// Method A
Wrapper<T> thing = root["field1"]["field2"];
// Method B
Wrapper<T> first_thing = root["field1"];
Wrapper<T> second_thing = first_thing["field2"];
}
The compile-time error occurs if I attempt Method A. Method B yields the result I expect at compile and run-time: a Wrapper object that contains the appropriate node. The error from A is below:
error: conversion from ‘const char’ to non-scalar type ‘Wrapper<to_wrap>’ requested Wrapper<T> thing = root["field1"]["field2"];
This leads me to think there is an issue with how the compiler is inferring type, but I am not entirely sure. Any help/insights would be greatly appreciated!
| 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, and is not permitted to be used on const objects.
|
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's quite big project so just please tell me what could I publish to make this easier for you?
I have it all on git https://github.com/Orpiczy/AcornScanner/compare/fronAndBackJoin if you wish to check it out
I'm using Mingw compiler 8.1.0 64-bit for c++ and Qt 6.2.0, I'm working on windows10
moc_SerialPortManager.cpp
#include <memory>
#include "../../../../../../source/controllers/LowLevelFunctionality/DeviceController/ProfilometerManager/SerialPortManager.hpp"
#include <QtCore/qbytearray.h> ...
logs
E:\Dokumenty\AiR_rok_4\S7\EngineeringThesis\AcornScanner\cm\cm-lib\build\windows\gcc\x64\debug.moc\moc_SerialPortManager.cpp:10: error: ../../../../../../source/controllers/LowLevelFunctionality/DeviceController/ProfilometerManager/SerialPortManager.hpp: No such file or directory
........\AcornScanner\cm\cm-lib\build\windows\gcc\x64\debug.moc\moc_SerialPortManager.cpp:10:10: fatal error: ../../../../../../source/controllers/LowLevelFunctionality/DeviceController/ProfilometerManager/SerialPortManager.hpp: No such file or directory
#include "../../../../../../source/controllers/LowLevelFunctionality/DeviceController/ProfilometerManager/SerialPortManager.hpp"
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| 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. I would assume if you remove the whole build directory and build again you will be fine.
|
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>
#include <string>
// 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;
public:
// friends
friend std::ostream& operator<<(std::ostream& out, const Tuple<T, Args...>& tuply);
public:
Tuple(T&& firsty, Args&&... resty): first(firsty), rest(resty...){};
};
template <class T, class Args...>
std::ostream& operator<<(std::ostream& out, const Tuple<T, Args...>& tuply){
out << tuply.first;
((out << " - " << std::forward<Args>(tuply.rest)), ...);
}
probably Tuple<T, Args...> is illegal, and the line where I am using folding does not make sense. I really cannot find a way to make this work. Can someone help?
| 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 << tuply.first;
if constexpr (sizeof...(Args) == 0) return out;
else return out << " - " << tuply.rest;
}
public:
Tuple(T&& firsty, Args&&... resty)
: first(std::forward<T>(firsty)), rest(std::forward<Args>(resty)...) { }
};
Demo.
|
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 [](const Parent& someone), and inside downcast from Parent to ChildType1.
If I have a function wrapper as std::function<void(const Parent&)>, is there any way to allow it take a function with Parent subclass as parameter, e.g., [](const Child& child){...}, where Child is a subclass of Parent.
Something below does not compile. Online IDE link.
#include <iostream>
#include <functional>
class Parent {
public:
virtual void say() const {
std::cout<<"I am parent"<<"\n";
}
};
class Child: public Parent {
public:
void say() const {
std::cout<<"I am child"<<"\n";
}
};
typedef std::function<void(const Parent&)> Wrapper;
int main() {
Wrapper func=[](const Child& child){ // of course works if Child->Parent
child.say();
};
Child c;
func(c);
return 0;
}
| 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 Parent {
public:
void say() const {
std::cout<<"I am child1"<<"\n";
}
virtual void tell() const {
std::cout<<"This is specific to child1"<<"\n";
}
};
class Child2: public Parent {
public:
void say() const {
std::cout<<"I am child2"<<"\n";
}
};
The following code would also be valid, since Child1 and Child2 derive from Parent:
Child1 y;
Child2 z;
f(y);
f(z);
If you were allowed to assign a function with a child argument instead of a parent argument for your wrapper, you could as well do something like:
Wrapper f=[](const Child1& child){ // if this is legitimate
child.tell(); // then this would be legitimate
};
And you'll easily guess that f(x) and f(z) would not work although the type of f should allow it.
Is there a work-around?
What you can do, but this is something more risky, is to make a wrapper function that takes a Parent argmument and down-casts is to a Child. But I'd not recommend it unless there's no other solution and only with extra-care.
using Wrapper = std::function<void(const Parent&)>;
int main() {
Wrapper func=[](const Parent& parent){
auto child=dynamic_cast<const Child*>(&parent);
if (child)
child->say();
else std::cout<<"OUCH!!! I need a child"<<std::endl;
};
Parent x;
Child c;
func(c);
func(x);
}
Demo
|
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 online.
Internet is drawing a very scary blank
If you were searching literally -D_LNX64i -I -ldl -lm, then it's important for you to learn that prefixing a word with - will exclude pages that contain such word when using most search engines. This is counter productive when you want to find pages that do contain those words. That search would find nothing since you're only excluding search results. You have to add quotes around words that begin with -.
Furthermore, this is an opportunity to learn about common command line option patterns: Double dash such as --option is a long option that can usually be searched easily. Single dash such as -o is a short option. Due to their compact form, these are hard to find using search engines. It's best to go for the documentation or man-page directly.
Options may be followed by a value for the option. Long options are usually separated from the value using whitespace or =, but short options may be followed by the value immediately such as in the case of -D_LNX64i and -ldl. Many values such as these are often project specific and you won't find them in GCC documentation.
|
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 TokenList. I am not sure how to use namespace and still be able to use the range-based for loops. Any pointers would be helpful.
Are the adapters for the Iterator namely: begin, end, ++, *, != correct? Currently, I'm an interested in reading the contents of the LinkedList using range-based for loops.
Coliru
#include <cstdio>
#include <numeric>
#include <algorithm>
struct LinkedList {
double v;
LinkedList *next;
};
struct Iterator {
LinkedList *current;
LinkedList &c;
};
Iterator begin(LinkedList *c) { return Iterator {c, *c}; }
Iterator end(LinkedList *c) { return Iterator {nullptr, *c}; }
Iterator &operator++(Iterator &p) { p.current = p.current->next; return p; }
LinkedList *operator*(Iterator p) { return p.current; }
bool operator!=(Iterator lhs, Iterator rhs) { return (lhs.current != rhs.current); }
int main()
{
LinkedList *node1 = new LinkedList;
LinkedList *node2 = new LinkedList;
LinkedList *node3 = new LinkedList;
node1->v = 1; node1->next = node2;
node2->v = 2; node2->next = node3;
node3->v = 3; node3->next = nullptr;
printf("// C style: iteration\n");
for (auto ptr = node1; ptr; ptr = ptr->next) {
printf("%e\n", ptr->v);
}
auto head = node1;
// make use of begin(), end(), ++, != and *
printf("// Modern C++ style: range based for-loop\n");
for (const auto& it : head) {
printf("%e\n", it->v);
}
delete node3;
delete node2;
delete node1;
return 0;
}
| 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 to broadcast an iterator type. Yours looks like a forward iterator. All end iterators can be equal.
Iterator begin(LinkedList *c) { return Iterator {c, *c}; }
Iterator end(LinkedList *c) { return Iterator {nullptr, *c}; }
These look ok. Just remove *c.
Note that the name does not have to be Iterator. begin/end must be defined in the namespace of LinkedList, but the return type does not have to be.
Iterator &operator++(Iterator &p) { p.current = p.current->next; return p; }
I usually implement this as a member function, and implement both pre and post increment; post is implemented using pre and copy.
LinkedList *operator*(Iterator p) { return p.current; }
This is wrong. It should return *p.current as a double&.
bool operator!=(Iterator lhs, Iterator rhs) { return (lhs.current != rhs.current); }
sure. Also implement == as !(lhs!=rhs).
Look up the forward iterator concept and forward iterator tag. Include the types needed for std::iterator_traits.
For other things to iterate, give the iterator a different name. This can be via a different namespace.
If the thing that differs is just the type of the value, you can make it a template pretty easy. Then you only have to manually write begin/end.
If the name of v also changes, you could use ADL on a GetValue(List*) function you write as a customization point.
Now, being usable in a ranged based for is different than being an iterator. Ranged based for is a tad easier; but the above upgrades you to a full forward iterator, which in turn reduces surprise when you try to use a std algorithm or basically anything else.
How I would write it:
// Iteration::LinkedListIterator<X> assumes that X is a linked list node
// with members ->next and ->value. If it isn't, override the customization
// points GetNextNode and GetListElement in the namespace of X.
namespace Iteration {
template<class List>
List* GetNextNode( List* l ) {
if (!l) return l;
return l->next;
}
template<class List>
decltype(auto) GetListElement( List* l ) {
return l->value;
}
template<class List>
struct LinkedListIterator {
using self=LinkedListIterator;
List *current;
self& operator++(){ current = GetNextNode(current); return *this; }
self operator++(int)&{ auto copy = *this; ++*this; return copy; }
decltype(auto) operator*() {
return GetListElement(current);
}
decltype(auto) operator*() const {
return GetListElement(current);
}
auto operator->() {
return std::addressof(GetListElement(current));
}
auto operator->() const {
return std::addressof(GetListElement(current));
}
friend bool operator==(self const& lhs, self const& rhs) {
return lhs.current == rhs.current;
}
friend bool operator!=(self const& lhs, self const& rhs) {
return lhs.current != rhs.current;
}
using iterator_category = std::forward_iterator_tag;
using value_type = std::decay_t<decltype(GetListElement(std::declval<List*>()))>;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
};
};
struct LinkedList {
double v;
LinkedList *next;
};
// customization point; the name of
double& GetListElement( LinkedList* l ) { return l->v; }
double const& GetListElement( LinkedList const* l ) { return l->v; }
Iteration::LinkedListIterator<LinkedList> begin( LinkedList* l ) {
return {l};
}
Iteration::LinkedListIterator<LinkedList> end( LinkedList* l ) {
return {nullptr};
}
|
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 being passed has many arguments, and writing them into the template brackets of std::function will not be sustainable, as I need to do this often with many similar functions that I pass to this function.
Is there a way to convert a function pointer to a std::function without specifying the return type and arguments, by some form of deducing?
This is what I've tried so far:
template <auto* F>
struct stdfunc {};
template <class Ret, class... Args, auto (*F)(Args...) -> Ret>
struct stdfunc<F>
{
typedef std::function<Ret(Args...)> type;
};
The above code does not work as intended. I found the syntax in this answer. In that case, it wasn't used for this purpose, but surely there is a way to achieve what I'm trying to do using this technique? It seems like all the pieces are there, I just have to put them in the right place.
Am I on the right track?
| 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 is the rule, but I can't find where this is stated.
Edit: I was making a mistake considering that const int& matches const T for T=int&, since templates are more than a mere "macro substitution". In particular, it makes no sense to talk about a const reference (only reference to const). Both the current answers helped me figure it out. Unfortunately, I can only pick one as accepted answer, but thank you both.
| 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 be calculated in the background while my runtime of the code won't be affected?
| 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 seconds, and sleep_until shall be used if you want to wait till some point in time, e.g. to sleep until 11:32:40 time is reached.
In code below you can see that Doing Something 1 is run before start of async thread, then thread starts, which is waiting for 2 seconds, same time Doing Something 2 is called. After that you may wish (if so) to wait for delayed task to be finished, for that you call res.get(), this blocks main thread till async thread is fully finished. Afterwards Doing Something 3 is called.
If you don't do res.get() explicitly then async thread just finishes by itself at some point. Of if program is about to exit while async thread is still running, then program waits for this async thread to finish.
Try it online!
#include <future>
#include <chrono>
#include <thread>
#include <iostream>
#include <iomanip>
int main() {
int some_value = 123;
auto const tb = std::chrono::system_clock::now();
auto Time = [&]{
return std::chrono::duration_cast<std::chrono::duration<double>>(
std::chrono::system_clock::now() - tb).count();
};
std::cout << std::fixed << std::setprecision(3);
std::cout << "Doing Something 1... at "
<< Time() << " sec" << std::endl;
auto res = std::async(std::launch::async, [&]{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Doing Delayed Task... at "
<< Time() << " sec, value " << some_value << std::endl;
});
std::cout << "Doing Something 2... at "
<< Time() << " sec" << std::endl;
res.get();
std::cout << "Doing Something 3... at "
<< Time() << " sec" << std::endl;
}
Output:
Doing Something 1... at 0.000 sec
Doing Something 2... at 0.000 sec
Doing Delayed Task... at 2.001 sec, value 123
Doing Something 3... at 2.001 sec
|
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;
}
Node(object* obj) {
o = obj;
left = nullptr;
right = nullptr;
}
friend class Btree;
private:
object *o;
Node *left;
Node *right;
};
class Btree {
public:
Btree() {
count = 0;
root = nullptr;
}
void deleteNotes(Node *n) {
if (!n) return;
delete n;
delete n->left;
delete n->right;
}
Node* getRoot() {
return root;
}
Node* getLeft(Node* n) {
return n->left;
}
Node* getRight(Node* n) {
return n->right;
}
object* getData(Node *n) {
return n->o;
}
void add(object *obj) {
Node *n = new Node;
n->o = obj;
if (!n) {
return;
}
insertNode(root, n);
}
void insertNode(Node *node, Node *elem) {
if (node == nullptr) node = elem;
else {
if (equal(node->o, elem->o) < 0)
insertNode(node->left, elem);
else insertNode(node->right, elem);
}
}
Node *search(object *obj) {
return searchNode(root, obj);
}
Node *searchNode(Node *node, object *obj) {
if (equal(node->o, obj) == 0) return node;
else {
if (equal(node->o, obj) < 0) {
searchNode(node->left, obj);
}
else {
searchNode(node->right, obj);
}
}
}
void show() {
showNode(root);
}
void showNode(Node *n) {
if (n != nullptr) {
showNode(n->left);
cout << n->o->uploadInString() << "\n";
showNode(n->right);
}
}
void deleteNodes(Node *n) {
if (!n) return;
delete n;
delete n->left;
delete n->right;
}
~Btree() {
deleteNodes(root);
}
private:
int count;
Node *root;
};
I have two datatypes - Integer and Date as children of class "object". I dont't know which details should I write........
| 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 function. The function modifies the value of the variable, then the function quits and the variable is forgotten. The value of root is still nullptr.
There are several ways to solve this problem. Here is one:
Node* insertNode(Node *node, Node *elem) {
if (node == nullptr) return elem;
if (equal(node->o, elem->o) < 0)
node->left = MyInsertNode(node->left, elem);
else node->right = MyInsertNode(node->right, elem);
return node;
}
void add(object *obj) {
...
root = insertNode(root, n);
}
There are other problems. I advise you to work on simpler exercises (such as linked lists) for a while longer, before attempting trees.
|
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++ r.cpp -o ($)/r -D LOCAL -Wall -O2 -fsanitize=undefined
Undefined symbols for architecture arm64:
"_Tp::INT", referenced from:
split(char const*, _Tp*) in r-ebf422.o
"_Tp::fmt", referenced from:
split(char const*, _Tp*) in r-ebf422.o
"_Tp::str", referenced from:
split(char const*, _Tp*) in r-ebf422.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
What's more, when I tried to link some files, similar error happened.
clang++ -shared -o libmystdio.so myscanf.o myprintf.o
Undefined symbols for architecture arm64:
"_Tp::INT", referenced from:
split(char const*, _Tp*) in myscanf.o
split(char const*, _Tp*) in myprintf.o
"_Tp::fmt", referenced from:
split(char const*, _Tp*) in myscanf.o
split(char const*, _Tp*) in myprintf.o
"_Tp::str", referenced from:
split(char const*, _Tp*) in myscanf.o
split(char const*, _Tp*) in myprintf.o
"_Tp::LONG", referenced from:
split(char const*, _Tp*) in myscanf.o
split(char const*, _Tp*) in myprintf.o
"_Tp::LONGLONG", referenced from:
split(char const*, _Tp*) in myscanf.o
split(char const*, _Tp*) in myprintf.o
"_out_buf", referenced from:
myprintf(char const*, ...) in myprintf.o
"_out_idx", referenced from:
myprintf(char const*, ...) in myprintf.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [libmystdio.so] Error 1
In case you wonder what I've written, please click here. However it's not finished,I doubt you would be interested...(I made a few comments and most of them are in Chinese, for my groupmates to read)
And, files in folder code aren't affected. They can be compiled and run normally.Only those in folder code/myIO went wrong.
Here's my clang++ version:
clang++ -v
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: arm64-apple-darwin20.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Thanks for your help in advance!
| 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 then you need to have a definition for them, meaning that there needs to be a single place designated to hold the bytes of memory for these constants in your program.[0]
The normal way to do this is to have a matching utilities.cpp with:
const int _Tp::INT;
const int _Tp::SHORT;
const int _Tp::LONG;
const int _Tp::LONGLONG;
const int _Tp::FLOAT;
const int _Tp::DOUBLE;
const int _Tp::LONGDOUBLE;
but in your case you might want to consider switching to an enum! To do that you would write in utilities.h:
class _Tp {
// [...]
public:
// [...]
enum { INT = 1, SHORT = 2, LONG = 3, LONGLONG = 4,
FLOAT = 10, DOUBLE = 11, LONGDOUBLE = 12 };
then you don't need a utilities.cpp.
[0] There's a special-case for allowing values of integral types to be ODR-used without being defined in narrow circumstances, but I recommend that programmers not rely on it. A non-expert makes a innocent change to the code and gets a confusing link error.
|
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 assignment operator is deleted:
<source>: In function 'int main()':
<source>:23:22: error: use of deleted function 'constexpr A& A::operator=(const A&)'
23 | a2 = std::move(a1);
| ^
<source>:3:7: note: 'constexpr A& A::operator=(const A&)' is implicitly declared as deleted because 'A' declares a move constructor or move assignment operator
3 | class A {
| ^
Compiler returned: 1
Then, after I defined the move assignment operator (not copy assignment operator), it compiled fine. Then, it means compiler is indeed looking for move assignment operator, which I expected. I don't understand why when the move assignment operator is implicitly deleted, the compiler would look for the copy assignment operator. Any idea? Or it is just a bad error message from compiler?
| 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 exist, but it is defined as deleted.
Therefore, the copy assignment operator is the only operator that can be used for that assignment (since constant lvalue references can bind rvalues). The compiler tries to use it but finds out that it is deleted, which triggers that compilation error.
|
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.But the teacher thinks that variables cannot be used in macro definition.
I'm not sure who is right.
I've seen a lot of answers, but what I want to know is not whether it's reasonable to write like this, but what causes the program error in the end.
Add ';' after '#define' Not particularly good, but the compilation can pass. "#define" can also allow variables to appear. So the final error reason is "* a + b"?
| 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 result of the macro expansion is
int h = ((g) * (g));;
That's valid code; the second semicolon marks the end of an empty expression, just as if it had been written
int h = ((g) * (g));
;
That's bad style, of course, and it could cause problems in other contexts, so the "right" way to use that macro would be
int h = calc(g)
That way, the text that results from the macro expansion would only have one semi-colon. But that looks weird, and the macro really shouldn't have that semicolon in it.
As to using variables, again, it depends on what the result of the text substitution is.
#define calc (x) * (x)
void f() {
int x = 3;
int y = calc;
}
That's okay; the code is equivalent to
void f() {
int x = 3;
int y = (x) * (x);
}
On the other hand, this isn't okay:
void f() {
int b = 3;
int y = calc;
}
It doesn't work because there is no x there. So this macro has vary limited usefulness; there are rare situations where it might be appropriate, but, in general, it's a bad idea.
|
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 the above result in cancellation of * with & and will just be int p?
How correct is it if i try to pass reference to pointer of a class object on similar terms?
#include <iostream>
using namespace std;
int gobal_var = 42;
// function to change Reference to pointer value
void changeReferenceValue(int*& pp)
{
pp = &gobal_var;
}
int main()
{
int var = 23;
int* ptr_to_var = &var;
cout << "Passing a Reference to a pointer to function" << endl;
cout << "Before :" << *ptr_to_var << endl; // display 23
changeReferenceValue(ptr_to_var);
cout << "After :" << *ptr_to_var << endl; // display 42
return 0;
}
| 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 declaration, they do not cancel each other out.
An object of type int*& is simply a reference to a pointer to an int.
|
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 space1 {
int a = 10;
void f() {
cout << "in space1 of code 1" << endl;
};
}
namespace {
int x = 20;
void f() {
cout << "in unnamed space" << endl;
}
}
file2: where I accessed the namespace from file1
#include <iostream>
#include "code1.cpp"
using namespace std;
int main() {
space1::f();
cout << space1::a;
cout << x << endl;
f();
return 0;
}
|
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 to the entire translation unit then no, the unnamed namespace cannot be accessed from other translation units.
|
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 place of parameter A.
Sqwiggle error saying B doesn't match with A.
And of course an example is better than a riddle.
class A {};
class B : A { /* some function */ };
class C : A { /* some function */ };
class D : A { /* some function */ };
void fD(A a, void (*fP)(A))
{
for (int i = 0; i < 10; i++)
{
fP(a);
}
}
void PointedFunction(B b)
{
/* Do Something with the B function */
}
void PointedFunction2(C c)
{
/* Do Something with the C function */
}
void PointedFunction3(D d)
{
/* Do Something with the D function */
}
int main()
{
// What i want to do
B b;
fD(b, &PointedFunction);
C c;
fD(c, &PointedFunction);
D d;
fD(d, &PointedFunction);
// But sqwiggle at & saying argument don't match
return 0;
};
Question: How can I use child classes in place of parent class in a function pointer?
I'm prettry sure the cause is because I'm trying to use a child class. Since c++ is very strict about these stuff. But... I don't know how to solve this.
Also, as long as i know, what I'm doing looks very inappropriate to me. Is this like.. legal?
| 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()
{
B b;
fD(b, &PointedFunction);
C c;
fD(c, &PointedFunction);
D d;
fD(d, &PointedFunction);
return 0;
};
Alternatively, if you have specialized methods for B and C, you may use generics instead of a class hierarchy.
class A {};
class B {};
class C {};
template<class T>
void fD(T& instance, void (*fP)(T&))
{
for (int i = 0; i < 10; i++)
{
fP(instance);
}
}
void PointedFunction(B& a)
{
/* Do Something with B */
}
void PointedFunction(C& a)
{
/* Do Something with C */
}
int main()
{
B b;
fD(b, &PointedFunction);
C c;
fD(c, &PointedFunction);
return 0;
};
|
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 within the node?
Exception thrown: read access violation.
it was 0x2.
class Tree {
private:
struct Node {
int* val = nullptr;
Node* right = nullptr;
Node* left = nullptr;
};
Node* root = nullptr;
public:
bool Insert(int* num);
void Empty();
bool isEmpty() const;
};
void Tree::Empty()
{
while (!(root == nullptr)) // Just handling the simplest case for now
{
if (root->left == nullptr && root->right == nullptr)
{
delete root->val; // Read access violation
delete root;
root = nullptr;
break;
}
[...]
}
}
bool Tree::Insert(int* num)
{
Node* insertion = new Node;
int* temp = new int(*num);
insertion->val = temp;
if (root == nullptr)
{
root = insertion;
return true;
}
Node* c_node = root;
while (true)
{
if (*temp == *c_node->val)
{
delete temp;
delete insertion;
return false;
}
if (*temp > *c_node->val)
{
if (c_node->right != nullptr)
{
c_node = c_node->right;
continue;
}
c_node->right = insertion;
return true;
}
if (c_node->left != nullptr)
{
c_node = c_node->left;
continue;
}
c_node->left = insertion;
return true;
}
}
int main()
{
int a = 2;
Tree my_tree;
my_tree.Insert(&a);
my_tree.Empty();
}
I'd appreciate any feedback!
| 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 letting it deal with the value it's storing, so the fragment of Empty you've implemented so far ends up something like this:
void Tree::Empty()
{
while (!(root == nullptr)) // Just handling the simplest case for now
{
if (root->left == nullptr && root->right == nullptr)
{
delete root;
root = nullptr;
break;
}
}
}
As for making this implementation work for a tree with more than one node, I'd probably do it recursively:
void Tree::Empty(Node *node)
{
if (node == nullptr)
return;
Empty(node->left);
Empty(node->right);
delete node;
}
I'd probably also define a dtor for Tree, so the user doesn't need to explicitly call Empty (in fact, I'd probably make Empty private, so the outside world can't call it at all, but that's a separate question).
|
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 both tracks in arrays and check if it possible to get one of them from another using cycling shift of the elements.
I can't understand what the above statement is saying or why it would hold. Also, I found a solution here, but I can't understand what they are doing. Can anyone help me with this? I don't need a complete solution, just an understanding of what is the underlying concept here. Any help is appreciated, thanks !
| 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_barrier because of cyclic nature of circle running.
The second problem - we have two lists/arrays of distances, and should check whether cyclic shift of one list give a list similar to second one. Linked solution just generates all cyclic shifts and compares for indentity. It is simple approach and it works nice for given limits (n=50).
If you need to do the same for large n, quadratic complexity becomes unappropriate, and you would need better approach - for example, double the first list (4,1,2=>4,1,2,4,1,2) and search for occurence of second one in doubled (like substring search)
|
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 fine when linked to a project in Visual Studio 2020 (my main IDE).
The problem is that the instructions only say how to compile RELEASE-build libs, whereas I need to compile DEBUG-build libs so that I can use the debugger in VS2020. So I changed the final commands to try and compile a DEBUG-build. I changed them from:
gn gen out/Release-x64 --args="is_debug=false is_official_build=true skia_use_system_expat=false skia_use_system_icu=false skia_use_system_libjpeg_turbo=false skia_use_system_libpng=false skia_use_system_libwebp=false skia_use_system_zlib=false skia_use_sfntly=false skia_use_freetype=true skia_use_harfbuzz=true skia_pdf_subset_harfbuzz=true skia_use_system_freetype2=false skia_use_system_harfbuzz=false target_cpu=""x64"" cc=""clang"" cxx=""clang++"" clang_win=""c:\deps\llvm"" win_vc=""C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC"" extra_cflags=[""-MT""]"
ninja -C out/Release-x64 skia modules
to:
gn gen out/Debug-x64 --args="is_debug=true is_official_build=false skia_use_system_expat=false skia_use_system_icu=false skia_use_system_libjpeg_turbo=false skia_use_system_libpng=false skia_use_system_libwebp=false skia_use_system_zlib=false skia_use_sfntly=false skia_use_freetype=true skia_use_harfbuzz=true skia_pdf_subset_harfbuzz=true skia_use_system_freetype2=false skia_use_system_harfbuzz=false target_cpu=""x64"" cc=""clang"" cxx=""clang++"" clang_win=""c:\dev\llvm"" win_vc=""C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC"" extra_cflags=[""-MT""]"
ninja -C out/Debug-x64 skia modules
Changes made, being:
"is_debug=false" to "is_debug=true"
"is_official_build=true" to "is_official_build=false"
output directory "Release-x64" to "Debug-x64"
It builds fine, and the lib files are notably bigger, suggesting that they contain debug info. However, when statically linking them into a DEBUG-build project in VS2020, I get lots of this error:
LNK2038 - mismatch detected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value 'MT_StaticRelease'
When I link the DEBUG-build libs into a RELEASE-build project in VS, it builds and runs without errors, suggesting that VS2020 sees the DEBUG-build libs as RELEASE-build libs, despite the changes listed above.
Does anyone have an idea as to what is needed to build these libs in such a way that they work in a DEBUG-build project in VS2020?
Thanks for any help you can provide.
| 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 "-MT" needs to be changed to "-MTd".
The other changes listed in the question are most likely necessary too. Most notably:
"is_debug=false" to "is_debug=true"
"is_official_build=true" to "is_official_build=false"
|
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 continiumTransfunctioneer(const T zoo){return zoo < foo;}
// ...
};
I know that the code will fail to compile if that requirement is not met but the messages from the compiler can be quite verbose-I would like to be able to forewarn the users.
| 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){
if(a[i] == "+" || a[i] == "-" || a[i] == "*" || a[i] == "/"){
int v1 = s.top();
s.pop();
int v2 = s.top();
s.pop();
if(a[i] == "+") {
s.push(v2+v1);
}
else if (a[i] == "-") {
s.push(v2-v1);
}
else if (a[i] == "*") {
s.push(v2*v1);
}
else if (a[i] == "/") {
s.push(v2/v1);
}
}
else{
s.push(atoi(a[i].c_str()));
}
}
return s.top();
}
| 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::string> getSignalNames() // Returns all signal names in the file
std::vector<std::vector<double>> getSignals() // Returns the actual data as M x N matrix (with M rows and N columns)
Using the library in C++ works perfectly and yields the expected results, e.g.:
getSignalNames():
Signal1
Signal2
getSignals():
1 1 1 2
2 1 2 3
Perl programmers asked me to also offer the library to them and I decided to use the wrapper generator SWIG to create bindings. I worked through the tutorial and I was able to successfully set up a minimal working example.
Based on the example, I wrote a complete SWIG interface file for the C++ library. The wrapper generation and build process works smoothly and I can also use getSignalNames() without any problems:
// Perl snippet to read out signal names
my $parserPointer = new waveformparser::ScopeParser("input.file");
$signalNames = $parserPointer->getSignalNames();
foreach my $signalName ( @$signalNames ) {
print "$signalName\n";
}
// Output:
Signal1
Signal2
But, I ran into trouble when using the return value from getSignals():
// Perl snippet to read out the actual signal data
my $parserPointer = new waveformparser::ScopeParser("input.file");
$signalData = $parserPointer->getSignals();
foreach my $rowAsHashRef ( @$signalData ) {
print "reftype: " . reftype($rowAsHashRef) . "\n";
print "keys: " . keys(%$rowAsHashRef) . "\n"
}
// Output:
reftype: HASH
keys: 0
reftype: HASH
keys: 0
As you see, each row is represented as hash in Perl, but there are no keys in the Hash. Nevertheless, when using Perl's Data::Dumper, I can see the correct data type for each row:
my $parserPointer = new waveformparser::ScopeParser("input.file");
$signalData = $parserPointer->getSignals();
print Dumper $signalData;
// Output:
$VAR1 = [
bless( {}, 'waveformparser::vector_1d_double' ),
bless( {}, 'waveformparser::vector_1d_double' )
];
I.e., according to the data dumper, each row consists of several columns (i.e., 'waveformparser::vector_1d_double') which are defined in the SWIG interface file as following:
...
%include "std_vector.i"
%template(vector_1d_double) std::vector<double>;
%template(vector_2d_double) std::vector<std::vector<double>>;
...
My question is now: How can I access elements of this "blessed" (wrapped) vector_1d_double objects in Perl?
I thought, SWIG would provide convenient access methods for such objects. I.e., the underlying C++ data type is just a simple 1d vector of doubles (std::vector<double>).
| 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;
for (const auto &item : vec) {
AV *subarray = (AV *) newAV();
for (const auto &subitem : item) {
av_push(subarray, newSVnv((NV) subitem));
}
av_push(array, (SV*) newRV_noinc((SV*)subarray));
}
$result = newRV_noinc((SV*) array);
sv_2mortal($result);
argvi++;
}
%{
#include "VecVec.h"
%}
%include "VecVec.h"
VecVec.h:
#ifndef VEVEC_H_
#define VECVEC_H_
#include <vector>
class VecVec
{
public:
VecVec() {}
~VecVec() {}
std::vector<std::vector<double>> getSignals();
private:
};
#endif
VecVec.cpp:
#include <string>
#include <vector>
#include <iostream>
#include "VecVec.h"
std::vector<std::vector<double>> VecVec::getSignals()
{
std::vector<std::vector<double>> vec {
{1, 2, 3},
{4, 5, 6}
};
return vec;
}
Then compile with:
perl_include_dir=$(perl -MConfig -e'print $Config{archlib}')"/CORE"
swig -perl5 -c++ -I/usr/include VecVec.i
g++ -fPIC -c VecVec.cpp
g++ -I${perl_include_dir} -c -fPIC -g -o VecVec_wrap.o VecVec_wrap.cxx
g++ -shared -L. VecVec.o VecVec_wrap.o -o VecVec.so
and test the module with test.pl:
use strict;
use warnings;
use Data::Dumper qw(Dumper);
use lib '.';
use VecVec;
my $p = VecVec::VecVec->new();
my $sig = $p->getSignals();
print Dumper($sig);
Output:
$VAR1 = [
[
'1',
'2',
'3'
],
[
'4',
'5',
'6'
]
];
|
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 is used to manage vector of objects r1 and r2. I have a problem with method clone, I'm not sure what type should i return and what should it do.
#include <vector>
using namespace std;
class robot;
//typedef robot* wsk;
using wsk = robot*;
class robot{
protected:
static int l_ob;
public:
static int l_obiektow(){return l_ob;}
virtual ~robot(){ cout << "~robot()" << endl;}
virtual void praca()const=0;
virtual wsk clone()const=0;
};
class r1 : public robot {
public:
r1(){l_ob++;}
r1(const r1& r){l_ob++;}
void praca()const{
cout<<"r1"<<endl;
}
virtual wsk clone()const{
r1 tmp=r1(*this);
return &tmp;
}
~r1(){cout << "~r1()" << endl; l_ob--;}
};
class r2 : public robot {
public:
r2(){l_ob++;}
r2(const r2& r){l_ob++;}
void praca()const{
cout<<"r2"<<endl;
}
virtual wsk clone()const{
r2 tmp=r2(*this);
return &tmp;
}
~r2(){cout << "~r2()" << endl; l_ob--;}
};
class line{
vector <wsk> ve;
public:
line(){}
line(int r):ve(r){
for(size_t i=0; i<ve.size(); ++i )
cout << ve[i] << ", " ;
cout << endl;
}
line(const wsk* b, const wsk* e){
size_t roz=e-b;
for(size_t i=0;i<roz;i++){
ve.push_back(b[i]->clone());
}
}
line(const line& arg){
for(size_t i=0;i<arg.ve.size();i++){
ve.push_back(arg.ve[i]->clone());
}
}
line& operator = (const line& a){
if(this!=&a){
ve.clear();
for(size_t i=0;i<a.ve.size();i++){
ve.push_back(a.ve[i]->clone());
}
}
return *this;
}
void add( const wsk& arg){
ve.push_back(arg);
}
void del(int i){
delete ve[i-1];
ve.erase(ve.begin()+i-1);
}
void delet(){
delete ve[ve.size()-1];
ve.pop_back();
}
void work(){
for(size_t i=0;i<ve.size();i++){
ve[i]->praca();
}
}
~line(){
for(size_t i=0;i<ve.size();i++){
delete ve[i];
}
ve.clear();
cout<<"~line()"<<endl;
}
};
int robot::l_ob=0;
void numberofobj(){
cout << robot::l_obiektow() << endl;
}
int main()
{
{
{ line l1 ; }
{ line l2(5) ; }
cout << "--==**1**==--" << endl;
line lp1, lp2;
lp1.add(new r1);
lp1.add(new r1);
lp1.add(new r2);
lp1.add(new r2);
lp2=lp1;
{
line lp3;
lp3.add(new r1);
lp3.add(new r2);
lp3.add(new r1);
lp3.add(new r2);
lp3.delet();
cout << "--==**2**==--" << endl;
lp3.work();
lp1 = lp3;
cout << "--==**2a**==--" << endl;
}
cout << "--==**3**==--" << endl;
lp1.work();
cout << "--==**4**==--" << endl;
wsk TabAdrRob[] = {new r2, new r2};
line lp4(TabAdrRob, TabAdrRob+2 );
lp4.work();
cout << "--==**5**==--" << endl;
lp4 = lp2;
lp4.work();
cout << "--==**6**==--" << endl;
line lp6(lp1);
lp6.del(1);
lp6.work();
cout << "--==**7**==--" << endl;
delete TabAdrRob[0];
delete TabAdrRob[1];}
numberofobj();
return 0;
}
| 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 .
It's also a good habit to use override in subclasses, so the compiler can emit an error if you override the wrong method. You don't need virtual in subclasses, if subclasses are not meant to be derived from (it's an old way of marking virtual methods in a pre C++-11 era).
So the method becomes:
unique_ptr<robot> clone() const override
{
return make_unique<robot>(new r1(*this));
}
And for the list of robots you could use a vector of smart pointers vector<unique_ptr<robot>>, so that all objects vector are automaticaly destroyed and memory freed.
|
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 should return;
54
54
but my code returns 108
i guess the problem is in this part sum += static_cast<int>(compute - 64); but I don't know the right approach for my problem
for(int x = 1; x <= numofinput; x++){
cout << "Word no. " << x << ": ";
getline(cin,words);
for(auto compute : words){
if(isalpha(compute)){
compute = toupper(compute);
sum += static_cast<int>(compute - 64);
}
}
}
| 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. " << x << ": ";
if(std::string word; std::cin >> word) { // read one word
int sum = 0; // only count the sum for this word
// auto& if you'd like to show it in uppercase later:
for(auto& compute : word) {
// use unsigned char's with the cctype functions:
auto ucompute = static_cast<unsigned char>(compute);
if(std::isalpha(ucompute)) {
compute = static_cast<char>(std::toupper(ucompute));
sum += compute - ('A' - 1); // 'A' - 1 instead of 64
}
}
std::cout << "stats for " << word << '\n'
<< "sum: " << sum << '\n'
<< "avg: " << static_cast<unsigned>(sum) / word.size() << '\n';
}
}
}
|
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 involve a wxGridCellRenderer but I can't seem to wrap my head around how to use it.
I have looked at the grid sample but that did not help me with my problem.
Could anyone nudge me in the right direction, please?
| 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 some existing renderer (e.g. wxGridCellStringRenderer for the cells showing text), override its Draw() method, call the base class method to draw the text and then draw your own border.
|
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[0]; //remove the first entry from the list?
}
I know this code doesn't work but just for the logic so you know what I mean. Also the first entry would be empty then, would it be possible to move all other entries one down so the [0] entry isn't empty anymore?
| 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 advantages of disabling the synchronization?
What can go wrong if synchronization is set to false? Which things should I take into account if I want to disable the synchronization?
| 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 ‘char**’ to ‘const char**’ [-fpermissive]
Details
I'm using an external api that takes a const char* argv[] as input. Based on variables stored in more sane data structures, like std::string, I construct this input variable, but I'm obviously unable to do so correctly.
To be honest, the root of the problem boils down to a single trouble argument which is optional. The following works (somewhat) ..
bool use_optional = false;
std::string optional = "blah";
const char* arr[] = {
"arg1",
(use_optional ? optional.c_str() : ""),
"arg3"
};
The problem with this solution is that I get an empty entry in arr, i.e. {"arg1", "", "arg3"}, and I would very much like to avoid this.
| 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_back(optional.c_str()),
varr.push_back("arg3");
auto arr = &varr[0];
|
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 contiguous data";
// reinterpret some contiguous 10 bytes of s as std::array<char,10>
// Is this UB or valid?
const std::array<char,10>& key=*reinterpret_cast<const std::array<char,10>*>(s+5);
m[key]=1;
}
I would say yes, because char is a POD type that does not require alignment to specific addresses (in contrast to bigger POD types, see https://stackoverflow.com/a/32590117/6212870). Therefore, it should be OK to reinterpret_cast to std::array<char,N> starting at every address as long as the covered bytes are still a subrange of s, i.e. as long as I ensure that I do not have buffer overflow.
Can I really do such reinterpret_cast or is it UB?
EDIT:
In the comments, people correctly pointed to the fact that I cannot know for sure that for std::array<char,10> arr it holds that (void*)&arr==(void*)&arr[0] due to the possibility of padding of the internal c-array data member of the std::array template class, even though this typically should not be the case, especially since we are considering a char POD array. So I update my question:
Can I rely on the reinterpret_cast as done above when I check via static_assert that indeed there is no padding? Of coures the code won't compile anymore on compiler/platform combinations where there is padding, so I won't use this method. But I want to know: Are there other concerns apart from the padding? Or is the code valid with a static_assert check?
| 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-object when using it as a map key. (What you are allowed to do in this case is merely cast it back to the real type, for use with C-like interfaces that require a fixed pointer type but do not actually use the object.)
This access also of course involves a copy; if your goal was to avoid copying at all, just make a
std::map<const char*,int,ten_cmp>
where ten_cmp is a functor type that compares 10 bytes starting from each address (via std::strncmp or std::string_view).
If you do want the map to own its key data, just std::memcpy from the string into a key; compilers often recognize that such temporary “buffers” don’t need to exist independently and actually read from the source in the fashion you hope to do with reinterpret_cast.
|
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 for example:
If I send list below as an input:
[ [1,2,3] , [2,3,4] , [2,3,4] , [4,5,6] ]
I should get [ [1,2,3] , [2,3,4] , [4,5,6] ] as a result from the method.
So, how can I make my nested list contains only unique elements? Are there any efficient way or built-int function in c++ instead of using nested loop?
| 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(); ++iteratorList)
{
cout<<*iteratorList<<", ";
}
cout<<endl;
}
return;
}
void solve()
{
list<list<int>> listOfLists={{1, 2, 3}, {2, 3, 4}, {2, 3, 4}, {4, 5, 6}};
set<list<int>> setOfLists;
for(auto iterator=listOfLists.begin(); iterator!=listOfLists.end(); ++iterator)
{
setOfLists.insert(*iterator);
}
cout<<"Before, listOfLists <- "<<endl;
showContentContainer(listOfLists);
listOfLists.clear();
for(auto item : setOfLists)
{
listOfLists.push_back(item);
}
cout<<endl<<"After, listOfLists <- "<<endl;
showContentContainer(listOfLists);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
Here is the result:
Before, listOfLists <-
1, 2, 3,
2, 3, 4,
2, 3, 4,
4, 5, 6,
After, listOfLists <-
1, 2, 3,
2, 3, 4,
4, 5, 6,
|
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, but found nothing, the closes I could think of is to add an #ifdef, that checks for __cplusplus and fails if does so.
Basically I am looking for a way to inject the /Tc, /Tp, /TC, /TP (Specify Source File Type) commands from the source.
| "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>
#include <chrono>
#include <unistd.h>
void f1(int num)
{
printf("1\n");
while(1)
{
sleep(1);
}
}
void f2(int num)
{
printf("2\n");
while(1)
{
sleep(1);
}
}
int main(int argc, char **argv)
{
std::thread thd_1 = std::thread(f1, 1);
std::thread thd_2 = std::thread(f2, 1);
pthread_setname_np(thd_1.native_handle(), "TCPCall30003Proc");
pthread_setname_np(thd_2.native_handle(), "TCPCall30004Proc");
while(1)
{
sleep(1);
}
return 0;
}
| 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 -1 and with errno set to ERANGE.
You need to shorten your names.
|
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<class POS, class META>
size_t test11( META POS:: *member)
{
/********/
}
Thanks everyone.
| 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;
Name() = default;
Name(std::string pname): name(pname)
{
std::cout<<"Constructor called"<<std::endl;
}
};
template<class POS, class META>
size_t test11( META POS:: *member)
{
//create object of type Name
Name n("Anoop");
//create a pointer to object n
Name *ptrN = &n;
//Now let's use the variable member
std::cout<<ptrN->*member<<std::endl;
return 5;//don't forget to return something since the function has non-void return type
}
int main()
{
//create a pointer to non-static member
std::string Name::*ptrData = &Name::name;
//pass the pointer ptrData to the template function test11<>
test11(ptrData);
}
The output of the program is:
Constructor called
Anoop
which can be verified here.
Explanation
When i wrote
test11(ptrData);
in the above code sample, then using template argument deduction, POS is deduced to be the type Name and META is deduced to be the type std::string.
|
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);
}
}
//Output = 0, 1, 3, 4
this way it crashes somehow instead of removing the current entry from the list.
I know that there are easier methods for the example above, but I simplified it a lot to show what I want to achieve here. The list has to be std::set in my case.
| #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 <- ";
showContentSet(uniqueSet);
cout<<endl;
auto iterator=uniqueSet.find(2);
uniqueSet.erase(iterator);
cout<<"After, uniqueSet <- ";
showContentSet(uniqueSet);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
Here is the result:
Before, uniqueSet <- 0, 1, 2, 3, 4,
After, uniqueSet <- 0, 1, 3, 4,
|
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 = T;
T data;
constexpr S() : data() {}
constexpr explicit S(const T &t) : data(t) {}
template <typename U>
requires
(!is_S<U>) && std::equality_comparable_with<T, U>
friend constexpr bool operator==(const S &s, const U &u) { return s.data == u; }
};
// pre-existing, not hidden friend
template <typename T>
constexpr bool operator==(const S<T> &a, const S<T> &b) { return a.data == b.data; }
The code above seems reasonable, but it doesn't work due to CWG2369's resolution -- which at the moment is only implemented by GCC (>=11). The resolution make the constraint resolution have endless recursion, for instance when using something like this:
template <typename T>
struct wrapper
{
T value;
};
template <typename T, typename U>
requires std::equality_comparable_with <T, U>
constexpr bool operator==(const wrapper<T>& a, const wrapper<U>& b)
{
return a.value == b.value;
}
using SD = S<double>;
static_assert(std::equality_comparable<wrapper<SD>>); // ERROR, recursive constraints
The solution in this case should be to constrain S's operator== in a non-dependent way:
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; }
But now this does not depend on a specific S specialization any more, and therefore will cause redefinition errors:
S<int> s1;
S<double> s2; // ERROR: redefinition of operator==
(Godbolt for all of the above.)
Am I missing something or the above solution for the recursive constraints is fundamentally incompatible with hidden friends?
| 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; }
};
Then have S privately inherit from it:
template <typename T>
struct S : private S_base
{
using type = T;
T data;
constexpr S() : data() {}
constexpr explicit S(const T &t) : data(t) {}
};
Many thanks to Patrick Palka for suggesting this approach.
|
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 conversions" causes a negative number to be converted to an unsigned type, then you trigger [conv.integral]/2, which causes negative numbers to be mapped to "the least unsigned integer congruent to the source integer".
The actual operation is... bitwise. The standard requires that implementations provide some binary representation of signed integers. So a bitwise operation on two signed integers is whatever you get by doing a bitwise operation on that binary representation. Since the actual representation is implementation-defined, the result is allowed to vary based on that representation. However, since the implementation requires that the signed representation's positive values match the corresponding unsigned integer's representation for the same range of numbers, bitwise operations have reliable results for positive values stored in signed integers.
The results are not undefined; you will get a value from them. But the results can be different on different implementations.
C++20 standardized 2's complement signed integer representations (since pretty much every C++ compiler already did this), so the results are consistent across implementations.
|
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?
Any insights would help!
String::String(const char * const pString)
{
Length = strlen(pString)
}
| 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 if there is no null character in the character array pointed to by str.
So it will count the number of characters up to, but not including, the '\0' character. If this character is not encountered within the allocated bounds of the character array, the behavior is undefined, and likely in practice will result in reading outside the bounds of the array. Note that a string literal will implicitly contain a null termination character, in other words:
"hello" -> {'h', 'e', 'l', 'l', 'o', '\0'};
|
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 function, it will return 0 only if failbit or badbit is set. And the operator>> function will set eofbit if it read EOF.
bool convert function: https://www.cplusplus.com/reference/ios/ios/operator_bool/
operator>> function: https://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
In this case, After I enter EOF the bool converter should return 1 because the failbit and badbit aren't set.
Therefore, I use the below program to check what actually happened to the error bit after I enter EOF. And I find out that the failbit will be set after entering EOF!!
So I'm wondering if anyone can help me understand why is failbit set?
#include <iostream>
using namespace std;
int main()
{
int num;
cin >> num;
cout << cin.eof() << " " << cin.fail() << " " << cin.bad() << endl;
return 0;
}
Input: ^Z(on windows using qt creator, non qt c++ project)
Output: 1 1 0
Input: ^D(on windows using qt creator, non qt c++ project)
Output: 0 1 0
| 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 alone is not enough to enter an error state, as there may be usable data in the buffer.
So, for example, imagine a while (cin >> num) loop is used and the user enters 123<Ctrl-Z>.
on the 1st iteration, operator>> reads 1, 2, 3 into the buffer, then encounters Ctrl-Z, so it sets eofbit and stops reading. 123 is then extracted from the buffer into num and the operator exits. At this point, the stream is not yet in an error state. When the stream's bool conversion is evaluated by while, it returns true, allowing the while body to be entered so it can process num.
on the next iteration, operator>> sees eofbit is set, preventing further reading. There is nothing left in the buffer to extract into num, so the operator sets failbit and exits. The stream is now in an error state. When the stream's bool conversion is evaluated by while, it returns false, breaking the while loop.
|
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 namespace std;
int main(){
int n,i;
cout<<"Enter the value of n:";
cin>>n;
int a[n];
for (i=0;i<n;i++){
cout<<"Enter element "<<i<<":";
cin>>a[i];
}
for (int i=0;i<n;i++){
printf("%d",a[i]);
}
leastfreq(a,n);
}
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++){
if(a[i]=temp){
currentct++;
}
if(currentct<leastct){
currentct = leastct;
leastelm = a[j];
}
}
}
return leastelm;
}
| 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++){
if(a[i]=temp){
currentct++;
}
if(currentct<leastct){
currentct = leastct;
leastelm = a[j];
}
}
}
return leastelm;
}
int main(){
int n,i;
cout<<"Enter the value of n:";
cin>>n;
int a[n];
for (i=0;i<n;i++){
cout<<"Enter element "<<i<<":";
cin>>a[i];
}
for (int i=0;i<n;i++){
printf("%d",a[i]);
}
leastfreq(a,n);
}
Solution 2: Added a function declaration for leastfreq before main() as shown below:
#include<iostream>
using namespace std;
//added declaration for `leastfreq`
int leastfreq(int a[],int arrsize);
int main(){
int n,i;
cout<<"Enter the value of n:";
cin>>n;
int a[n];
for (i=0;i<n;i++){
cout<<"Enter element "<<i<<":";
cin>>a[i];
}
for (int i=0;i<n;i++){
printf("%d",a[i]);
}
leastfreq(a,n);
}
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++){
if(a[i]=temp){
currentct++;
}
if(currentct<leastct){
currentct = leastct;
leastelm = a[j];
}
}
}
return leastelm;
}
|
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 your setup code here, to run once:
ClassA clA();
ClassB clB(clA);
};
void loop() {
// put your main code here, to run repeatedly:
};
classA.h:
#ifndef H_CLASSA
#define H_CLASSA
class ClassA
{
private:
/* data */
public:
ClassA();
~ClassA();
};
#endif
classA.cpp:
#include <ClassA.h>
ClassA::ClassA()
{
};
ClassA::~ClassA()
{
};
classB.h
#ifndef H_CLASSB
#define H_CLASSB
#include <ClassA.h>
class ClassB
{
private:
ClassA& _a;
public:
ClassB(ClassA& a);
~ClassB();
};
#endif
ClassB.cpp
#include <ClassB.h>
#include <ClassA.h>
ClassB::ClassB(ClassA &a) :
_a(a)
{
}
ClassB::~ClassB()
{
}
The error is shown in the main here: ClassB clB(clA);
Keine Instanz des Konstruktors ""ClassB::ClassB"" stimmt mit der Argumentliste überein. -- Argumenttypen sind: (ClassA ())
When compiling, the following error is thrown:
src\main.cpp: In function 'void setup()':
src\main.cpp:8:17: error: no matching function for call to 'ClassB::ClassB(ClassA (&)())'
ClassB clB(clA);
^
In file included from src\main.cpp:3:0:
src/ClassB.h:11:5: note: candidate: ClassB::ClassB(ClassA&)
ClassB(ClassA& a);
^~~~~~
src/ClassB.h:11:5: note: no known conversion for argument 1 from 'ClassA()' to 'ClassA&'
src/ClassB.h:6:7: note: candidate: constexpr ClassB::ClassB(const ClassB&)
class ClassB
^~~~~~
src/ClassB.h:6:7: note: no known conversion for argument 1 from 'ClassA()' to 'const ClassB&'
Anyone got an idea about what is going on here? Thank you for any help!
| 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 interpreted as a function declaration called clA which returns a ClassA and requires no arguments (()).
|
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>() == false);
static_assert(std::is_invocable<C, int>() == true);
}
Clang can figure it all out, but GCC seems to have problem with this line:
static_assert(std::is_invocable<C, int>() == true);
C has inherited function call operators.
So GCC's implementation is incorrect or still in progress?
| 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 using-declarations). In the declaration set, type declarations (including injected-class-names) are replaced by the types they designate.
S(N,C) is calculated as follows:
So we are going to build a set of names S(N, C) for the class (also named C in this case)
Moving on to the next paragraph we have
The declaration set is the result of a single search in the scope of C for N from immediately after the class-specifier of C if P is in a complete-class context of C or from P otherwise. If the resulting declaration set is not empty, the subobject set contains C itself, and calculation is complete.
and when we do the lookup of operator() in C, we don't find any, so S(N, C) is empty. We then move on to the next pargraph
Otherwise (i.e., C does not contain a declaration of N or the resulting declaration set is empty), S(N,C) is initially empty. Calculate the lookup set for N in each direct non-dependent ([temp.dep.type]) base class subobject Bi, and merge each such lookup set S(N,Bi) in turn into S(N,C).
So, we are going to go through each base and add it's lookup set into S(N, C) which brings us to the next sub paragraph of
Otherwise, if the declaration sets of S(N,Bi) and S(N,C) differ, the merge is ambiguous: the new S(N,C) is a lookup set with an invalid declaration set and the union of the subobject sets. In subsequent merges, an invalid declaration set is considered different from any other.
So, since there was no operator() in C, but it is in the bases, then we now have invalid declaration set that contains the base class operator()'s. Then we have
he result of the search is the declaration set of S(N,T). If it is an invalid set, the program is ill-formed. If it differs from the result of a search in T for N from immediately after the class-specifier of T, the program is ill-formed, no diagnostic required.
Which tells us that a invalid declaration set is ill-formed, so it is an error and should fail to compile.
The workaround for this is to bring the base class functions into the derived class scope utilizing a using statement like
struct C : A, B {
using A::operator();
using B::operator();
};
Which now brings the name into C which will give you a valid name set that can then be passed to overload resolution for it to pick the correct overload.
|
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 it a list but some reason only count as 1 instead of two when server accept the client 2
this function process the buffer from the client
unsigned __stdcall ClientSession(void* data)
{
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
int iResult;
int iSendResult;
SOCKET ClientSocket = (SOCKET)data;
do
{
// recv buffer from the client
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
{
//iSendResult = send(ClientSocket, recvbuf, iResult, 0);
iSendResult = send_data(ClientSocket, recvbuf, iResult);
if (iSendResult == SOCKET_ERROR)
{
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
//receive from the clients
printf("Message %.*s\n", iResult, recvbuf);
}
else if (iResult == 0)
{
printf("Connection closing... \n");
}
else
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
} while (iResult > 0);
//ACCEPT COMING CLIENTS
while (ClientSocket = accept(ListenSocket, (sockaddr*)&ClientSocket, NULL))
{
printf("Accepted");
if (ClientSocket == INVALID_SOCKET)
{
printf("accept failed with errir: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
unsigned threadID;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ClientSession, (void*)ClientSocket, 0, &threadID);
// try add new clients to a list
list<SOCKET> a;
a.push_back(ClientSocket);
for (SOCKET i : a) {
cout << "Hi I'm\n" << ClientSocket;
cout << "MY SIZE\n" << a.size();
}
}
enter code here
| 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, you have it send to itself:
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
iSendResult = send_data(ClientSocket, recvbuf, iResult);
Sorry to just rephrase, but hopefully that lets you see the issue. There's two main approaches to address this:
Keep most of this, make the list<SOCKET> a; global, add a mutex around it. Change the send_data call to send to all clients in the list a except itself.
Forget the idea of a thread per client. Use non-blocking sockets. Have a mainloop that try to receive from each client and then send to all other clients.
The first approach will look something like:
// lock mutex
for(auto s:a)
{
if (s != ClientSocket)
{
iSendResult = send_data(s, recvbuf, iResult);
// error handling
}
}
// unlock mutex
and
// lock mutex (same one)
a.push_back(ClientSocket);
for (SOCKET i : a) {
cout << "Hi I'm\n" << ClientSocket;
cout << "MY SIZE\n" << a.size();
}
// unlock mutex
|
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 some_func(AnotherClass *(func)()) {
// do something
return another_class_again_obj;
}
void here_comes_another_func() {
some_func(&SomeClass::passed_func);
}
};
However, this code gives error:
cannot initialize a parameter of type 'AnotherClass *(*)()' with an rvalue of type 'AnotherClass (SomeClass::*)()': different return type ('AnotherClass *' vs 'AnotherClass')
Thanks!!
| 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:
// ...
public:
AnotherClass passed_func() {
// do something
return {};
}
AnotherClassAgain some_func(AnotherClass (SomeClass::*func)()) {
(this->*func)();
// do something
return {};
}
void here_comes_another_func() {
some_func(&SomeClass::passed_func);
}
};
|
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_type n);
};
template <class T, class U>
bool operator==(const Allocator<T>&, const Allocator<U>&) {
return true;
}
int main() {
using T = long int;
std::unordered_map<
T,
T,
std::hash<T>,
std::equal_to<T>,
Allocator< std::pair<const T, T> >
> a;
}
It works with vector, but it fails somewhere inside the templates when I use unordered_map.
Can you help me to figure out what I am doing wrong?
Here is the error:
error: no matching constructor for initialization of 'std::__detail::_Hashtable_alloc<Allocator<std::__detail::_Hash_node<std::pair<const long, long>, false>>>::__buckets_alloc_type' (aka 'Allocator<std::__detail::_Hash_node_base *>')
And link to code: https://godbolt.org/z/zje3EGjb6
P.S. If I replace Allocator to std::allocator everything works fine.
| 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 void* hint = 0) {
return nullptr;
}
T* allocate_at_least(size_type n) {
return nullptr;
}
void deallocate(T* p, size_type n) {
}
Allocator() {} // <= this
template <class U>
Allocator(const Allocator<U>&) {} // <= and this
};
template <class T, class U>
bool operator==(const Allocator<T>&, const Allocator<U>&) {
return true;
}
int main() {
using T = long int;
std::unordered_map<
T,
T,
std::hash<T>,
std::equal_to<T>,
Allocator< std::pair<const T, T> >
> a;
}
|
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 file and took a closer look.
#if __cplusplus >= 201703L
std::any value_;
#else
boost::any value_;
#endif
It does appear that c++17 is viable for the latest avro. this indicates to me that it wants to use std::any for anything new than 201703L, which I take as c++17 or newer.
The comment in the post indicated you want to use boost. What am I missing?
ORIGINAL: So I'm working with Apache Avro serialization library. I'm attempting to understand it better by testing the examples it provides. that information can be found here.
Some of the examples work fine, but one issue I'm having is with the generic.cc file. When I compile the generic.cc example via the command line I have no issues. it runs just fine.
g++ generic.cc -lavrocpp -o test.exe
Because I'm using the c++17 standard in my main project, I went back and re-compiled the generic.cc file with c++17
g++ generic.cc -std=c++17 -lavrocpp -o test.exe
it compiles fine, yet throws a segmentation fault. So there's something with the example software that is not formatted properly for the c++17 standard.
I've run a debugger, gdb, and it spit out.
Program received signal SIGSEGV, Segmentation fault.
0x0000555555556e28 in avro::GenericDatum::GenericDatum(avro::GenericDatum const&) ()
So the GenericDatum is part of Avro, without attempting to make changes to the avro library, is there a way for me to use c++17?
as the code throws the segmentation fault at the GenericDatum initialization. The minimum code to reproduce is as follows.
#include <fstream>
#include <complex>
#include "cpx.hh"
#include "avro/Compiler.hh"
#include "avro/Encoder.hh"
#include "avro/Decoder.hh"
#include "avro/Specific.hh"
#include "avro/Generic.hh"
int
main()
{
std::ifstream ifs("cpx.json");
avro::ValidSchema cpxSchema;
avro::compileJsonSchema(ifs, cpxSchema);
std::unique_ptr<avro::OutputStream> out = avro::memoryOutputStream();
avro::EncoderPtr e = avro::binaryEncoder();
e->init(*out);
c::cpx c1;
c1.re = 100.23;
c1.im = 105.77;
avro::encode(*e, c1);
std::unique_ptr<avro::InputStream> in = avro::memoryInputStream(*out);
avro::DecoderPtr d = avro::binaryDecoder();
d->init(*in);
avro::GenericDatum datum(cpxSchema);
return 0;
}
| 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_STANDARD value from 11 to 17.
Obviously, if it's not clear this is for the C++ build of Avro. When building the library for Avro you need to be located in the /Development/aphache_avro/avro-src-1.11.0/lang/c++ directory.
Here you will find the build script build.sh and the CMakeLists.txt file it uses to configure and build the library. on lines 23-25, of CMakeLists.txt, you will be able to change from c++11 to c++17, simply by updating the 11 to 17. Once you do this you can rebuild with the command ./build test, which will first test the build for any errors, you can then build and install with the command sudo ./build.sh install.
This allowed me to rebuild the library with c++17 standard and now I can build my own application linking with the Avro library and building with c++17.
|
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.
Example:
> Ball: (280,70)
Input:
> 2(power) 230(x) 110(y)
Output:
> 180(x) 150(y)
The power means that basically it's going to go X * the distance of the given coordinates. So if it's 1 it would just go to 230 110 but if it's more it will go double, triple, quadruple, etc. times that distance. (external factors should be ignored - friction, etc.)
By now I've managed to create an algorithm to find the line that the ball is going to travel on. But I can't figure out on what point of this line the ball will stop at. Any help will be greatly appreciated!
Also one more thing, I also need to calculate where it would go if it hits the wall of the pool table(pool table is a 2:1 rectangle with given coordinates of edges) and I've also managed to find the line where it would travel on but not the exact point where it will stop.
TL;DR I need to find the point of the line of travel that a billiards ball will stop at.
| 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 factor. For example, here, deltaX = 2*(280-230) or -100, so the destination will be 280 + -100, which equals 180.
To account for the edges, you bound the movement in any direction to be within the 4 edges. You'll have some extra displacement if it strikes the edge. You might think of a bounce as reversing some of the remainder and then recursively call your moveBall function with power 1 when given the location on the edge the ball strikes plus the excess deltaX and deltaY changed in sign appropriately. If moveBall took std::pair<int, int> startingPosition, std::pair<int, int> displacement, int power, if it hits the wall, you'll return moveBall(locationOnEdge, predictedLocationBasedOnExcess, 1). This setup will recursively call itself as many times as is needed until the ball finally finds its ending position (a ball can bounce off edges multiple times).
For example, if you had an edge at x = 200 and y = 100 (meaning your asserted desired output was different), you'd have a remaining deltaX of -20 and deltaY of 50. Since the ball was traveling up and to the left, it will bounce down and to the left. You'd call moveBall with starting location (200, 100), displacement (-20, -50), and power 1.
I'm doing some guesswork here since you didn't define the expected behavior when the ball bounces off an edge.
|
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 WHAT_DO_I_PUT_HERE_FOR_C++_20
#else
#ifdef WHAT_DO_I_PUT_HERE_FOR_C++_17
...
| 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<decltype(f3), int&>); // failed
}
See demo
Why can't a const mutable lambda take a reference argument?
| 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 look at this:
auto const f3 = [](auto&) mutable {};
static_assert(std::is_invocable_v<decltype(f3), int&>); // failed
This is a const object, whose call operator template (because it's a generic lambda) is non-const. So you can't invoke it, for the same reason you can't invoke a non-const member function on a const object in any other context. See this other answer.
Second, it has been pointed out that, nevertheless, this works:
auto const f4 = [](int&) mutable {}; // changed auto& to int&
static_assert(std::is_invocable_v<decltype(f4), int&>); // now ok
This is not a compiler bug. Nor does it mean that what I just said was wrong. f4 still has a non-const call operator. Which you cannot invoke, because f4 is a const object.
However.
There's one other interesting aspect of lambdas that have no capture: they have a conversion function to a function pointer type. That is, we usually think about the lambda f4 as looking like this:
struct __unique_f4 {
auto operator()(int&) /* not const */ { }
};
And, if that were the whole story, const __unique_f4 is indeed not invocable with int&. But it actually looks like this:
struct __unique_f4 {
auto operator()(int&) /* not const */ { }
// conversion function to the appropriate function
// pointer type
operator void(*)(int&)() const { /* ... */ }
};
And there is this rule we have where when you invoke an object, like f(x), you not only consider f's call operators -- those members named operator() -- but you also consider any of f's surrogate call functions -- are there any function pointers that you can convert f to, to then invoke.
In this case, you can! You can convert f4 to a void(*)(int&) and that function pointer is invocable with int&.
But that still means that f4's call operator is not const, because you declared it mutable. And it doesn't say anything about whether you can have mutable lambdas take reference parameters.
|
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 value)
{
...
}
...
}
But when to toPduValue passed bool, and then to buildPduValue passed (quint16) value buildPduValue specializes like <int>?
callstack
debugger shows next expression
| 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 a cast to your ternary expression to cast it to the specific type you want.
Or you could ensure that both possible values of the ternary expression have the same type, so that the overall expression will have the same type.
Or you could use a if statement instead of a ternary expression.
Note that your ternary expression can only have one type; it doesn't have a different type depending on which case was evaluated.
|
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() << "\n";
}
body.hpp:
class Body {
private:
Vec3D pos_;
Vec3D vel_;
double mass_{ 1 };
System* system_{ nullptr };
public:
/*#### Constructors ####*/
Body() noexcept = default;
Body(Vec3D pos, Vec3D vel, double mass, System& system):
pos_(pos), vel_(vel), system_{&system}
{
if (mass <= 0)
throw std::runtime_error("Mass cannot be negative.");
mass_ = mass;
std::cout << "Constructed Body" << "\n";
}
~Body() {std::cout << "Destructed Body" << "\n";}
/*#### Copy/Move ####*/
Body(const Body &) =default;
Body & operator=(const Body &) =default;
Body(Body &&) =default;
Body & operator=(Body &&) =default;
system.hpp:
class System {
private:
std::vector<Body> bodies;
public:
[[nodiscard]] inline
std::vector<Body> get_bodies() const {return bodies;}
inline
void add_body(Body& body)
{
bodies.emplace_back(std::move(body));
}
};
output:
----- Test Body -----
Constructed Body
(1.000000, 1.000000, 1.000000)
Destructed Body
Destructed Body
Destructed Body
I understand that it has to do with system1.add_body(body1); and std::cout << system1.get_bodies()[0].get_pos() << "\n"; but questions are :
How can an object be destructed more times than it has been constructed ?
Is this a performance loss (should I be worried about it on a larger scale) ? If so, how can I work my way around it ?
PS: On a more general manner, I'll be happy to receive advice on my code!
|
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.
And std::vector<Body> get_bodies() const returns a copy of bodies, thus has to make new Body objects using the Body(const Body&) copy constructor, which you have likewise also default'ed and are not logging.
Try the following instead, and you will see a better picture of what is really happening:
class Body
{
private:
Vec3D pos_;
Vec3D vel_;
double mass_{ 1 };
System* system_{ nullptr };
public:
/*#### Constructors ####*/
//Body() noexcept = default;
Body() {
std::cout << "Default Constructor " << static_cast<void*>(this) << "\n";
}
Body(Vec3D pos, Vec3D vel, double mass, System& system)
: pos_(pos), vel_(vel), mass_(mass), system_(&system)
{
...
std::cout << "Conversion Constructor " << static_cast<void*>(this) << "\n";
}
~Body() {
std::cout << "Destructor " << static_cast<void*>(this) << "\n";
}
/*#### Copy/Move ####*/
//Body(const Body &) = default;
Body(const Body &src)
: pos_(src.pos_), vel_(src.vel_), mass_(src.mass_), system_(src.system_)
{
...
std::cout << "Copy Constructor " << static_cast<void*>(this) << "\n";
}
//Body(Body &&) = default;
Body(Body &&src)
: pos_(std::move(src.pos_)), vel_(std::move(src.vel_)), mass_(src.mass_), system_(src.system_)
...
src.mass_ = 0;
src.system_ = nullptr;
...
std::cout << "Move Constructor " << static_cast<void*>(this) << "\n";
}
//Body& operator=(const Body &) = default;
Body& operator=(const Body &rhs) {
if (&rhs != this) {
pos_ = rhs.pos_;
vel_ = rhs.vel_;
mass_ = rhs.mass_;
system_ = rhs.system_;
}
std::cout << "Copy Assignment " << static_cast<const void*>(&rhs) << " -> " static_cast<void*>(this) << "\n";
return *this;
}
//Body& operator=(Body &&) = default;
Body& operator=(Body &&rhs) {
pos_ = std::move(rhs.pos_);
vel_ = std::move(rhs.vel_);
mass_ = rhs.mass_; rhs.mass_ = 0;
system_ = rhs.system_; rhs.system_ = nullptr;
std::cout << "Move Assignment " << static_cast<void*>(&rhs) << " -> " static_cast<void*>(this) << "\n";
return *this;
}
...
};
|
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 play.
I really can't understand why.
audio.hpp
#ifndef AUDIO_HPP
#define AUDIO_HPP
#pragma once
#include <SFML/Audio.hpp>
#include <vector>
#include <string>
enum {SELECTION_SOUND, DEAD_SOUND};
enum {MAIN_THEME_MUSIC, GAME_MUSIC, GAME_OVER_MUSIC};
class Audio
{
public:
Audio();
void setVolumeMusic(const float v);
void setVolumeSound(const float v);
float getVolumeSound() const;
float getVolumeMusic() const;
void playSound(const unsigned int soundExecute);
void stopMusic();
void deleteMusicTheme();
~Audio();
private:
bool m_musicThemeUse;
float m_volumeMusic, m_volumeSound;
std::vector <sf::SoundBuffer> m_buffer;
std::vector <bool> accessMusic, accessSound;
std::vector <sf::Sound> m_sound;
std::vector <sf::Music*> m_music;
std::vector <std::string> m_nameFileMusic, m_nameFileSound;
/*
* m_musicThemeUse : If this variable is equal to "true" then, the main menu music is deleted from memory.
* m_volumeMusic, m_volumeSound : Music/sound volume, it is fixed between 0.f and 100.f.
* m_buffer: vector containing the audio files of the sounds.
* accessMusic, accessSound : bool vector determining whether a music is available for playback or not. Useful when a file is deleted.
* m_sound: vector containing the audio files of the sounds.
* m_music: vector containing the audio files of the musics.
* m_nameFileMusic, m_nameFileSound : vector of string containing the path of the audio files.
*/
};
#endif
The constructor of the Audio class.
Audio::Audio() : m_nameFileMusic{ "data/mainTheme.ogg", "data/game.ogg", "data/gameOver.ogg" }, m_nameFileSound{"data/selectionSound.ogg", "data/dead.ogg" },
m_musicThemeUse(true), m_volumeMusic(0.f), m_volumeSound(100.f)
{
//Fill the values of accessMusic and accessSound to "true"
accessMusic.assign(std::size(m_nameFileMusic), true);
accessSound.assign(std::size(m_nameFileSound), true);
//Loads music files.
for (unsigned int i = 0; i < std::size(m_nameFileMusic); i++)
{
m_music.push_back(new sf::Music);
if (!m_music[i]->openFromFile(m_nameFileMusic[i]))
accessMusic[i] = false;
}
//Set the music files by setting the volume to them and activating repeat when the music files are finished.
setVolumeMusic(m_volumeMusic);
for(unsigned int i = 0; i < std::size(m_music); i++)
if(m_nameFileMusic[i] != "data/gameOver.ogg")
m_music[i]->setLoop(true);
//Load sound files.
const sf::SoundBuffer a;
const sf::Sound b;
for (unsigned int i = 0; i < std::size(m_nameFileSound); i++)
{
m_buffer.push_back(a);
m_sound.push_back(b);
if (!m_buffer[i].loadFromFile(m_nameFileSound[i]))
accessSound[i] = false;
else
m_sound[i].setBuffer(m_buffer[i]);
}
//Fix the volume of the sound files.
setVolumeSound(m_volumeSound);
//If the main menu music file is available then play the music file.
if(accessMusic[0])
m_music[0]->play();
m_sound[0].play();
}
| 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.push_back(in);
}
return Search(arr, in+1, n, t, v);
}
int main(){
int arr[] = {1, 2, 3, 4, 5, 4, 7, 4, 9, 4};
vector<int> v;
v = Search(arr, 0, 10, 4, v);
for(int i = 0; i < v.size(); i++){
cout << v.at(i) << endl;
}
return 0;
}
In this code, I had passed the v as reference, but when I tried passing it without a reference then interestingly both of the codes worked.
#include<bits/stdc++.h>
using namespace std;
vector<int> Search(int arr[], int in, int n, int t, vector<int> v){
if(in == n){
return v;
}
if(arr[in] == t){
v.push_back(in);
}
return Search(arr, in+1, n, t, v);
}
int main(){
int arr[] = {1, 2, 3, 4, 5, 4, 7, 4, 9, 4};
vector<int> v;
v = Search(arr, 0, 10, 4, v);
for(int i = 0; i < v.size(); i++){
cout << v.at(i) << endl;
}
return 0;
}
Can you explain why this happens?
| 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 look like the code does the same thing even though it does not.
|
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 error. The same happens when I swap out the IPs.
#include <iostream>
#include <boost/asio.hpp>
#include <sstream>
#include <thread>
#include <chrono>
#include <boost/random.hpp>
const unsigned int MS_INTERVAL = 100;
enum CMD_ARG
{
PROG_NAME = 0,
LOCAL_IP_1,
LOCAL_IP_2,
REMOTE_IP,
REMOTE_PORT
};
using namespace boost::asio;
using std::string;
using std::cout;
using std::endl;
int main(int argc, char *argv[]) {
if(argc == 5)
{
//Test data initialisation
unsigned int counter = 0;
boost::random::mt19937 randSeed; // seed, produces randomness out of thin air
boost::random::uniform_int_distribution<> randGen(-1000,1000); // Random number generator between -100 and 100
//Initialise ASIO service
io_service io_service;
//socket creation and binding (one per network adapter)
std::cout << "Opening and binding local sockets to " << argv[LOCAL_IP_1] << " and " << argv[LOCAL_IP_2] << std::endl;
ip::tcp::socket socket1(io_service);
ip::tcp::socket socket2(io_service);
socket1.open(ip::tcp::v4());
socket2.open(ip::tcp::v4());
socket1.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_1]), 0));
std::cout << "1/2 done" << std::endl;
socket2.bind(ip::tcp::endpoint(ip::address::from_string(argv[LOCAL_IP_2]), 0));
//Connection to remote end point starting with defining the remote endpoint
std::istringstream iss(argv[REMOTE_PORT]);
unsigned int port = 0;
iss >> port;
ip::tcp::endpoint remoteEndpoint = ip::tcp::endpoint( ip::address::from_string(argv[REMOTE_IP]), port);
std::cout << "Connecting to " << argv[REMOTE_IP] << " on port " << port << std::endl;
socket1.connect(remoteEndpoint);
std::cout << "1/2 done" << std::endl;
socket2.connect(remoteEndpoint);
std::cout << "Ready" << std::endl;
while(1)
{
//Build message
std::ostringstream oss;
oss << counter << "," << randGen(randSeed) << "," << randGen(randSeed) << "," << randGen(randSeed) << std::endl;
//Send message on both interfaces
boost::system::error_code error1, error2;
write(socket1, boost::asio::buffer(oss.str()), error1);
write(socket2, boost::asio::buffer(oss.str()), error2);
//Check errors
if( !error1 && !error2) {
cout << "Sending: " << oss.str() << endl;
counter++;
}
else {
cout << "Error: " << (error1?error1.message():error2.message()) << endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(MS_INTERVAL));
}
}
else
{
std::cout << "Usage: <program> <local IP 1> <local IP 2> <remote server IP> <server's opened port>" << argc << std::endl;
}
return 0;
}
| 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? Is this the simplest way to achieve this?
std::make_unique< decltype(Foo{...}) > (...);
This seems pretty clean but if Foo's constructor takes a lot of arguments it can turn into a pretty ugly line.
| 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 SHGetKnownFolderPath() function. And there are StackOverflow references that explain how to resolve %APPDATA% to its actual path:
How do I get the application data path in Windows using C++?
C++ CreateDirectory() not working with APPDATA
| 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 T> void foo(const T* begin, const T* end) {
...
}
int main() {
std::array<int, 5> arr = { 1, 2, 3, 4, 5 };
foo(arr.begin(), arr.end()); // <-- error!
return 0;
}
|
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 element), with some caveats: not all iterators have all the operations a pointer does. A pointer satisfies the random access iterator concept, so on some implementations the iterator of std::array could be just an alias for the pointer type, but you can't rely on that. E.g. on the same compiler it can be a pointer for the release build, but a full class for the debug build.
The idiomatic way is to write:
template<class It>
void foo(It begin, It end) {
for (auto it = begin; it != end; ++it) {
const auto& elem = *it;
// ..
}
}
Since C++20 we should transition from iterator pairs to ranges:
void foo(std::ranges::range const auto& r) {
for (const auto& elem : r) {
// ...
}
}
|
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::string_view> my_map{
{1, "value1"},
{2, "value2"},
};
I've tried a number of strategies to do this, but I seem to be getting stuck in making a ctor or function that is able to both accept an arbitrary number of elements and also tell the compiler that all the braced entries being passed (e.x. {1, "value1"}) is a pair, otherwise it cannot deduce the type.
For example:
template <typename Key, typename Mapped, typename... Args>
constexpr auto make_map(std::pair<Key, Mapped>&& first, Args&&... args) {
if constexpr (sizeof...(Args) == 0) {
return std::tuple{std::forward<decltype(first)>(first)};
}
return std::tuple_cat(
std::tuple{std::forward<decltype(first)>(first)},
make_map(std::forward<Args>(args)...)
);
}
It seems like I could make a macro that would quickly allow me to make versions of the function for say all arguments up to a reasonable number (say 10-15) but this feels uglier and worse.
Is there a way to do what I want, or do I need to resort to macros or making users annotate each entry with std::pair?
| 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 for deduction to work.
#include <array>
#include <string_view>
#include <utility>
template <typename K, typename V, size_t N>
class MyMap {
public:
using value_type = std::pair<K, V>;
constexpr explicit MyMap(value_type(&&init)[N])
: data_(std::to_array(std::forward<value_type[N]>(init))) {}
const std::array<value_type, N> data_;
};
template <typename K, typename V, size_t N>
constexpr MyMap<K, V, N> MakeMyMap(
typename MyMap<K, V, N>::value_type(&&init)[N]) {
return MyMap{std::forward<typename MyMap<K, V, N>::value_type[N]>(init)};
}
int main(int argc, char* argv[]) {
constexpr std::string_view value_1 = "value1";
constexpr std::string_view value_2 = "value2";
constexpr auto my_map = MakeMyMap<int, std::string_view>({
{1, value_1},
{2, value_2},
});
static_assert(my_map.data_.at(0) == std::make_pair(1, value_1));
static_assert(my_map.data_.at(1) == std::make_pair(2, value_2));
return EXIT_SUCCESS;
}
Note: this is c++20 only because of std::to_array (https://en.cppreference.com/w/cpp/container/array/to_array). But one can easily implement that in c++17
#include <array>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace internal {
template <bool Move = false, typename T, std::size_t... I>
constexpr std::array<std::remove_cv_t<T>, sizeof...(I)> to_array_impl(T (&a)[sizeof...(I)], std::index_sequence<I...>) {
if constexpr (Move) {
return {{std::move(a[I])...}};
} else {
return {{a[I]...}};
}
}
} // namespace internal
template <typename T, std::size_t N>
constexpr std::array<std::remove_cv_t<T>, N> to_array(T (&a)[N]) noexcept(
std::is_nothrow_constructible_v<T, T&>) {
static_assert(!std::is_array_v<T>);
static_assert(std::is_constructible_v<T, T&>);
return internal::to_array_impl(a, std::make_index_sequence<N>{});
}
template <typename T, std::size_t N>
constexpr std::array<std::remove_cv_t<T>, N> to_array(T(&&a)[N]) noexcept(
std::is_nothrow_move_constructible_v<T>) {
static_assert(!std::is_array_v<T>);
static_assert(std::is_move_constructible_v<T>);
return internal::to_array_impl<true>(a, std::make_index_sequence<N>{});
}
|
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:
int main() {
std::cout << abc<int>() << "\n";
std::cout << abc<float>() << "\n";
}
Is that possible?
| 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";
}
Try it yourself!
|
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 into two different variables then store those variables in a vector of pairs. But I've noticed that when I output the pairs from the vector the first letter of the item is missing, and the points are completely off. I've tried to change the point to a char instead of an int, and did the same in the paired vector. Both gave similarly inaccurate/strange outputs. What am I doing wrong here? Thanks guys. Here is the part of my program where I'm trying to store the items/points in a paired vector:
int answer;
int points;
std::string tempName;
std::string name;
std::string item;
std::ifstream inFS;
std::vector<std::string> nameList;
std::vector<std::pair<std::string, int>> pairedList;
std::cout << "Would you like to add points to a member's name? If not, input 0 to look at other options!" << std::endl;
std::cout<< "Otherwise, input 1 to continue to the point system." << std::endl;
std::cin >> answer;
if (answer == 0)
options();
if (answer == 1) {
inFS.open("items.dat");
if (inFS.is_open())
std::cout << "File opened successfully." << std::endl;
while (std::getline(inFS, item)) {
inFS >> points;
pairedList.push_back(make_pair(item, points));
}
if (!inFS.eof())
std::cout << "Not able to reach end of file" << std::endl;
inFS.close();
for (int i = 0; i < pairedList.size(); i++)
std::cout << pairedList[i].first << " " << pairedList[i].second << std::endl;
exit(1);
}
}
| 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{};
while (std::getline(std::cin, item))
{
std::getline(std::cin, points);
std::cout << "item = " << item << ", points = " << std::stoi(points) << "\n";
}
}
|
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 know why it is that such a basic program would be so slow?
Window.cpp:
#include "Window.h"
#include <vector>
#include <iostream>
LPCWSTR title = L"hello";
HWND textfield;
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;
break;
}
textfield = CreateWindowW(L"STATIC", L"Text is here",
WS_VISIBLE | WS_CHILD | WS_BORDER, 20, 20, 300, 25, hWnd, NULL, NULL, NULL);
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Window::Window()
: m_hInstance(GetModuleHandle(nullptr))
{
const wchar_t* CLASS_NAME = L"Kai Window Class";
WNDCLASS wndClass = {};
wndClass.lpszClassName = CLASS_NAME;
wndClass.hInstance = m_hInstance;
wndClass.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.lpfnWndProc = WindowProc;
RegisterClass(&wndClass);
DWORD style = WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU;
std::vector<int> AspectRatio = {1920, 1080};
RECT rect;
rect.left = AspectRatio.at(0)/2;
rect.top = AspectRatio.at(1)/2;
rect.right = AspectRatio.at(0);
rect.bottom = AspectRatio.at(1);
AdjustWindowRect(&rect, style, false);
m_hWnd = CreateWindowEx(
0,
CLASS_NAME,
title,
style,
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
NULL,
NULL,
m_hInstance,
NULL
);
ShowWindow(m_hWnd, SW_SHOW);
}
Window::~Window()
{
const wchar_t* CLASS_NAME = L"Kai Window Class";
UnregisterClass(CLASS_NAME, m_hInstance);
}
bool Window::ProcessMessages()
{
MSG msg = {};
while (PeekMessage(&msg, nullptr, 0u, 0u, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
return false;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return true;
}
Window.h:
#pragma once
#include <Windows.h>
#include <Vector>
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
class Window
{
public:
Window();
Window(const Window&) = delete;
Window& operator = (const Window&) = delete;
~Window();
bool ProcessMessages();
private:
HINSTANCE m_hInstance;
HWND m_hWnd;
};
Main.cpp:
#include <iostream>
#include "Window.h"
int main()
{
std::cout << "Creating Window...\n";
Window* pWindow = new Window();
bool running = true;
while (running)
{
if (!pWindow->ProcessMessages())
{
std::cout << "Closing Window...\n";
running = false;
}
// Render
Sleep(10);
}
delete pWindow;
return 0;
}
| 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;
break;
}
///////////// This should not be here .....
textfield = CreateWindowW(L"STATIC", L"Text is here",
WS_VISIBLE | WS_CHILD | WS_BORDER, 20, 20, 300, 25, hWnd, NULL, NULL, NULL);
/////////////
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
You want to create the label once, not every time the window procedure is called. A good place is in the WM_CREATE handler i.e.
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
textfield = CreateWindowW(L"STATIC", L"Text is here", WS_VISIBLE | WS_CHILD | WS_BORDER, 20, 20, 300, 25, hWnd, NULL, NULL, NULL);
return 0;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
|
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" : "97acbfa7acrbad90adb6578adabd0dcbf80abad43276d79b76f687590390b3ff429"
},
{
"name" : "Henry",
"age" : 42,
"id_hash" : "2acbfa7acrbad90adb6578adabd0dcbf80abad493276d79b76f687590390b3ff429"
},
{
"name" : "Jake",
"age" : 31,
"id_hash" : "facbfa7acrbad90adb6578adabd0dcbf80abad432b76d79b76f687590390b3ff429"
},
{
"name" : "Goku",
"age" : 22,
"id_hash" : "0acbfa7acrbad90adb6578adabd0dcbf80abad43276d79b76f687e590390b3ff429"
}
]
}
Having keys named id_hash within an array named ADMIN_LIST, I want to get the value of each instance of id_hash and store it into a string vector std::vector<std::string> Id_Vector = {};. As simple as that.
The number of Admins varies from json files/objects.... as such a hard-coded predetermined number of key values needed would not be accurate.
Rules
The source of the json data can be streamed from a file, file.json file or a file.txt containing json formatted text.
Any json library can be used (as long as it is c++ friendly)
Any json library used, should please come with a link to it's repository or download site.
The use of for loops is very much allowed.
Loop used in determining amount of key values to store should be dynamic.
Sample Code
#include <iostream>
#include "SomeJSON_Library.h"
#include <string>
#include <vector>
int main()
{
std::vector<std::string> Id_Vector = {};
for(int g = 0; j <= Length_Of_Keys; j++) // Where Length_Of_Keys refers to the dynamic number of instances within a json file/object
{
Id_Vector [j] = FromJson.Array.Keys("id_hash");
}
return 0;
}
Such that a call to any id_hash index would hold relative value gotten from Json File.
Further Usage of Json Value Parsing
#include <iostream>
#include "SomeJSON_Library.h"
#include <string>
#include <vector>
int main()
{
std::vector<std::string> Id_Vector = {};
std::vector<std::string> Admin_Name = {};
for(int j = 0; j <= Length_Of_Keys; j++) // Where Length_Of_Keys refers to the dynamic number of instances within a json file/object
{
Id_Vector [j] = FromJson.Array.Keys("id_hash"); // Get value of key "id_hash"
Admin_Name [j] = FromJson.Array.Keys("name"); // Get value of key "name"
}
// For the sake of confirming implemented code
for(int x = 0; x <= Length_Of_Keys; x++) // Length_Of_Keys or sizeof(Id_Vector[0]) / sizeof(Id_Vector)
{
std::cout << "Id Hash of Admin " << Admin_Name[x] << "is " << Id_Vector[x] << "\n";
}
return 0;
}
Output
Id Hash of Admin Luke is acbfa7acrbad90adb6578adabdff0dcbf80abad43276d79b76f687590390b3ff429
Id Hash of Admin Sasha is 97acbfa7acrbad90adb6578adabd0dcbf80abad43276d79b76f687590390b3ff429
Id Hash of Admin Henry is 2acbfa7acrbad90adb6578adabd0dcbf80abad493276d79b76f687590390b3ff429
Id Hash of Admin Jake is facbfa7acrbad90adb6578adabd0dcbf80abad432b76d79b76f687590390b3ff429
Id Hash of Admin Goku is 0acbfa7acrbad90adb6578adabd0dcbf80abad43276d79b76f687e590390b3ff429
The truth is I'm certain that it's as simple as I've obviously laid it out to be, but I can't for the life of me figure out which Json library or function can do this. I know it's something like FromJsonObj.GetValueFromKey("id_hash"); but I haven't had any luck figuring out how to go about this.
I really wish I knew of a library with such a straight forward syntax call as FromJsonObj.GetValueFromKey();.
I just need an actual C++ code that implements the illustrated desired result.
Help me out and please don't mark as DUPLICATE....Thanks.
| 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 array T a[n] be used in function B somehow without passing the arguments to B explicitly?
Is it called function forwarding or perfect forwarding in C++?
I'm aware that creating attempting to create a static array out of a variable int isn't standard C++ and some compilers support it. My main question is can the arguments be used in B without passing?
| 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 opposite of what you are asking for.
|
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)
{
printf("\n Socket creation error \n");
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "0.0.0.0", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
}
std::vector<char> buffer = {0};
buffer.reserve(1024);
read(sock, buffer.data(), 1024);
Since the server response size is variable in length but not more than 1024 so that why the size of buffer fixed to 1024.
Now since I am receiving variable size response I want to know the size of the buffer.
I tried following:
std::cout<<sizeof(buffer)<<" "<<buffer.size();
and output is
sizeof(buffer) = 32
buffer.size() = 1
if I try 1024 value that comes up with the some garbage values which is as follow:
for (int i = 0; i < 1024; i++)
{
std::cout<<buffer[i];
}
output:
[{"xmin": 95, "ymin": 147, "ymax": 276, "xmax": 193}, {"xmin": 42, "ymin": 353, "ymax": 488, "xmax": 123}, {"xmin": 85, "ymin": 19, "ymax": 166, "xmax": 145}, {"xmin": 1, "ymin": 254, "ymax": 327, "xmax": 107}, {"xmin": 393, "ymin": 281, "ymax": 419, "xmax": 463}, {"xmin": 379, "ymin": 316, "ymax": 457, "xmax": 442}]������� ��!� )��0� 8��?� G��N� V��]� e��l� t��{� ����� ����� ����� ����� ���Ʈ ή�ծ ݮ��� ����� ����
So is there any way we can get exact size of response?
| 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) while output data (e.g. byte buffers, struct pointers, etc) is passed through pointers passed as parameters. Because C exposes raw program memory it means that you can easily crash your process (or worse...) if you attempt to use an invalid pointer or if the library you're using indicates it's in an invalid-state or terminal-state (e.g. eof on file streams).
POSIX's read function returns the number of bytes actually written into the buffer.
https://man7.org/linux/man-pages/man2/read.2.html
On success, the number of bytes read is returned (zero indicates
end of file), and the file position is advanced by this number.
It is not an error if this number is smaller than the number of
bytes requested; this may happen for example because fewer bytes
are actually available right now (maybe because we were close to
end-of-file, or because we are reading from a pipe, or from a
terminal), or because read() was interrupted by a signal.
Note this part:
this may happen for example because fewer bytes are actually available right now
...which means you need to call read in a loop until it returns zero.
Like so:
using std::vector<char>; // Consider using `std::Array` instead as it's a fixed-size buffer.
//
const size_t bufferLength = 1024;
vector<char> buffer(/*n:*/ bufferLength);
char* bufferPtr = buffer.data();
size_t totalRead = 0;
while( totalRead < bufferLength )
{
char* bufferPtrOffset = bufferPtr + totalRead;
ssize_t bytesRead = read( /*fd:*/ sock, /*buffer:*/ bufferPtrOffset, /*count:*/ bufferLength - totalRead );
if( bytesRead < 0 )
{
// TODO: Error condition. Throw an exception or something.
}
else if( bytesRead == 0 )
{
break;
}
else
{
totalRead += bytesRead;
}
}
|
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); // r can be a value like 14
void show();
};
BankDeposit::BankDeposit(int p, int y, float r) {
principal = p;
years = y;
interestRate = r;
returnValue = principal;
for (int i = 0; i < y; i++) {
returnValue = returnValue * (1 + interestRate);
}
}
BankDeposit::BankDeposit(int p, int y, int r) {
principal = p;
years = y;
interestRate = float(r)/100;
returnValue = principal;
for (int i = 0; i < y; i++) {
returnValue = returnValue * (1+interestRate);
}
}
void BankDeposit::show() {
cout << endl << "Principal amount was " << principal
<< ". Return value after " << years
<< " years is "<<returnValue << endl;
}
int main() {
BankDeposit bd1, bd2, bd3;
int p, y;
float r;
int R;
// bd1 = BankDeposit(1, 2, 3);
// bd1.show();
cout << "Enter the value of p y and R" << endl;
cin >> p >> y >> R;
bd2 = BankDeposit(p, y, R);
bd2.show();
return 0;
}
Why removing or commenting out the code in line number 12 is giving error in running the code?
But as I know that we are making our own constructor so what is the need of having default constructor in the code? Also not including the default constructor in the code is why giving the errors?
| 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 reading the error message. you can learn about constructers here : here
|
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, it has not been constructed
return ptr;
}
//.....
}
class B derived from an abstract base class A, and how can i use singleton in class B?
| 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, you implement your method1, so that AImplement becomes not abstract.
Now, you can create AImplement inside class B.
And do not derive B from A.
|
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 class A, B is not be declared, but I want class A be defined earlier than class B, how should i do? I was thought it may need forward declaration, but it seems not this reason...
| 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;
}
};
// and now, as B implementation is visible, you can use it.
// To do this, you can define the previously declared method:
void A::method() { B::method(); }
int main()
{
class A a;
a.method();
}
Hint: Please never use using namespace std
|
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, TRUE);
timeout(0);
for ( int t=0;; t++ )
{
int ch = getch();
if (ch == 'q')
{
break;
}
uint8_t temp = t;
std::cout<<temp;
}
}
When this code is run, I want it to generate sound until I press "q" on my keyboard, after which I want the program to quit. This works fine; however, there is a noticeable delay between pressing the keyboard and the program quitting. This is not due to a delay with ncurses, as when I run the program without std::cout<<temp; (i.e. no sound generated), there is no latency
Is there a way to amend this? If not, how are real-time responsive audio programs written?
Edits and suggestions to the question are welcome. I am a novice to ALSA, so I am not sure if any additional details are required to replicate the bug.
| 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 forces the real time audio loop to adjust synthesis as required.
In this gtkIOStream example, a full duplex audio class is created. The process method in the class can have your synthesis computation compiled in. This will handle the playback of your sound using ALSA.
To get user input, one possibility is to add a threaded method to the class by inheriting the FullDuplexTest class, like so :
class UIALSA : public FullDuplexTest, public ThreadedMethod {
void *threadMain(void){
while (1){
// use getchar here to block and wait for user input
// change the memory in FullDuplexTest to indicate a change in variables
}
return NULL;
}
public:
UIALSA(const char*devName, int latency) : FullDuplexTest(devName, latency), ThreadedMethod() {};
};
Then change all references to FullDuplexTest to UIALSA in the original test file (you will probably have to fix some compile time errors) :
UIALSA fullDuplex(deviceName, latency);
Also you will need to call UIALSA::run() to make sure the UI thread is running and listening for user input. You can add the call before you call "go" :
fullDuplex.run(); // start the UI thread
res=fullDuplex.go(); // start the full duplex read/write/process going.
|
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],n,num,mid,l=0,h=n-1,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;i++)
{
cin>>arr[i];
}
cout<<"Enter the number to be searched.\n";
cin>>num;
while(l<=h)
{
mid=(l+h)/2;
if(arr[mid]==num)
{
cout<<"Number found at "<<mid<<"\n";
break;
}
if(arr[mid]>num)
{
h=mid-1;
}
else
{
l=mid+1;
}
}
if(l>h)
{
cout<<"Number not found.\n";
}
return 0;
}
| 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;i++)
{
cin>>arr[i];
}
cout<<"Enter the number to be searched.\n";
cin>>num;
l = 0;
h = n-1;
while(l <= h)
{
mid = (l+h)/2;
if(arr[mid] == num)
{
cout<<"Number found at index "<<mid<<"\n";
break;
}
if(arr[mid] > num)
{
h = mid-1;
}
else
{
l = mid+1;
}
}
if(l > h)
{
cout<<"Number not found.\n";
}
return 0;
}
|
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::cout << static_cast< short >( std::any_cast< int >( x ) );
#endif
}
| 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;
string mystring;
float x = 1051.0;
for (int i = 0; i < 20; i++)
{
mybits = bitset<16>(x*32);
mystring = mybits.to_string<char, string::traits_type, string::allocator_type>();
cout << x << "\t" << "mystring: " << mystring << '\n';
x += 0.1;
}
return 0;
}
However, the result is this:
1051 mystring: 1000001101100000
1051.1 mystring: 1000001101100011
1051.2 mystring: 1000001101100110
1051.3 mystring: 1000001101101001
1051.4 mystring: 1000001101101100
1051.5 mystring: 1000001101101111
1051.6 mystring: 1000001101110011
1051.7 mystring: 1000001101110110
1051.8 mystring: 1000001101111001
1051.9 mystring: 1000001101111100
1052 mystring: 1000001101111111
1052.1 mystring: 1000001110000011
1052.2 mystring: 1000001110000110
1052.3 mystring: 1000001110001001
1052.4 mystring: 1000001110001100
1052.5 mystring: 1000001110001111
1052.6 mystring: 1000001110010011
1052.7 mystring: 1000001110010110
1052.8 mystring: 1000001110011001
1052.9 mystring: 1000001110011100
There are problems at fractional part. For example 1051.5 should be 1000001101110000, not 1000001101101111 (the fractional part is wrong due to the nature of float variable). There are also problems at 1052.0 and 1052.5. How can I fix it?
|
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*10 + i)*32/10));. This will produce correct results until something beyond i = 317,169. (Remove x += 0.1; from the loop; x is used as an unchanging value in this new formula.)
The problem stems from the fact that .1 is not representable in a binary-based floating-point format, so the source text 0.1 is converted to 0.1000000000000000055511151231257827021181583404541015625 (when IEEE-754 “double precision” is used for double), and each addition of that to x (in x += 0.1;) performs an operation that rounds the ideal real-arithmetic sum to the nearest value representable in double, and, since x is float, rounds that again to the nearest value representable in float (typically the IEEE-754 “single precision” format).
The desired value for the fixed-point number in iteration i is 1051 + i/10, converted to a fixed-point encoding with five fraction bits. The encoding of this is (1051 + i/10) • 32 rounded to the nearest integer. So the value we want to compute is round((1051 + i/10) • 32), where “round” is the desired round-to-integer function (such as round-to-nearest-ties-to-even, or round-to-nearest-ties-to-away).
We can write this as a fraction as ((1051•10 + i)•32) / 10. The advantage of this is that (1051•10 + i)•32 is an integer and can be calculated exactly, with either integer or floating-point arithmetic, as long as it stays within the bounds of exact arithmetic. (For the “single precision” format, this means (1051•10 + i)•32 ≤ 224, so i ≤ 219−10,510 = 513,778.)
Then the only unwanted rounding is in the division. That division occurs immediately before the desired rounding to an integer, so it is not exacerbated by any other operations. So we can compute the fixed-point encoding as std::round((x*10 + i)*32/10) and only be concerned with the rounding error in the division by ten. (To use std::round, include <cmath>. Note that std::round rounds halfway cases away from zero. To use the current floating-point rounding mode, usually round-to-nearest-ties-to-even by default, use std::nearbyint.)
A rounding in the division will cause an error in the final result only if it causes a value of (x•10 + i)*32/10 whose fraction portion is not exactly ½ to become a value with a fraction of exactly ½. (The converse, causing a value with a fraction of ½ to become a value with some other fraction does not occur because a value with a fraction of ½ is exactly representable in binary floating-point, so no rounding occurs. An exception would be if the number were so large it would be beyond the point where any fractions are representable. However, this does not occur for the IEEE-754 “single precision” format unless the value is also overflowing the Q10.5 format.)
Assuming round-to-nearest is in use, any computed result is at most ½ ULP from the real-arithmetic result. (“ULP” stands for “Unit of Least Precision,” the effective position value of the lowest bit in the significand given the exponent scaling.) Therefore, (x•10 + i)*32/10 can round to a value with fraction ½ only if its fraction portion is at most ½ ULP from that value. The nearest the fraction portion of any such quotient can be to ½ without being ½ is 4/10 or 6/10. The distance of these from ½ is 1/10. So as long as 1/10 exceeds ½ ULP, std::round((x*10 + i)*32/10) produces the desired result.
For numbers in [219, 220), the ULP of the “single precision” format is 2−4 = 1/16, which is less than 1/10. Therefore, considering only non-negative i, as long as (x*10 + i)*32/10 < 220, the result is correct. For x = 1051, this gives us (1051•10 + i)•32/10 < 220 ⇒ i < 317,170.
Thus we can use mybits = bitset<16>(std::round((x*10 + i)*32/10)); up until i = 317,169, at least.
|
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 documentation doesn't mention? Here is a minimal repro-example.
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <dwrite.h>
#pragma comment(lib, "dwrite")
IDWriteFactory* pDWriteFactory = NULL;
IDWriteFontCollection* pFontCollection = NULL;
IDWriteFontFamily* pFontFamily = NULL;
IDWriteFont* pFont = NULL;
IDWriteFontFace* pFontFace = NULL;
int main()
{
HRESULT hr = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, &IID_IDWriteFactory, &pDWriteFactory);
if (FAILED(hr))
return -1;
hr = pDWriteFactory->GetSystemFontCollection(&pFontCollection, FALSE);
if (FAILED(hr))
return -2;
UINT index = 0;
BOOL exists;
hr = pFontCollection->FindFamilyName(L"Arial", &index, &exists);
if (FAILED(hr))
return -3;
hr = pFontCollection->GetFontFamily(index, &pFontFamily);
if (FAILED(hr))
return -4;
UINT count;
count = pFontFamily->GetFontCount();
if (FAILED(hr))
return -5;
DWRITE_FONT_METRICS metrics;
for (int i = 0; i < count; i++)
{
hr = pFontFamily->GetFont(i, &pFont);
pFont->GetMetrics(&metrics);
printf("%d %d %d %d\n", metrics.designUnitsPerEm, metrics.ascent, metrics.descent, metrics.lineGap);
}
return 0;
}
| 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 simulate an
italic font.
So you'll get 'Oblique', 'Narrow Oblique', 'Bold Oblique', 'Narrow Bold Oblique', 'Black Oblique' simulated fonts for a total of 14.
If italic is available, oblique should not be used.
You can check that using the IDWriteFontFace::GetSimulations method, on each font, which will get you back DWRITE_FONT_SIMULATIONS_OBLIQUE for those fonts.
|
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.godbolt.org/z/va9vcsEed
Is it right to assume just a bug in MSVC?
Overall, does the presence or deletion of the destructor change any rule of the aggregate initialization?
| 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 private or protected direct non-static data members (11.9),
(1.3) — no virtual functions (11.7.3), and
(1.4) — no virtual, private, or protected base classes (11.7.2).
If to execute this statement in MS VS 2019
std::cout << std::is_aggregate_v<B> << '\n';
then the output will be 1.
On the other hand, the default constructor is defined as deleted (the C++ 20 Standard, 11.4.5.2 Default constructors) if
(2.8) — any potentially constructed subobject has a type with a
destructor that is deleted or inaccessible from the defaulted default
constructor.
But in the provided example there is no such sub-object.
So it seems it is a compiler bug of MS VS 2019.
|
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 either.
So it would be great to call some API from my program to start perf event collection for the fragment of code I'm interested in, and then stop collection after the code finishes.
It's not really an option to run the code in a loop because there is a ~30 seconds initialization phase and 10 seconds measurement phase and I'm only interested in the latter.
| 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 either a pair of pathnames of FIFO files (named pipes) or a pair of file descriptors. The first file is used for issuing commands to enable or disable all events in any perf process that is listening to the same file. The second file, which is optional, is used to check with perf when it has actually executed the command.
There is an example in the manpage that shows how to use this option to control a perf process from a bash script, which you can easily translate to C/C++:
ctl_dir=/tmp/
ctl_fifo=${ctl_dir}perf_ctl.fifo
test -p ${ctl_fifo} && unlink ${ctl_fifo}
mkfifo ${ctl_fifo}
exec ${ctl_fd}<>${ctl_fifo} # open for read+write as specified FD
This first checks the file /tmp/perf_ctl.fifo, if exists, is a named pipe and only then it deletes it. It's not a problem if the file doesn't exist, but if it exists and it's not a named pipe, the file should not be deleted and mkfifo should fail instead. The mkfifo creates a named pipe with the pathname /tmp/perf_ctl.fifo. The next command then opens the file with read/write permissions and assigns the file descriptor to ctl_fd. The equivalent syscalls are fstat, unlink, mkfifo, and open. Note that the named pipe will be written to by the shell script (controlling process) or the process being profiled and will be read from the perf process. The same commands are repeated for the second named pipe, ctl_fd_ack, which will be used to receive acknowledgements from perf.
perf stat -D -1 -e cpu-cycles -a -I 1000 \
--control fd:${ctl_fd},${ctl_fd_ack} \
-- sleep 30 &
perf_pid=$!
This forks the current process and runs the perf stat program in the child process, which inherits the same file descriptors. The -D -1 option tells perf to start with all events disabled. You probably need to change the perf options as follows:
perf stat -D -1 -e <your event list> --control fd:${ctl_fd},${ctl_fd_ack} -p pid
In this case, the program to be profiled is the the same as the controlling process, so tell perf to profile your already running program using -p. The equivalent syscalls are fork followed by execv in the child process.
sleep 5 && echo 'enable' >&${ctl_fd} && read -u ${ctl_fd_ack} e1 && echo "enabled(${e1})"
sleep 10 && echo 'disable' >&${ctl_fd} && read -u ${ctl_fd_ack} d1 && echo "disabled(${d1})"
The example script sleeps for about 5 seconds, writes 'enable' to the ctl_fd pipe, and then checks the response from perf to ensure that the events have been enabled before proceeding to disable the events after about 10 seconds. The equivalent syscalls are write and read.
The rest of the script deletes the file descriptors and the pipe files.
Putting it all together now, your program should look like this:
/* PART 1
Initialization code.
*/
/* PART 2
Create named pipes and fds.
Fork perf with disabled events.
perf is running now but nothing is being measured.
You can redirect perf output to a file if you wish.
*/
/* PART 3
Enable events.
*/
/* PART 4
The code you want to profile goes here.
*/
/* PART 5
Disable events.
perf is still running but nothing is being measured.
*/
/* PART 6
Cleanup.
Let this process terminate, which would cause the perf process to terminate as well.
Alternatively, use `kill(pid, SIGINT)` to gracefully kill perf.
perf stat outputs the results when it terminates.
*/
|
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 any way I can get the a and b variables from the corresponding element(s)? (ex: std::cout << items[0]->a;)
class Item
{
public:
int id;
Item(int id) { this->id = id; }
};
class ItemTypeA : public Item
{
public:
int a;
ItemTypeA(int a, int id) : Item(id) { this->a = a; }
};
class ItemTypeB : public Item
{
public:
int b;
ItemTypeB(int b, int id) : Item(id) { this->b = b; }
};
int main()
{
std::vector<std::shared_ptr<Item>> items;
items.push_back(std::make_unique<ItemTypeA>(2, 0));
items.push_back(std::make_unique<ItemTypeB>(3, 1));
std::cout << items[0]->// I wanna print the a variable but it only lets me print the ID;
return 0;
}
| 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;
ItemTypeA(int a, int id) : Item(id) { this->a = a; }
void Print(std::ostream& os) override { Item::Print( os ); os << a << std::endl; }
};
class ItemTypeB : public Item
{
public:
int b;
ItemTypeB(int b, int id) : Item(id) { this->b = b; }
void Print(std::ostream& os) override { Item::Print( os ); os << b << std::endl; }
};
int main()
{
std::vector<std::shared_ptr<Item>> items;
items.push_back(std::make_unique<ItemTypeA>(2, 0));
items.push_back(std::make_unique<ItemTypeB>(3, 1));
for ( auto& el: items ) { el->Print(std::cout); }
}
|
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>)
std::cout << "std::string with value " << std::quoted(arg) << '\n';
else
static_assert(always_false_v<T>, "non-exhaustive visitor!");
}, v);
But instead, I figured I could also just use
if(auto x = std::get_if<int>(&v))
std::cout << " is int " << *x << std::endl;
else if(auto x = std::get_if<std::string>(&v))
std::cout << " is String " << *x << std::endl;
else
std::cout << "non-exhaustive visitor!" << std::endl;
The only disadvantage that I see right now is that I do not have a static message for when my matching is not exhaustive. Is there any other advantage of using std::visit that I am not seeing?
|
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...) -> Overload<Fs...>;
static_assert(visit(Overload{
[](int) { return "int"; },
[](std::string_view) { return "string_view"; },
[](auto) { return "something else"; }
}, std::variant<int, std::string_view, bool, double>{42}) == "int"sv);
Also, visit might compile to faster code because of only one type match, but it should be checked whether the ifs-version gets its multiple matches optimized away.
Update
As @Quentin mentioned in a comment,
unlike the manual if ladders, an overload will be selected not if it is an exact match, but merely if it is callable (via conversions if needed)
If there is an overload where conversions are undesirable, this technique should help:
[](std::same_as<int> auto) {} // C++20
or
template<typename T, typename U> using SameAs = std::enable_if_t<std::is_same_v<T, U>>;
[](auto t, SameAs<decltype(t), int>* = 0) {} // C++17
|
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 I suppose I did something wrong in JS.) What did I do wrong?
//Server handling
void mainserver(){
String POS = server.arg("VOLM");
number = 100 - POS.toInt();
delay(15);
displayrendering();
server.send(200, "text/plane","");
}
void returnpos() {
String s = String(number, DEC);
server.send(200, "text/plain", s); //Send web page
}
<div class="slidecontainer">
<input type="range" min="-100" max="0" value="0" class="slider" id="myrange" onchange="send()">
<p>Value : <span id="demo">0</span></p>
</div>
<script>
function send() {
fetch('/setPOS?' + new URLSearchParams({
VOLM: 100 - document.querySelector("#myrange").value,
}))
document.querySelector("#demo").innerText = document.querySelector("#myrange").value;
}
const interval = setInterval(function() {
fetch('/getPOS').then(function(response) {
return response.text().then(function(text) {
document.querySelector("#demo").innerHTML = text;
document.querySelector("#myrange").value = text;
});
});
}, 100);
</script>
```
| 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-transform: rotate(180deg); /* IE 9 */
transform: rotate(180deg);
}
|
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 increment, notifies more then one waiter only if increment is more than one.
libc++ counting_semaphore::acquire:
void acquire()
{
auto const __test_fn = [=]() -> bool {
auto __old = __a.load(memory_order_relaxed);
return (__old != 0) && __a.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed);
};
__cxx_atomic_wait(&__a.__a_, __test_fn);
}
Waits for count to be non-zero, and tries to CAS it with decremented value.
Now please look into the following 3-threaded case:
counting_semaphore<10> s;
T1: { s.acquire(); /*signal to T3*/ }
T2: { s.acquire(); /*signal to T3*/ }
T3: { /*wait until both signals*/ s.release(1); s.release(1); }
Initially:
__a == 0
(desired parameter passed as 0, any attempt to acquire would block)
Timeline
T1: enters wait
T2: enters wait
T3: fetch add 1 & returns 0, now __a == 1
T3: (0 < 0) is false, so notify_one happens
T1: unblocks from wait
T3: fetch add 1 & returns 1, now __a == 2
T3: (0 < 1) is true, so no notification
T1: loads 2
T1: cas 2 to 1 successfully
T1: returns from acquire
T2: still waits despite __a == 1
Does this look like a valid deadlock?
why I am asking here instead of reporting the issue?
I reported the issue quite some time ago, no reply so far.
I want to understand if there's indeed a deadlock or I am missing something.
| 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 value happened to be 1, all of the threads blocked on this condition must be notified. So calling notify_one is wrong, unless the implementation of notify_one always unblocks all waiting threads. Which would be an... interesting implementation of that function.
Even if you change notify_one to notify_all, that doesn't fix the problem. The logic of the condition basically assumes that thread notification should only happen if all of the threads (logically) notified by a previous release have escaped from their acquire calls. The standard requires no such thing.
|
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 will allocate new memory to the type of the piece.
What I tried:
for (int i = 0; i < NUM_ROWS; i++)
{
for (int j = 0; j < NUM_COLUMN; j++)
{
if (this->_board[i][j] != nullptr)
{
this->_board[i][j] = new typeid(*(other->_board[i][j]));
}
}
}
What command can I use instead of typeid(*(other->_board[i][j])), that will return a (King) type (for example), and I will be able to allocate memory for it?
thank you.
| 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::vector), then return a list of trapezoids(points).
| 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 line hits a vertex, you emit appropriate trapezoids and remove edges that have become inactive and introduce any new active edges.
Convert all edges to directed edges (they need to have direction so that you can handle holes correctly)
Sort the edges by increasing minimum x coordinate (you could do it by y either, but assuming that x is increasing from left to right in your diagram this is the correct choice for your case). For edges with the same minimum x coordinate use the y coordinate to order them. For example, in the diagram you showed it looks like they sorted from top to bottom. Whether that is increasing or decreasing y depends on your coordinate system.
Set the scan-line to the first vertex and introduce and edges that touch the scan-line
Advance the scan line to the next vertex. It's usually helpful to keep the value of the previous scan-line available.
Emit any trapezoids. The emitted trapezoids will all be between the previous scan-line and the current one. And the vertices will be where the current or previous scan-line intersects and edge.
Remove any edges that are now to left of your scan-line. (For example, in the diagram, when the scan-line is at vertex 2, you would remove the edge from 0-2)
Merge in any new edges.
While there are edges remaining go to step 4.
I'm glossing over some awkward details here. You may need to "grid" the output trapezoids depending on your application and you have to be quite careful with the floating point portions of the calculations.
If you can find code that does polygon rasterization it can often be adapted to do this. In that case you alter the code for calculating the edge intersections at every x or y coordinate to only those at vertices. Another place to look would be for open source EDA packages. This algorithm is needed to prepare chip design data for mask preparation, but since you used the term "fracture" maybe you knew this already ;-)
|
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(positive)
{
}
Integer operator+(const Integer a) const
{
if (positive && a.positive)
return Integer(i + a.i);
else if (positive && !a.positive)
return Integer(i - a.i);
else if (!positive && a.positive)
return Integer(a.i - i);
else
return Integer(-i - a.i);
}
friend std::ostream& operator<<(std::ostream& out, const Integer& i)
{
if (!i.positive)
out << "-";
out << i.i;
}
};
int main()
{
Integer a1(2u);
Integer a2(3u, false);
std::cout << a2 + a1 << std::endl;
}
And when i run it, it shows :
4294967295
| 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
rep stosq
call _start
jmp $
The Kernel.cpp had:
extern "C" void _start() {
return;
}
One of the comments in the video shows that for C++ a different name, _Z6_startv is
created.
So to try out I modified my Kernel.cpp as:
extern void _Z6_startv() { return; }
And also modified the ExtendedProgram.asm by replacing _start with _Z6_startv but the linker complained,
/usr/local/x86_64elfgcc/bin/x86_64-elf-ld: warning: cannot find entry symbol _start; defaulting to 0000000000008000
then I tried,
Kernel.cpp
extern "C++" void _Z6_startv() { return; } // I didn't even know wut i was doin'
And linker complained again.
I did try some other combinations & methods, all ending miserably, eventually landing here on Stack Overflow.
So, the question:
How to compile the function as a C++ function and link it to assembly?
| 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 a C program where no mangling happen so _start stay _start which means you do not need to change anything from the code you initialy showed.
or if you want to remove the extern "C"
what you want to do is:
[extern _Z6_startv]
Start64bit:
mov edi, 0xb8000
mov rax, 0x1f201f201f201f20
mov ecx, 500
rep stosq
call _Z6_startv
jmp $
|
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(int led[])
{
for (size_t i = 0; i < LEN(led); i++) {
digitalWrite(led[i], HIGH);
}
}
if I try this way, it won't work. I would like it to be like that. But I couldn't find anything about it on the internet. ...:
in the Arduino sketch:
RS.phase_an(RS.ampelRot, RS.ampelGelb, ..... ); <--- is there a way to do it like that?
what amazes me is that it works this way:
int p_an [5] = {RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb};
...................
RS.phase_an (p_an);
does anyone have a suggestion?
| 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 function to know the real length of that array. I don't know how LEN() is defined, but chances are high that it doesn't works well in your code.
A safer and more practical alternative is to use a vector<int> instead:
#include <iostream>
#include <vector>
using namespace std;
void f(const vector<int>& a){
for (int i=0; i<a.size(); i++) {
cout<<a[i]<<" ";
}
cout<<endl;
}
int main() {
vector<int> test={1,2,3,4};
f(test);
f({1,2,3,4});
return 0;
}
In this case, you can pass your multiple values between bracket in the function call (e.g. ({RS.ampelRot, RS.ampelGelb, RS.ampelGruen, RS.rot, RS.gelb})and C++ will automatically convert it to a vector.
|
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));
cout << "a: " << a << "\n";
cout << a.length();
return 0;
}
| 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.
* @param __out [OUT] The output iterator.
* @param __first [IN] The start of the string to search.
* @param __last [IN] One-past-the-end of the string to search.
* @param __e [IN] The regular expression to search for.
* @param __fmt [IN] The format string.
* @param __flags [IN] Search and replace policy flags.
*
* @returns __out
* @throws an exception of type regex_error.
*/
template<typename _Out_iter, typename _Bi_iter,
typename _Rx_traits, typename _Ch_type,
typename _St, typename _Sa>
inline _Out_iter
regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last,
const basic_regex<_Ch_type, _Rx_traits>& __e,
const basic_string<_Ch_type, _St, _Sa>& __fmt,
regex_constants::match_flag_type __flags
= regex_constants::match_default)
{
return regex_replace(__out, __first, __last, __e, __fmt.c_str(), __flags);
}
Referencing this write-up at cppreference.com, this seems to be implementing the first overload, the one that takes a std::string for the replacement string, by calling its c_str() and then calling the 2nd overload, the one that takes a const char * parameter, for the actual implementation. And that explains the observed behavior. I can't find anything that requires this approach.
Stepping further into the actual implementation:
auto __len = char_traits<_Ch_type>::length(__fmt);
__out = __i->format(__out, __fmt, __fmt + __len, __flags);
So, it determines the length of the replacement string and passes the replacement string, as a beginning and an ending iterator, into format().
This seems like it should be the other way around, with __fmt preserved as a std::basic_string, and passing iterators directly derived from it into format().
|
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 core-cpp set.
I've tried a few permutations, but this one seems the most "correct"
#ifdef _DEBUG
template<typename T>
constexpr void MY_VERY_SPECIAL_ASSERT(T x, const std::string &msg) {
assert(x && msg);
}
#else
template<typename T>
constexpr void MY_VERY_SPECIAL_ASSERT(T x, const std::string &msg) { }
#endif
But of course, it doesn't want to compile. Specifically, there's no logical-and overload for "T" and string, which kind of makes sense. You'd think it'd just always return true, right?
Anyway, if anyone has any pointers here, I'm happy to learn more about templating. =)
| 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 work
assert(x && msg.empty()); // Should work. The string won't be displayed when an assertion fails, though.
}
But this wouldn't do what one could think it would, anyway.
assert(x && msg);
Will always result in the message "Assertion failed: x && msg" being displayed.
You can use this instead:
assert ( false or !"message" );
#ifndef _DEBUG
# define SPECIAL_ASSERT(...) ()
#else
# define SPECIAL_ASSERT(COND, MSG) (assert(COND or! MSG))
#endif
SPECIAL_ASSERT( 1 == 0, "One isn't zero." );
|
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"+(user input number)}
| 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::function<int()>> functions = {
{"step001", &Step001},
{"step002", &Step002},
};
// Get user input
int StepNumber = 1;
// Lookup the function and call it.
auto kv = functions.find("step00" + std::to_string(StepNumber));
assert(kv != functions.end());
auto &function = kv->second;
function();
}
|
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 this errors? Can please someone that has android kit on Ubuntu already set, tell me which compilers is using and which paths are for the compilers?
I will add more information for the current compilers or kits if needed.
| 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 up in the following way:
Download the Qt online installer. Login and DO NOT choose individual packages, install Qt for desktop and Qt for mobile (check the last 3 options). This will install Qt 6 + QtCreator
Run QtCreator after everything finishes (+1.2Gb download). Go to Tools>Options>Devices>Android. Check that Java SDK is ok. On the Android section, choose "Set up Android". Accept all licenses.
This is what you should see in the end:
|
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 a = A<4>();
for (auto x : a.arr)
std::cout << x << '\n';
}
Is this just old advice (maybe pre-C++17 advice?) or am I missing something because it seems to me I can just do the following:
constexpr std::array<int, 4> get_ary() {
std::array<int, 4> ary = {};
for (int i = 0; i < 4; ++i) {
ary[i] = i;
}
return ary;
}
int main() {
constexpr auto ary = get_ary();
static_assert(ary.size() == 4, "The length should be 4!");
}
|
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 examples are allowed.
The std::array example won't work pre-C++17. There's no issue with returning, but there is an issue with using the non-constexpr operator[].
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.