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 |
|---|---|---|---|---|
72,370,627 | 72,372,732 | error C2106: '=': left operand must be l-value when trying to change value from function | I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list.
I have a function that returns the data in the first node.
I want to be able to change it using queue1.front() = 3;. However, I am getting
lvalue required as left operand of assignment
error while compiling
Node class
template<class T> class Node
{
public:
Node(const T& t);
Node(const Node&) = default; // Copy Constructor set to default
Node& operator=(const Node&) = default; // Assignment operator set to default
T getData();
private:
T m_data;
Node* m_nextNode;
};
template<class T> Node<T>::Node(const T& t)
{
this->m_data = t;
this->m_nextNode = nullptr;
}
template<class T> T Node<T>::getData()
{
return this->m_data;
}
Queue class
template<class T> class Queue
{
public:
static const int DEFAULT_FIRST_INDEX = 0;
static const int SIZE_EMPTY = 0;
Queue();
Queue(const Queue&) = default; // Copy Constructor set to default
Queue& operator=(const Queue&) = default; // Assignment operator set to default
T front();
private:
Node<T>* m_head;
Node<T>* m_tail;
int m_size;
};
template<class T>
T Queue<T>::front()
{
if (this->m_size == Queue<T>::SIZE_EMPTY)
{
throw Queue<T>::EmptyQueue();
}
return this->m_head->getData();
}
| The member functions
T Node::getData() ...
T Queue<T>::front() ...
returning a copy of the member m_data, which is an r-value temporary. In order to work with assignment, you need non-const l-value reference qualified T. Hence, the compiler error.
Therefore, you need the following fix:
template<class T> class Node
{
public:
T& getData()
// ^^
{
return this->m_data;
}
const T& getData() const; // you might also need
// ^^^^^^^^^ ^^^^^
};
template<class T> class Queue
{
public:
T& front()
// ^^
{
// ....
return this->m_head->getData();
}
const T& front() const; // you might also need
// ^^^^^^^^ ^^^^^
};
|
72,371,911 | 72,372,473 | How is incrementing and dereferencing the iterator faster than incrementing a separate variable and indexing it into the array? | Why is the following:
for (auto & x : vec) { /* do stuff with x */ }
faster than
for (int i = 0; i < v.size(); ++i) { /* do stuff with v[i] */ }
As my title said, I was told that incrementing and dereferencing the iterator faster than incrementing a separate variable and indexing it into the array, but don't understand why?
What exactly is happening that makes it faster?
I tried to step through and see what was happening and this is what I came up with
// pseudo instructions
// iterator
increment iterator
e.g., if the object is 3 integers you would increment the iterator
by 12
dereference this iterator
// pseudo instructions
// array
increment array index
add 1 to index counter
multiply by size of object
e.g., if the object is 3 integers, you multiply by 12
dereference the array
Iterating through an array seems rather trivial. You are just doing the following:
[offset + index * size] ; An array takes this form in assembly
Which would look something like this if you have an array of integers
[rbp - 16 + rdi * 4] ; rbp - 16 is the offset
; rdi is the index
; 4 is the size of the integer
The array iteration seems rather trivial, so I don't understand how dereferencing an iterator is faster.
| The only way it MAY be faster, at least in unoptimized code is because you call size() member function at beginning of every iteration and it's really depends on container and type of iterator it uses. Otherwise using iterators for array-like container is same as using pointer arithmetics and which order is faster depends on optimization. Also it would help if i would be of appropriate type size to not confuse compiler by different width of values.
Range-based for loop got more invalidation issues than index-based though if you're in process of modifying same container. Because it coded in this way:
The range-based for statement
for ( for-range-declaration : for-range-initializer ) statement
is equivalent to
{
auto &&__range = for-range-initializer ;
auto __begin = begin-expr ;
auto __end = end-expr ;
for ( ; __begin != __end; ++__begin ) {
for-range-declaration = *__begin;
statement
}
}
As you see, iterators for begin and end of range are evaluated before loop and any actions taken upon the range which invalidates them would invoke an UB.
If we speak of generic idea of container and not just std::vector, for some containers operator[] may be way more expensive than iterator increment. Only a few number of standard containers have constant cost of operator[] and in case of views\ranges its cost is generally larger, non-constant or non-linear. Cost of incrementing iterators tends to be constant or linear. Costs are usually declared or can be found out during performance tests.
So main issue is not performance but correctness of code, and use of range-based for loop suggests that range wasn't changed in it. It makes harder to cause such change deliberately because all that you have access to is a reference or a copy of an element. An attempt to do so would be obvious, it would be some usage of original range. It also saves from boilerplate code of begin-expr/end-expr.
In common for-loop calling size in i < v.size() may suggest that size() could change during execution. If it's true and happens in middle of loop's body, you may find out that index is out of bound from that point.
When reviewing code not knowing author of code, If I look for source of such change, every such loop is a suspect in detected bug or crash on out-of-bound access from the moment I saw its first line followed by some non-transparent code.
|
72,372,117 | 72,372,353 | How can I retrieve the return value of pclose when the unique_ptr is destroyed? | As @user17732522 pointed out that the deleter of std::unique_ptr is supposed to be callable with exactly one pointer as argument.
How can I retrieve the return value of pclose when the unique_ptr is destroyed?
This code snippet does not compile,
#include<memory>
#include<iostream>
#include<string>
#include<cstdio>
int ExecCmd(const std::string& cmd, std::string& output)
{
int ret = 0;
{
std::unique_ptr<FILE, void(*)(FILE*, int*)> pipe(popen(cmd.c_str(), "r"), [](FILE* file, int* ret_ptr){
if(NULL==file)
{
*ret_ptr = -1;
}
else
{
*ret_ptr = pclose(file);
}
});
}
return ret;
}
int main()
{
}
Whereas this code snippet below compiles.
#include<memory>
#include<iostream>
#include<string>
#include<cstdio>
int ExecCmd(const std::string& cmd, std::string& output)
{
int ret = 0;
{
std::unique_ptr<FILE, void(*)(FILE*)> pipe(popen(cmd.c_str(), "r"), [](FILE* file){
if(NULL==file)
{
}
else
{
pclose(file);
}
});
}
return ret;
}
int main()
{
}
Here is what the compiler complains about the former code snippet:
In file included from /opt/compiler-explorer/gcc-11.3.0/include/c++/11.3.0/memory:76,
from <source>:1:
/opt/compiler-explorer/gcc-11.3.0/include/c++/11.3.0/bits/unique_ptr.h: In instantiation of 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = _IO_FILE; _Dp = void (*)(_IO_FILE*, int*)]':
<source>:20:27: required from here
/opt/compiler-explorer/gcc-11.3.0/include/c++/11.3.0/bits/unique_ptr.h:357:63: error: static assertion failed: unique_ptr's deleter must be invocable with a pointer
357 | static_assert(__is_invocable<deleter_type&, pointer>::value,
| ^~~~~
/opt/compiler-explorer/gcc-11.3.0/include/c++/11.3.0/bits/unique_ptr.h:357:63: note: 'std::integral_constant<bool, false>::value' evaluates to false
/opt/compiler-explorer/gcc-11.3.0/include/c++/11.3.0/bits/unique_ptr.h:361:24: error: too few arguments to function
361 | get_deleter()(std::move(__ptr));
| ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~
I tried this code snippet to acquire the return value, but it does not compile:
#include<memory>
#include<iostream>
#include<string>
#include<cstdio>
int ExecCmd(const std::string& cmd, std::string& output)
{
int ret = 0;
{
std::unique_ptr<FILE, void(*)(FILE*)> pipe(popen(cmd.c_str(), "r"), [&ret](FILE* file){
if(NULL==file)
{
ret = -1;
}
else
{
ret = pclose(file);
}
});
}
return ret;
}
int main()
{
}
Could anybody shed some light on this matter?
| Since you can only provide a custom deleter which can be callable with exactly one pointer as argument, you can not have the lambda with two arguments in it as deleter.
Your lambda with capture will also not work, as it can not be converted to a pointer to a function (i.e. only stateless lambdas can be converted to free function pointers type)
How can I retrieve the return value of pclose when the std::unique_ptr is destroyed?
Using lambda
int ExecCmd(const std::string& cmd, std::string& output)
{
int ret = 0;
const auto deleter = [&ret](FILE* file) { ret = file ? pclose(file) : 0; };
{
std::unique_ptr<FILE, decltype(deleter)> pipe(popen(cmd.c_str(), "r"), deleter);
}
return ret;
}
See a demo
|
72,372,253 | 72,372,341 | cannot find the nanosleep function when cross compile configure | I use toolchain from here, then extract to gcc11_arm_armv7_none_gnueabihf,
below is command:
export ASFLAGS='-march=armv7-a -fPIC -fstack-protector -Wall -fno-omit-frame-pointer --sysroot=gcc11_arm_armv7_none_gnueabihf/arm-none-linux-gnueabihf/libc -no-canonical-prefixes -Wno-builtin-macro-redefined -D__DATE__=redacted -D__TIMESTAMP__=redacted -D__TIME__=redacted -g3'
export CFLAGS='-march=armv7-a -fPIC -fstack-protector -Wall -fno-omit-frame-pointer --sysroot=gcc11_arm_armv7_none_gnueabihf/arm-none-linux-gnueabihf/libc -std=c99 -no-canonical-prefixes -Wno-builtin-macro-redefined -D__DATE__=redacted -D__TIMESTAMP__=redacted -D__TIME__=redacted -g3'
export CXXFLAGS='-march=armv7-a -fPIC -fstack-protector -Wall -fno-omit-frame-pointer --sysroot=gcc11_arm_armv7_none_gnueabihf/arm-none-linux-gnueabihf/libc -std=c++11 -no-canonical-prefixes -Wno-builtin-macro-redefined -D__DATE__=redacted -D__TIMESTAMP__=redacted -D__TIME__=redacted -g3'
export LDFLAGS='-lstdc++ -Wl,-z,relro,-z,now -pass-exit-codes -lm -Wall --sysroot=gcc11_arm_armv7_none_gnueabihf/arm-none-linux-gnueabihf/libc -lpthread'
export AR=gcc11_arm_armv7_none_gnueabihf/bin/arm-none-linux-gnueabihf-gcc-ar
export CC=gcc11_arm_armv7_none_gnueabihf/bin/arm-none-linux-gnueabihf-gcc
export CXX=gcc11_arm_armv7_none_gnueabihf/bin/arm-none-linux-gnueabihf-gcc
export LD=gcc11_arm_armv7_none_gnueabihf/bin/arm-none-linux-gnueabihf-ld
./configure
......
......
checking if nanosleep requires any libraries... configure: error: cannot find the nanosleep function
I can find nanosleep function in gcc11_arm_armv7_none_gnueabihf/arm-none-linux-gnueabihf/libc/usr/include/time.h, but it's a extern declaration, do I need pass something to compiler to let it know where to find nanosleep definition?
| nanosleep requires _POSIX_C_SOURCE >= 199309L feature macro as specified by man nanosleep.
Try adding #define _POSIX_C_SOURCE 199309L before #include <time.h>.
|
72,372,495 | 72,372,601 | Not able to load texture using DSA | My code works if i don't use DSA to create texture.
This is how i am creating texture using DSA.
My opengl version is 4.6
unsigned int loadTexture(char const* path)
{
unsigned int textureID;
// glGenTextures(1, &textureID);
glCreateTextures(GL_TEXTURE_2D, 1, &textureID);
int width, height, nrComponents;
unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glTextureParameteri(textureID, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(textureID, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTextureParameteri(textureID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTextureParameteri(textureID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureSubImage2D(textureID, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, data);
glGenerateTextureMipmap(textureID);
stbi_image_free(data);
}
else
{
stbi_image_free(data);
}
glBindTextureUnit(0, textureID);
return textureID;
}
| You have to create the texture storage with glTextureStorage2D. e.g.:
glCreateTextures(GL_TEXTURE_2D, 1, &textureID);
glTextureStorage2D(textureID, 1, GL_RGBA8, width, height);
|
72,373,002 | 72,383,335 | fscanf read another format in same file.csv | My data file:
name/month/date/year
1.Moore Harris,12/9/1995
2.Ragdoll Moore,11/5/2022
3.Sax,Smart,3/1/2033
4.Robert String,9/7/204
bool success = fscanf(fptr, "%[^,]", nameEmploy) == 1;
bool success = fscanf(fptr, ",%d", &month) == 1;
I only can read 1,2,4 and then the program skips No.3.
What should I use in this format to read it along with the other data?
| To parse the CSV file, it is recommended to read one line at a time with fgets() and use sscanf() to parse all fields in one call:
#include <stdio.h>
#include <string.h>
struct data {
char name[32];
int month, day, year;
};
int parse_csv(FILE *fp) {
char buf[256];
char c[2];
struct data entry;
int count = 0;
while (fgets(buf, sizeof buf, fp)) {
if (sscanf(buf, "%31[^,],%d/%d/%d%1[\n]",
entry.name, &entry.month, &entry.day, &entry.year, c) == 5) {
add_entry(&entry);
count++;
} else {
printf("invalid line: %.*s\n", (int)strcspn(buf, "\n"), buf);
}
}
return count;
}
Note however these shortcomings:
lines longer than 254 bytes will cause errors
fields cannot be quoted
the name field cannot contain ,
empty fields cannot be parsed by sscanf
|
72,374,384 | 72,376,916 | patchelf set interpreter to a path relative to executable | I have tried to do this:
patchelf --set-interpreter ../lib/ld-linux-x86-64.so.2 "${APPDIR}/usr/bin/myapp"
so I have this:
readelf -l AppDir/usr/bin/myapp
...
[Requesting program interpreter: ../lib/ld-linux-x86-64.so.2]
But it looks like it does not like the relative path as I get the error:
$ AppDir/usr/bin/myapp
bash: AppDir/usr/bin/myapp: No such file or directory
I have found this question, as I tried to solve this by using $ORIGIN: Using $ORIGIN to specify the interpreter in ELF binaries isn't working, but it does not answer my question.
Is there a simple way to patch an executable with your certain linker, if you could not know beforehand its absolute path on a machine (e.g. if it's an appimage case)? The only workaround I know is to use path/to/my/ld.so --library-path <path/to/my/libs> path/to/my/exe. But I am just curious, if there is a way to actually patch an executable, so that I could launch it directly?
| You need to specify the path relative to the current working directory (the one you use to execute the program) and not relative to the directory that contains the binary file.
echo 'int main() { return 0; }' > main.c
gcc -Wl,--dynamic-linker=./lib/ld-linux-x86-64.so.2 -o main main.c
mkdir bin
mkdir lib
cp /lib64/ld-linux-x86-64.so.2 lib/
cp main bin/
bin/main # this should run without problems
cd bin; ./main # this throws a "No such file or directory" error
|
72,374,472 | 72,374,545 | How to exit QApplication from another thread? | So the problem is that in any application sometimes the GUI might freeze. Regardless of why it has happened, I want to be able to terminate/exit/quit my application.
Is there any way to do it from another thread (in the same application instance)? Assume that the GUI event loop is frozen and stuck in a while(1); line for example!
What I've already tried:
Calling QCoreApplication::quit() on qApp from another thread, which doesn't work because the GUI event loop is blocked.
Calling QCoreApplication::exit() on qApp from another thread, which doesn't work because it says I can only call it from the GUI thread.
If it is not possible to do it from another thread, how would you suggest to exit the application, assuming the GUI thread is blocked?
| Do you want a hard or a graceful exit? For a super hard exit, that can't be blocked by shutdown handlers (destructors, functions registered with atexit) use the C standard function abort: https://en.cppreference.com/w/cpp/utility/program/abort
|
72,374,596 | 72,374,758 | How can I get the correct json in FlatBuffers? | I successfully parsed the data,but then are not correct json data.How can I get the correct json in FlatBuffers?
My code:
auto result = GenerateText(parser, in, &json_data);
flatbuffers::SaveFile("test.json",json_data.c_str(), json_data.size(), true);
test.json`s content:
{
account: "0520-1",
passwd: "",
device: "test",
token: "11aasasdfasdf"
}
It cannot be parsed correctly by JSON.
Thanks !!!
| You need to enable the strict_json option on the Parser, otherwise you don't get the quoted field names that JSON requires:
auto options = IDLOptions();
options.strict_json = true;
auto parser = Parser(options);
|
72,375,020 | 72,375,659 | c++: cross interactions within dual hierarchy | In a C++ application, I have two class hierarchies, one for Workers and for Stuff. I want each sub-class of Worker to interact differently with each sub-class of Stuff through a do_stuff function. I'm not sure how to do that without systematically down-casting both the worker and stuff inside do_stuff and have specific treatments for each possibility.
Moving do_stuff to be a method for either Worker or Stuff and overriding in the sub-classes removes the need for one down-cast, but not the other.
Is there a specific good pratice to handle similar cases ?
Code structure is as below:
class Worker;
class Worker1 : public Worker;
class Worker2 : public Worker;
class Stuff;
class StuffA : public Stuff;
class StuffB : public Stuff;
void do_stuff(Worker worker, Stuff stuff);
int main() {
vector<Worker*> worker_vec = whatever;
vector<Stuff*> stuff_vec = whatever;
for(Worker* worker : worker_vec) {
for(Stuff* stuff: stuff_vec) {
do_stuff(*worker, *stuff);
}
}
return 0;
}
| A bit of an effort to implement, but at least possible:
class Worker1;
class Worker2;
class Stuff
{
public:
virtual ~Stuff() { }
virtual void doStuff(Worker1*) = 0;
virtual void doStuff(Worker2*) = 0;
};
class Worker
{
public:
virtual ~Worker() { }
virtual void doStuff(Stuff* stuff) = 0;
};
class Worker1 : public Worker
{
void doStuff(Stuff* stuff) override
{
stuff->doStuff(this);
}
};
// another approach: CRTP; spares the work of having to rewrite
// the overridden function again and again...
template <typename T>
class Stuffer : public Worker
{
public:
void doStuff(Stuff* stuff) override
{
stuff->doStuff(static_cast<T*>(this));
}
};
class Worker2 : public Stuffer<Worker2>
{
};
class Worker2 : public Worker
{
void doStuff(Stuff* stuff) override
{
stuff->doStuff(this);
}
};
class StuffA : public Stuff
{
public:
void doStuff(Worker1*) override
{
std::cout << "StuffA + Worker1\n";
}
void doStuff(Worker2*) override
{
std::cout << "StuffA + Worker2\n";
}
};
class StuffB : public Stuff
{
public:
void doStuff(Worker1*) override
{
std::cout << "StuffB + Worker1\n";
}
void doStuff(Worker2*) override
{
std::cout << "StuffB + Worker2\n";
}
};
int main()
{
std::vector<Worker*> worker_vec = { new Worker1, new Worker2 };
std::vector<Stuff*> stuff_vec = { new StuffA, new StuffB };
for(Worker* worker : worker_vec)
{
for(Stuff* stuff: stuff_vec)
{
worker->doStuff(stuff);
}
}
return 0;
}
All without explicit (dynamic_)casts...
For Worker2 I did the implementation via the curiously recurring template pattern – re-introducing a cast, yes, but a static_cast which is for free at runtime so probably won't mind. It would relieve you from having to write the overridden function again and again...
Demo on godbolt.
|
72,375,442 | 72,375,695 | I made this code where it will display the product of all positive integer inputs inputted by the user, but the output is wrong | So we were tasked to create a program that will ask user a positive integer until the user inputted a non-positive number or zero and then display the product of all positive inputs. Using function prototypes. Everything is working fine, however, the displayed output is wrong. I'm guessing it's related to the formula I used but I can't figure it out. Can someone help me please?
#include <iostream>
using namespace std;
int accept_number(){
int x;
cin >> x;
return x;
}
bool ispositive(int x){
if (x > 0)
return true;
else
return false;
}
int product(int x, int y){
return (x*y);
}
void display (int a){
cout << "The product is " << a << ".";
}
int main(){
int userNum, total = 1;
do {
cout << "Enter a number: ";
userNum = accept_number();
total += product(userNum, total);
} while (ispositive(userNum));
cout << endl;
display(total);
cout << endl;
return 0;
}
| Let's say you input 2 at the beginning of the program. Now you'd expect total to be 2 (2*1 = 2). But with what you're doing, this is not the case:
total += product(userNum, total);
..substituting values in this case:
1 += product(2, 1);
..which is 3. What you're doing is adding the product of userNum and total to total, which, according to the question, is not you want to do here. Try this:
total *= userNum; // can also be written as total = total * userNum
Also, your code's loop is wrong. Why? Because if you enter a negative number, it will get multiplied to total, then the loop will be exited, which will lead to incorrect results. So you should restructure your loop as such:
int userNum = 1, total = 1; // initialize userNum = 1
do {
total *= userNum; // this was the last instruction previously
cout << "Enter a number: ";
userNum = accept_number();
} while (ispositive(userNum));
|
72,375,794 | 72,376,365 | Template class compiles with C++17 but not with C++20 if unused function can't be compiled | The following compiles without error in VS2019 (version 16.11.15) with C++ 17 selected as the language. But it fails with C++ 20 with error "error C2027: use of undefined type 'Anon'"
template <typename T> class a_template
{
public:
void do_something(class Anon& anon) const;
};
template <typename T> void a_template<T>::do_something(class Anon& anon) const
{
anon.do_something();
}
The Anon class is of course undefined but the ::do_something function is unused so does not need to be instantiated. This is OK in C++17 but apparently not in C++20.
Is this a change in language rules? If so, can it be fixed without actually defining Anon?
|
Is this a change in language rules?
No, this is due to the fact that a C++ compiler is permitted (but not required!) to diagnose errors at the time the template is parsed
when all of the instantiations of the template would produce that error.
This means that for your given example, at the time of parsing the definition compilers may or may not issue an error. That is, the compiler can produce an error when parsing the template or may wait until the first template instantiation. Refer to demo where msvc doesn't issue an error but gcc and clang does.
Perhaps a simpler example would make it more clear :
void func()
{
}
template<typename T> void bar()
{
func(3); //compilers are allowed(but not required) to issue error at the time of pasrsing this
}
In the above example, func is a nondependent name and at the point where we have called func using func(3), the only visible func is the one that accepts 0 arguments and not one. And as i said earlier, some compiler may issue an error(at the time of parsing) even though we've not instantiated bar but some compilers may not. This is because they are allowed to but not required to do so. See demo where msvc doesn't issue an error here but gcc and clang does.
The same logic applies to your example as well. Meaning as Anon is an incomplete type and you have anon.do_something(), some compiler might choose to produce an error even though you have not instantiated a_template and some other compiler might not.
|
72,376,102 | 72,376,167 | Delete nth node from both beginning and end of singly linked list | I'm just starting to learn linkedlist.
I can come up with an approach to delete a nth node from the beginning and end separately but I couldn't take care of the checks needed to perform both at the same time.
Delete nth node from both beginning and end
INPUT:
1->2->3->4->5->6->7->8->9->10->NULL
N =4
OUTPUT:
1->2->3->5->6->8->9->10->NULL
DELETE FROM BEGINNING :
void deletePosition(struct Node** head, int n){
struct Node* temp = *head;
struct Node* previous;
int size=0;
while(node!=NULL){
node = node->next;
size++;
}
if(n < 1 || n > size){
return;
}
if(n == 1){
*head = (*head)->next;
free(temp);
return;
}
while (--n)
{
previous = temp;
temp = temp->next;
}
previous->next = temp->next;
free(temp);
}
DELETE FROM THE END :
Node* deleteNode(Node* head, int key)
{
Node* temp;
Node* first = head;
Node* second = head;
for (int i = 0; i < key; i++) {
if (second->next == NULL) {
if (i == key - 1) {
temp = head;
head = head->next;
free(temp);
}
return head;
}
second = second->next;
}
while (second->next != NULL) {
first = first->next;
second = second->next;
}
temp = first->next;
first->next = first->next->next;
free(temp);
return head;
}
general algorithm or pseudo code would be much appreciated.
| Suppose you are at node 3.
helper = this -> next -> next;
delete this -> next;
this -> next = helper;
So basically you need to get to the node after the one you seek to delete prior to that deletion as then there will be no way of accessing it.
To check if there are any nodes at all:
if(root == NULL)
{
/// there are no nodes
}
If there are nodes:
traverse = root;
int count = 0;
while(traverse != NULL)
{
++count;
if(count == n)
{ /* you are at the nth node */ }
traverse = traverse -> next;
}
Notice that if you delete node n and you are still at node (n-1), you will just have to do a seperate "shift of indicies," so to say, to remove another node. So if you want to delete another node that was previously the pth one, then just do in the if statement
///the deletion
++count;
Effectively you will get count == p when you arrive at the node that was the pth one until any deletions.
|
72,376,163 | 72,376,316 | What is the proper syntax in C++ for template classes with pointer template types with reference variables? | If I have a template class like this:
template <class T>
class MyClass
{
public:
virtual void MyFunction(const T& t)
{
///
}
};
How will MyFunction look like in a concrete class with a pointer T?
class Data;
class MyDerivedClass : public MyClass<Data*>
{
public:
void MyFunction(???) override
{
///
}
};
Also, how should I use the variable?
| If you really want this setup, you can.
Example:
class MyDerivedClass : public MyClass<Data*> {
public:
using value_type = Data*; // alias to simplify overriding
void MyFunction(const value_type& dpr) override {
// ....
}
};
how should I use the variable?
You'd use it like any other pointer. Note that it's not the Data instance that is const, it's the pointer itself.
|
72,376,513 | 72,376,804 | a value of type "int" cannot be assigned to an entity of type "Node<int> *"C/C++(513) | I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list.
I have a function that returns the first node.
I want to be able to change the m_data in the first node using queue1.front() = 3;. However, I am getting
invalid conversion from ‘int’ to ‘Node<int>*’
error while compiling
template <class T>
class Node {
public:
Node(const T& t);
~Node() = default; // Destructor
Node(const Node&) = default; // Copy Constructor set to default
Node& operator=(const Node&) =
default; // Assignment operator set to default
T& getData();
const T& getData() const;
Node* getNext();
void setNext(Node<T>* newNext);
private:
T m_data;
Node* m_nextNode;
};
template <class T>
Node<T>::Node(const T& t) {
this->m_data = t;
this->m_nextNode = nullptr;
}
template <class T>
class Queue {
public:
static const int SIZE_EMPTY = 0;
Queue();
~Queue(); // Destructor
Queue(const Queue&) = default; // Copy Constructor set to default
Queue& operator=(const Queue&) =
default; // Assignment operator set to default
void pushBack(const T& t);
Node<T>*& front();
const Node<T>*& front() const;
void popFront();
int size() const;
class EmptyQueue {};
private:
Node<T>* m_head;
Node<T>* m_tail;
int m_size;
};
template <class T>
Node<T>*& Queue<T>::front() {
if (this->m_size == Queue<T>::SIZE_EMPTY) {
throw Queue<T>::EmptyQueue();
}
return this->m_head;
}
template <class T>
void Queue<T>::pushBack(const T& t) {
this->m_size += 1;
Node<T>* newNode = new Node<T>(t);
this->m_tail = newNode;
if (this->m_size == 1) {
this->m_head = newNode;
} else {
Node<T>* tempNode = this->m_head;
while (tempNode->getNext()) {
tempNode = tempNode->getNext();
}
tempNode->setNext(newNode);
}
}
int main() {
Queue<int> queue1;
queue1.pushBack(1);
queue1.front() = 3;
}
| Queue<T>::front() is returning a Node<T>*& when it should return a T&.
Example:
template <class T>
T& Queue<T>::front() {
if (this->m_size == Queue<T>::SIZE_EMPTY) {
throw Queue<T>::EmptyQueue();
}
return m_head->getData();
}
template <class T>
const T& Queue<T>::front() const {
if (this->m_size == Queue<T>::SIZE_EMPTY) {
throw Queue<T>::EmptyQueue();
}
return m_head->getData();
}
You also need to make the same change in the class definition:
template <class T>
class Queue {
public:
//...
T& front();
const T& front() const;
//...
};
|
72,377,360 | 72,377,494 | How come std::initializer_list is allowed to not specify size AND be stack allocated at the same time? | I understand from here that std::initializer_list doesn't need to allocate heap memory. Which is very strange to me since you can take in an std::initializer_list object without specifying the size whereas for arrays you always need to specify the size. This is although initializer lists internally almost the same as arrays (as the post suggests).
What I have a hard time wrapping my head around is that with C++ as a statically typed language, the memory layout (and size) of every object must be fixed at compile time. Thus, every std::array is another type and we just spawn those types from a common template. But for std::initializer_list, this rule apparently doesn't apply, as the memory layout (while it can be derived from the arguments passed to its constructor) doesn't need to be considered for a receiving function or constructor. This makes sense to me only if the type heap allocates memory and only reserves storage to manage that memory. Then the difference would be much like std::array and std::vector, where for the later you also don't need to specify size.
Yet std::initializer_list doesn't use heap allocations, as my tests show:
#include <string>
#include <iostream>
void* operator new(size_t size)
{
std::cout << "new overload called" << std::endl;
return malloc(size);
}
template <typename T>
void foo(std::initializer_list<T> args)
{
for (auto&& a : args)
std::cout << a << std::endl;
}
int main()
{
foo({2, 3, 2, 6, 7});
// std::string test_alloc = "some string longer than std::string SSO";
}
How is this possible? Can I write a similar implementation for my own type? That would really save me from blowing my binary whenever I play the compile time orchestra.
EDIT: I should note that the question I wanted to ask is not how the compiler knows what size it should instantiate the initializer list with (as can be achieved via template argument deduction) but how it is then not a different type from all the other instantiations of an initializer list (hence why you can pass initializer lists of different sizes to the same function).
| The thing is, std::initializer_list does not hold the objects inside itself. When you instantiate it, compiler injects some additional code to create a temporary array on the stack and stores pointers to that array inside the initializer_list. For what its worth, an initializer_list is nothing but a struct with two pointers (or a pointer and a size):
template <class T>
class initializer_list {
private:
T* begin_;
T* end_;
public:
size_t size() const { return end_ - begin_; }
T const* begin() const { return begin_; }
T const* end() const { return end_; }
// ...
};
When you do:
foo({2, 3, 4, 5, 6});
Conceptually, here is what is happening:
int __tmp_arr[5] {2, 3, 4, 5, 6};
foo(std::initializer_list{arr, arr + 5});
One minor difference being, the life-time of the array does not exceed that of the initializer_list.
|
72,377,596 | 72,383,290 | verify google IdToken with jwt-cpp | How to verify google tokenId jwt with jwt-cpp lib or something else lib on c++? I tried to redo the example from the library on github, but I don't have enough knowledge in tokens to do everything right, that's what I got:
std::string raw_jwks =
R"({
"keys": [
{
"kid": "486f16482005a2cdaf26d9214018d029ca46fb56",
"e": "AQAB",
"n": "pKFKLmDnNozPu24-nCrbvbBjO0gith7VmxPm1px9lkJfwXOWEbNzyfDhd3SjylKTyH5lq6zMtJvNvKCr2TyQTwypvmZBpeMK29Zz0WvgPBFJ6HHsu9apa21hgE9iPf0A1lNG5Nd2kP9m2Kc8ekKy4OrshDp6gs1ntHPWiW2iSjttruFjTB20P7p5GTdlxzg6LCrJ03E7FJlrfXcEEKRDzZ4h3b6hN2aZ_heOZxRSZ6Uwx8_tbFRe2TIfw9IXaXXuodHMRottSIZBtdJdOanbIFAuhEev9b-lFTksFQXDvicUiz_ri4JDliGuEAgINHjI6pcNo2vkYx3NupROmkDRIQ",
"use": "sig",
"alg": "RS256",
"kty": "RSA"
},
{
"kty": "RSA",
"alg": "RS256",
"n": "h0G4nnQc39gn04fTuSJB6l1JhE9ggG-SHrc9yfr85tzQEjxG55jipmnmW1x-IHS1PvWgtNbpeEDya9IUzkC8BxnBht7WVDV9mLBZK8szrCrj6l7SwvQOM6cw0-KgGgmzwE_IGkn452wmlVYz9IIY-etasrkstJ0G2smQJ3Db3YbZe32FoYnXbbK38O2hIf4bffegccrfmsEEbSisq0903IEbCi0qpJbhrgqvYg6_y0KeOxxX5u-_Jg-KM0Aub4YGT2LRsiE_ygskabuoh6nQDr8M9-SDC_bEind2FUk761ZSw_QMk9_Nc9orllaMZpQ4FpKRv5LXHUawz_er8P3c0w",
"use": "sig",
"kid": "38f3883468fc659abb4475f36313d22585c2d7ca",
"e": "AQAB"
}
]
}
)";
std::string token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ."
"SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
auto decoded_jwt = jwt::decode(token);
auto jwks = jwt::parse_jwks(raw_jwks);
auto jwk = jwks.get_jwk(decoded_jwt.get_key_id());
auto issuer = decoded_jwt.get_issuer();
auto x5c = jwk.get_x5c_key_value();
if (!x5c.empty() && !issuer.empty()) {
auto verifier =
jwt::verify()
.allow_algorithm(jwt::algorithm::rs256(jwt::helper::convert_base64_der_to_pem(x5c), "", "", ""))
.with_issuer(issuer)
.leeway(60UL); // value in seconds, add some to compensate timeout
verifier.verify(decoded_jwt);
}
But i have no x5c in JWK, only "e" and "n", what should I do?
| The array in your question raw_jwks is a JSON Web Key Set (JWKS). This contains an array of public keys. The key ID is either kid which you have or commonly x5c.
Some libraries accept a public key in the raw number format (n and e), others require that you create a public key in PKCS format from those numbers first. I do not use your library, so consult the documentation for the required format and conversion functions.
Since you do not know the actual private key ID used to sign the JWT you must loop thru raw_jwks checking each one for signature validation success. If neither succeeds, report failure.
For future information, in Google Cloud there are two types of private/public keys. Those managed by Google Cloud (only the public key is available) and service account keys.
The public keys for Google Cloud are located here:
https://www.googleapis.com/oauth2/v1/certs
For service accounts they start with this URL and have the service account email address appended:
https://www.googleapis.com/robot/v1/metadata/x509/
|
72,377,861 | 72,378,114 | create member variable of type that contains atomic value as its member | I'm using a third-party library with a class containing atomic<double>. Now the library returns a reference to that class object while calling a function. Now I want to keep that reference somewhere to reuse it in my application workflow.
Here is the actual class from the third party lib
Here is the function that returns the reference
Since it holds the atomic value I can't copy the class object (Gauge in the above link) and also I can't change that third party library at the moment. Is there any workaround for this?
I have tried to store the returned reference value in a unique_ptr<Gauge>
std::unique_ptr<prometheus::Gauge> cpuUsageInPercent = std::make_unique<prometheus::Gauge>(
prometheus::BuildGauge()
.Name("cpu_usage_percent")
.Help("cpu usage in percent")
.Register(*m_registry)
.Add({}));
but I got the below error
/usr/include/c++/11/bits/unique_ptr.h:962:30: error: use of deleted function ‘prometheus::Gauge::Gauge(const prometheus::Gauge&)’
962 | { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
| TL;DR
How about writing this?
Gauge & g = prometheus::BuildGauge()
.Name("cpu_usage_percent")
.Help("cpu usage in percent")
.Register(*m_registry)
.Add({});
Long Answer
If you have a function returning a reference, say
X &f();
then you can simply take the address of the result and store it, like so:
X * ptr = &f();
You can then refer to the object by pointer. You can copy the pointer around and thus keep it in the application wherever you want. You can also refer to the object by reference like this:
X & obj = f();
If you put something into an std::unique_ptr<X>, then this indicates that you become the unique owner of the object. However, you only want to borrow the reference as far as I can tell. Therefore, a simple raw pointer may be exactly what you need.
If you use std::make_unique<X>() to create an object, then you have to pass arguments to that function which are accepted as arguments to a constructor of X. The Gauge class does not provide a constructor which takes a Gauge & as argument.
|
72,378,266 | 72,385,294 | With boost::json, Is it possible to declare two separate value_from conversions in different namespaces? | Lets say I have a class Customer in namespace Data. Using boost, I know I can convert this into valid JSON by declaring a function with the signature: void tag_invoke( const value_from_tag&, value& jv, Customer const& c ).
However, in all of the examples in the boost documentation, it appears that this tag_invoke function must reside in the Data namespace, i.e. the same namespace as Customer.
I would like to know if it is possible to have something like the following:
namespace FileIO
{
void tag_invoke( const value_from_tag&, value& jv, Data::Customer const& c );
{
jv = {
{ "id", c.id },
{ "name", c.name },
{ "late", c.late }
};
}
}
namespace Network
{
void tag_invoke( const value_from_tag&, value& jv, Data::Customer const& c )
{
jv = {
{ "id", c.id },
{ "late", c.late }
};
}
}
In other words, have two different implementations of the value conversion, where the current namespace would determine which one gets used. I've not had any success getting it working, being met with various "no matching call to value_from_impl" errors.
In case it helps, my CMake setup is such that Data, FileIO, and Network are all separate targets, where both FileIO and Network are linked to/depend Data, but not to each other, and Data depends on no other libraries.
Any advice would be appreciated
| Tag invoke is a more useful implementation of the old-fashioned ADL customization points. But it still heavily uses ADL. That means that associated namespaces are considered for overload resolution.
See https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1895r0.pdf for rationale.
You can declare unrelated overloads in other namespaces but,
best case that namespace is not associated, and the overload is ignored
worst case, that namespace is also associated, and the call becomes ambiguous.
In case it helps, my CMake setup is such that Data, FileIO, and Network are all separate targets, where both FileIO and Network are linked to/depend Data, but not to each other, and Data depends on no other libraries.
That sounds like you have isolated source (translation units). You can define different customization points locally in those TUs. Make (doubly) sure they have internal linkage, so that you don't risk ODR violation. E.g.
namespace Data
{
namespace { // anonymous namespace for file static (no external linkage)
void tag_invoke( const value_from_tag&, value& jv, Customer const& c );
{
// ...
};
}
}
Alternative
Alternatively, you can use tagged wrappers, a bit like manipulators:
Live On Coliru
#include <boost/json.hpp>
#include <boost/json/src.hpp>
#include <iostream>
namespace json = boost::json;
template <typename T> struct UPPERCASE {
T const& ref;
UPPERCASE(T const& ref) : ref(ref) {}
};
namespace Data {
struct Customer {
int id;
std::string name;
bool late;
friend void tag_invoke(json::value_from_tag,json::value&jv, Customer const& c) {
jv = {{"id", c.id}, {"name", c.name}, {"late", c.late}};
}
friend void tag_invoke(json::value_from_tag, json::value& jv, UPPERCASE<Customer> const& c) {
jv = {{"ID", c.ref.id}, {"NAME", c.ref.name}, {"LATE", c.ref.late}};
}
};
} // namespace Data
int main() {
Data::Customer const c{1, "One", true};
std::cout << json::value_from(c) << "\n";
std::cout << json::value_from(UPPERCASE(c)) << "\n";
}
Prints
{"id":1,"name":"One","late":true}
{"ID":1,"NAME":"One","LATE":true}
|
72,378,941 | 72,379,004 | .hpp files not running in vscode | I was trying to create a .hpp file in vscode, but when I tried running it I was told it was not compatible with my system. However, I am able to use and run .cpp files just fine.
TreeNode.exe is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.
class TreeNode{
public:
char value;
char left;
char right;
TreeNode(char val){
value = val;
}
};
| *.hpp are the header files without main() function, whereas *.cpp files containing main() function are for compiling through (gcc or clang). To test out your *.hpp files you need to include it in *.cpp file.
#include "./my_header_file.hpp"
Always remember, main() is the entry of your program, it should exist.
Also, I think your class TreeNode isn't correct instead of:
char left;
char right;
It should be:
TreeNode *left; // allocate on heap-memory using `new` operator
TreeNode *right; // allocate on heap-memory using `new` operator
|
72,379,023 | 72,379,248 | Can you read and delete chunk of a file? | I am using ofstream and ifstream to read a chunk from a file post it over middleware (DDS) to another process and the other process writes that chuck of the file.
Basically transferring a file. The two components are unaware of each other and may live on the same hardware or on different hardware (DDS takes care of the transfer either way).
This is all working, however when I try to do this with a large file (>500MB) and if the destination component is on the same board, then I run out of RAM (since 500 x 2 = 1GB which is my limit).
So I am thinking of reading a chunk from a file deleting that chunk of the file and then sending the chunk. So I end up with:
A B
12345 ->
2345 -> 1
345 -> 12
45 -> 123
5 -> 1234
-> 12345
Where each number is a chunk of a file.
I am using linux, so I can use any linux APIs directly, but would probably prefer a pure c++ approach. I can't really see any good options here. i/ostream does not appear to let you do this. Options like sed will (I think) end up using more memory by copying.
Are there any better mechanisms for doing this?
Update
The files are stored in RAM via a tmpfs partition
|
I am using linux, so I can use any linux APIs directly, but would
probably prefer a pure c++ approach. I can't really see any good
options here. i/ostream does not appear to let you do this. Options
like sed will (I think) end up using more memory by copying.
Are there any better mechanisms for doing this?
There is no standard mechanism in C++ or Linux for shortening a file in-place by deleting data from the beginning or middle. Most file systems don't work in a way that would support it. When one wants to delete data from such a position, one has to make a new copy of the file, omitting the data that are to be deleted.
You can shorten a file by removing a tail, but that does not serve your purpose unless possibly if you send chunks in reverse order, from tail to head. However, the most natural ways I can think of to support that in an application such as yours would involve pre-allocating the full-size destination file, and that would have the same problem you are trying to solve.
|
72,379,364 | 72,379,654 | What does "template <> int line<0>::operator[](int y) const" do? | #include <bits/stdc++.h>
using namespace std;
constexpr int mod = 1e9 + 7, maxn = 2e6;
int N, M, p[1 << 10], buf[maxn];
template <bool t> struct line {
int *v;
int operator[](int y) const;
};
template <> int line<0>::operator[](int y) const { return v[y]; }
template <> int line<1>::operator[](int y) const { return v[M * y]; }
What is this operator thing? Is it a function? If it is then why does it have square brackets and "const" after it?
Also do these template things mean? I'm assuming that it executes one of them
depending on the value of t ( true or false )'
|
What is this operator thing? Is it a function? If it is then why does it have square brackets
You're declaring operator[] as a member function of the class template named line. By providing this, we say that we're overloading operator[] for our class template line(really for a specific class type that will be instantiated).
why does it have const after it
The const means that this operator[] member function is a const member function. Meaning we're not allowed to change the non-static non-mutable data members inside this member function.
Also do these template things mean?
Assuming you are asking about the template<> as the question title suggests, it means that you're explicitly(fully)specializing the member function operator[] for different class-template arguments 0 and 1.
More details can be found in any of the good C++ books.
Also refer to Why should I not #include <bits/stdc++.h>?.
|
72,379,380 | 72,379,469 | Callback With Forwarding vs Without | Lets say I have a function which triggers a callback.
template <typename Callback>
void call_callback(Callback&& rvalue_callback)
What is the difference between the following to calling snippets:
no forwarding:
{
rvalue_callback();
}
with forwarding:
{
std::forward<Callback>(rvalue_callback)();
}
A call example:
call_callback([]() { std::cout << "hello world" << std::endl; });
You can assume in your answer call_callback will always receive a lambda as a parameter and not an std::function for example.
More interested in practical differences then theoretical ones.
For example performance or optimizations the compiler can do in one situation but not in another.
Thanks in advance,
|
... rvalue_callback
First of all, note that you are dealing with a forwarding (or universal; common non-standard word) reference here, not an rvalue reference. For details, see e.g.:
rvalue reference or forwarding reference?
What is the difference between the following to calling snippets:
You can assume in your answer call_callback will always receive a lambda as a parameter and not an std::function for example.
Given the assumption: none. std::forward is just a conditional cast (think std::move), but as you are not passing on the function argument rvalue_callback elsewhere (no "forwarding" in this context), and as the closure type of a lambda does not overload its function call operator on ref- or const-qualifiers of its implicit object parameter, the conditional cast in your case will essentially be a no-op (somewhat slightly different conversion sequence used for ranking viable overloads, but you only have one viable overload here).
If you were instead passing custom class-type object and invoked a member function, or wrote a functor which overloaded the ref-qualifiers of the implicit object parameter (which is not the case of the closure type of a lambda) then it could make a difference:
#include <iostream>
struct S {
void f() & { std::cout << "lvalue\n"; }
void f() && { std::cout << "rvalue\n"; }
// This kind of implicit object parameter
// overloading would not be present in the
// closure type of a lambda.
void operator()() & { std::cout << "lvalue\n"; }
void operator()() && { std::cout << "rvalue\n"; }
};
template<typename T>
void memfn1(T&& t) { t(); }
template<typename T>
void memfn2(T&& t) { std::forward<T>(t)(); }
template<typename T>
void funcallop1(T&& t) { t.f(); }
template<typename T>
void funcallop2(T&& t) { std::forward<T>(t).f(); }
int main() {
S s{};
memfn1(s); // lvalue
memfn2(s); // lvalue
memfn1(S{}); // lvalue !!!
memfn2(S{}); // rvalue
funcallop1(s); // lvalue
funcallop2(s); // lvalue
funcallop1(S{}); // lvalue !!!
funcallop2(S{}); // rvalue
}
However this is forwarding, to an overloaded member function of the class-type function argument.
|
72,379,704 | 72,379,835 | invalid operands of types 'const char*' and const char[4]' to binary 'operator+' | I am getting the below error when I use the query to insert data in a database .
This is my code :
void Journal::insert_info()
{
//Variables
int id_journal= getId_journal();
string nom_journal=getNom_journal();
//Here is where the error
string insert_query = "INSERT INTO `info_journal`(`id_journal`, `nom_journal`, `date`, `id_fournisseur`, `id_atm`, `state`, `state_parse_journal`, `terminal`, `id_utilisateur`) VALUES ('"+id_journal+"','"+nom_journal+"',NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL )";
//int qstate = mysql_real_query(conn,insert_query.c_str(), strlen(insert_query.c_str()));
query_state=mysql_query(conn, insert_query.c_str());
if(!query_state)
{
cout << "Query Execution Problem " << mysql_errno(conn) << endl;
}
else
{
cout << endl << "success" << endl;
}
}
Do you have any ideas.
Thank you in advance.
| Like the error message says, you can't add pointers and arrays
The problematic part is:
"INSERT ..." + id_journal + "','"
Here the literal string "INSERT ..." will decay to a pointer (const char*) and then the value of id_journal is added. This result in the pointer &(("INSERT ...")[id_journal])). In other words, the value of id_journal is used as an array index instead of being converted to a string.
You then try to add this pointer to the literal string "','" which is really a constant array of four characters (including the string null-terminator).
There no usable + operator which can handle this.
The simplest solution is to turn at least one of the operands of the first addition to a std::string object. I suggest the integer variable id_journal since you can't concatenate strings with integers (there's no automatic conversion here):
string insert_query = "INSERT ...VALUES ('" + std::to_string(id_journal) + "','" + ...;
This works because there is an overloaded + operator which takes a const char* on the left-hand side and a std::string on the right-hand side. Then once this is done, you have a std::string object which can be used for any further concatenations.
|
72,379,794 | 72,381,181 | iterator operator++ overload compiling error | I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list.
I've implemented iterator for Queue that points to the address of the node, I've already succeeded implementing begin(),end() and ==,!=, and tested too,
but I'm unable to implement ++() and ++(int) operators for the iterators, i want the ++ operator to change the address of the node to the next one in the linked list, i get the following error when i try to compile: no matching function for call to ‘Node<int>::getNext() const’
and how can i make the iterator operator overload to work without typing typename at the start of the declaration
Node class:
template<class T>
class Node {
public:
Node(const T& t);
~Node()=default; // Destructor
Node(const Node&) = default; // Copy Constructor set to default
Node& operator=(const Node&) = default; // Assignment operator set to default
T& getData();
const T& getData() const;
Node* getNext();
void setNext(Node<T>* newNext);
private:
T m_data;
Node* m_nextNode;
};
template<class T>
Node<T>::Node(const T& t) {
this->m_data=t;
this->m_nextNode=nullptr;
}
template<class T>
Node<T>* Node<T>::getNext() {
return this->m_nextNode;
}
Queue class:
template<class T>
class Queue {
public:
static const int DEFAULT_FIRST_INDEX=0;
static const int SIZE_EMPTY=0;
Queue();
~Queue(); // Destructor
Queue(const Queue&) = default; // Copy Constructor set to default
Queue& operator=(const Queue&) = default; // Assignment operator set to default
void pushBack(const T& t);
T& front();
const T& front() const;
void popFront();
int size() const;
class Iterator;
Iterator begin() const;
Iterator end() const;
class EmptyQueue {};
private:
Node<T>* m_head;
Node<T>* m_tail;
int m_size;
};
Queue<T>::Iterator class:
template<class T>
class Queue<T>::Iterator {
public:
const T& operator*() const;
Iterator& operator++();
Iterator operator++(int);
bool operator==(const Iterator& iterator) const;
bool operator!=(const Iterator& iterator) const;
Iterator(const Iterator&)=default;
Iterator& operator=(const Iterator&)=default;
class InvalidOperation {};
private:
const Node<T>* m_node;
Iterator(const Node<T>* m_node);
friend class Queue<T>;
};
template<class T>
Queue<T>::Iterator::Iterator(const Node<T>* m_node) {
this->m_node=m_node;
}
template<class T>
typename Queue<T>::Iterator& Queue<T>::Iterator::operator++() {
this->m_node=m_node->getNext();
return *this;
}
|
How do I make it work without typename at the start of the definition?
If you meant about the function Queue<T>::Iterator::operator++() definition, you can do it via trailing return type as follows:
template<class T>
auto Queue<T>::Iterator::operator++() -> Iterator&
//^^^ ^^^^^^^^^
{
this->m_node = m_node->getNext();
return *this;
}
That been said, (IMO) moving definitions outside the same transition unit for template classes or template functions is a bit verbose and tedious.
|
72,380,211 | 72,381,282 | Global function call from function in unnamed namespace with the same name | I have a some code.
file1.cpp:
extern void callout();
int answer() {
return 5;
}
int main(){
callout();
return 0;
}
file2.cpp
#include <iostream>
using std::cout; using std::endl;
namespace {
int answer() {
cout << ::answer() << endl;
return 12;
}
}
void callout() {
cout << answer() << endl;
}
Instead of calling the global answer() function, the answer() function in unnamed namespace is calls itself recursively, resulting in a stack overflow. How do I call the global answer() function from answer() function in unnamed namespace?
| First of all, if you want to call a function, it needs to be declared in the translation unit. The answer function from file1.cpp is currently not declared in file2.cpp's translation unit.
To fix this add a header file included in both .cpp files containing
int answer();
(By the way: extern on a function declaration is pretty much useless)
With this, the qualified call ::answer() should work as you want it to, calling the overload in the global namespace.
Unfortunately, as you noted in the comments, it will result in the unqualified call answer() in callout failing. This is because an unnamed namespace behaves as if the using namespace /* unnamed namespace name */; was used and unqualified name lookup will consider both the overload in a namespace as well as the overload introduced "as if" part of the namespace due to a using-directive equally.
I don't think there is any way to call the answer inside the unnamed namespace from outside of it under these circumstances. You can't differentiate the functions by overload resolution and you can't select the one inside the unnamed namespace by name, since the unnamed namespace doesn't have a name you can refer to. Your best option is to rename answer in file2.cpp or to add a function in the unnamed namespace with a different name forwarding the call to answer. Inside the unnamed namespace a simple unqualified call answer() will call the function in the unnamed namespace and will not consider the global namespace scope.
All of this would be easier if you didn't use (only) an unnamed namespace. If there was a named namespace differentiating the two functions, either could be called by qualified name.
|
72,381,138 | 72,381,399 | Random ABCD char generator | I am making a quiz game and want when the player calls his friend(which is a simple cout), the program prints a random char of an answe(A, B, C or D) and a random number to present how sure he is(from 1 to 100). Whetever I try the char in console is always D, and the number is always 87. I don't know how to make this work. This is the current code:
char x = *("ABCD" + rand() % 4);
int y = 1+ (rand() % 100);
| Random numbers generation is not as simple as you might think.
See here some general info: Random number generation - Wikipedia.
In order to use rand properly, you should initialize the random seed (see the link).
Using the current time as seed is recommended for getting "nice" random values. Note that setting the seed using srand should be called only once.
Below you can see a fixed version for your code, that produce different values (potentially) in each run:
#include <time.h>
#include <stdlib.h>
#include <iostream>
int main() {
// Call once:
srand(static_cast<unsigned int>(time(0)));
// Can be called multiple times:
char x = *("ABCD" + rand() % 4);
int y = 1 + (rand() % 100);
std::cout << x << "," << y << std::endl;
return 0;
}
However - since C++11 the standard library has good and modern support for random generators. See: Pseudo-random number generation.
It requires a bit more boilerplate, but you have better control over the generation of random values. See more info in the <random> header, which contains a lot of classes and utilities.
A good alternative to rand() in your case is the std::uniform_int_distribution.
Here is some info why to prefer it over the old rand(): What are the advantages of using uniform_int_distribution vs a modulus operation?.
The code below shows how to use it in your case (the initilization of rd, gen, distrib1, distrib2 should be done only once):
#include <random>
#include <iostream>
int main() {
// Call once:
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib1(0, 3); // For getting a random integer in the range 0..3
std::uniform_int_distribution<> distrib2(1, 100); // For getting a random integer in the range 1..100
// Can be called multiple times:
char ABCD[] = "ABCD";
std::cout << ABCD[distrib1(gen)] << ',' << distrib2(gen) << std::endl;
return 0;
}
|
72,381,198 | 72,388,616 | std::conditional - Invalid parameter type ‘void’ even when testing for 'void' | The following compiles on Visual Studio:
template<typename ArgType, typename ReturnType>
struct Test
{
using FunctionPointerType = std::conditional_t<
std::is_same_v<ArgType, void>
, ReturnType(*)()
, ReturnType(*)(ArgType)
>;
FunctionPointerType Func;
};
int main()
{
Test<void, char> tt;
}
But does not compile on Linux g++. The error I get is
error : invalid parameter type ‘void’
I know I cannot use void in templates, which is why I have used std::conditional_t and std::is_same_v.
I cannot see what is incorrect, can someone please tell me?
| In std::conditional_t<B, T, F> both the true and false specialization should have valid types T as well as F. In your case, since the F deduce to an invalid char(*)(void) type, std::conditional can not be used here.
I would suggest a helper traits function_ptr_t as alternative
#include <type_traits>
template<typename RetType, typename... Args> struct function_ptr final {
using type = RetType(*)(Args...);
};
template <typename RetType> struct function_ptr<RetType, void> final {
using type = RetType(*)();
};
// alias helper
template<typename RetType, typename... Args>
using function_ptr_t = typename function_ptr<RetType, Args...>::type;
template<typename RetType, typename... Args>
struct Test
{
function_ptr_t<RetType, Args...> Func;
};
See a demo
Note that, I have swapped the template arguments in the class template Test, and made the second template argument be a variadic, so that the Test<char> will result in a member function pointer of type char(*)().
That means the following will work:
Test<char> tt1;
static_assert(std::is_same_v<char(*)(), decltype(tt1.Func)>, " are not same!");
Test<char, void> tt2;
static_assert(std::is_same_v<char(*)(), decltype(tt2.Func)>, " are not same!");
Test<void, double> tt3;
static_assert(std::is_same_v<void(*)(double), decltype(tt3.Func)>, " are not same!");
If that is not, you wanted, substitute the variadic template arguments to be a normal one.
|
72,381,728 | 72,396,026 | Cannot find >>() and <<() declared in unnamed namespace | The simplified example bellow illustrates the problem with the stream operators >> and <<. The example compiles in GCC10 and GCC11 with C++17 standard, but it does not compile in GCC 12.1. In GCC 12, the operators >> and << for ns_f::A declared in an unnamed namespace are not found.
This is my first question, why are not the operators >> and << found in GCC12? What has changed in GCC 12 and why has it changed?
A possible solution is to place operators declarations into the class A in the inline friend functions. But I like the version where the operators are hidden in the file.o module.
During my experimentation, I found that moving declaration of class Wrapper after an unnamed namespace solves the problem. This is my second question, why?
#ifndef FILE_H
#define FILE_H
#include <istream>
#include <ostream>
#include <vector>
namespace ns_f {
struct A { };
class Z {
std::vector<A> items;
public:
void save_items(std::ostream& out) const;
};
} // namespace ns_f
#endif
#include "file.h"
#include <fstream>
#include <istream>
template<typename T>
class Wrapper
{
public:
explicit Wrapper(T&) {}
private:
using P = typename T::value_type;
friend std::ostream& operator<<(std::ostream& out, const Wrapper&)
{
return out << P{};
}
};
namespace {
std::ostream& operator<<(std::ostream& out, const ns_f::A&)
{
return out;
}
} // unammed namespace
// If move declaration of Wrapper here it compiles.
namespace ns_f {
void Z::save_items(std::ostream& out) const
{
out << Wrapper(items);
}
} // namespace ns_f
| When using an operator like << (or calling a function with unqualified name) there are two ways that matching names (i.e. here operator<< overloads) can be found as candidates.
The first way is by simple unqualified name lookup which traverses the scopes from inner to outer until the name is found, and then stopping.
The second is via argument-dependent lookup (ADL) by looking for it in the namespaces of classes whose type appears as part of the arguments of the function call, or here the operands of the << operator.
Usually both lookups are performed from the point where the call appears and declarations which are only introduced after that point in the translation unit are not considered.
However if the call appears in a template, as is the case here for out << P{}; there are two (or maybe even more) points from which lookup could be performed: The point where the template containing the call is defined and the point where a specific template specialization is instantiated.
In your code the definition of the template is before the declaration of the operator<< overload in the unnamed namespace and the instantiation is after it (possible points are immediately before the definition of save_items or at the end of the translation unit).
So, one possibility would be that name lookup is done either only from one of the two points or equally from both. But the actual rules are that the simple unqualified name lookup is performed only from the point of definition and the argument-dependent lookup is performed from the point of instantiation.
So your overload could only be found via ADL, but ADL requires the function to be in the same namespace as the type(s) of the argument(s), which is here not the case, since A is not part of the unnamed namespace.
The rules are chosen this way with the conventional understanding that you will put operator overloads specific to a given class in the same namespace and header as the class itself.
Therefore GCC 12 is correct and the previous versions were wrong to accept the code.
Prior to version 12 GCC had a bug which also considered the unqualified name lookup from the point of instantiation instead of the point of definition when looking up operator overloads for operator uses. See bug 51577.
The unnamed namespace is a red herring, by the way. If you put the operator<< overload directly into the global namespace or any other namespace that isn't ns_f, nothing about the above changes.
|
72,381,803 | 72,381,839 | C++ higher order functions: different results when declaring multiple functions | I was plying with higher order functions, and I started getting different results when I created two instances and assigning them to variables.
I reduced the issue to the following example:
#include <iostream>
using ColorGetter = int(*)(void);
auto paint(const ColorGetter &f)
{
return [&]() { return f(); };
}
int colorA() { return 10; }
int colorB() { return 20; }
int main()
{
auto painter1 = paint(colorA);
auto painter2 = paint(colorB);
std::cout << "painter 1 : " << painter1() << "\n";
std::cout << "painter 2 : " << painter2() << "\n";
auto p1 = [] () { return colorA(); };
auto p2 = [] () { return colorB(); };
std::cout << "p 1 : " << p1() << "\n";
std::cout << "p 2 : " << p2() << "\n";
}
My expectation was to get 10, followed by 20 from both sequences.
Instead, depending on the compiler, I get:
➜ tmp clang++-13 -o out.gcc wrong.cpp&& ./out.gcc
painter 1 : 10
painter 2 : 20
p 1 : 10
p 2 : 20
➜ tmp g++-11 -o out.gcc wrong.cpp && ./out.gcc
painter 1 : 20
painter 2 : 20
p 1 : 10
p 2 : 20
Is there something fundamentally wrong with the above code?
I get no compiler warnings or clang-tidy issues, at least with my current settings.
| Let's look at this code:
auto paint(const ColorGetter &f)
{
return [&]() { return f(); };
}
The f parameter only exists for the lifetime of the function paint. Your lambda function captures it by reference (that's the [&] bit), and so your lambda capture is referencing a variable (the reference f) that no longer exists after the function ends. As a result, the object you're returning holds a dangling reference to the function. You're seeing undefined behavior here, which is why the result varies across compilers.
To fix this, change the code to read
auto paint(const ColorGetter &f)
{
return [=]() { return f(); };
}
This will cause the lambda capture to make a copy of the value stored in f (the pointer to the function in question), which will outlive the paint function.
|
72,382,432 | 72,383,295 | Templated constexpr function invocation with partially defined class changes subsequent results | I have a struct with multiple overloads of a static function taking some counter<int> as an argument:
struct S {
static void fn(counter<1>);
static void fn(counter<2>);
static void fn(counter<3>);
};
A templated constexpr function can be used to look for a specific overload in that class:
template <typename T>
inline constexpr size_t count_fns() {
// 'defines_fn' is a type trait, full code in demo link
if constexpr (defines_fn<T, counter<99> >::value) { return 99; }
if constexpr (defines_fn<T, counter<98> >::value) { return 98; }
if constexpr (defines_fn<T, counter<97> >::value) { return 97; }
// [...]
if constexpr (defines_fn<T, counter<3> >::value) { return 3; }
if constexpr (defines_fn<T, counter<2> >::value) { return 2; }
if constexpr (defines_fn<T, counter<1> >::value) { return 1; }
return 0;
}
In ordinary usage, count_fns<S>() returns 3, as expected.
However, adding an inline static variable invoking count_fns changes things:
struct U {
static void fn(counter<1>);
static void fn(counter<2>);
static constexpr size_t C0 = count_fns<U>(); // C0 is 2
static void fn(counter<3>);
};
static_assert(count_fns<U>() == 3, " <-- fails, value is actually 'still' 2");
Godbolt suggests this behavior is consistent across compilers (MSVC, gcc, clang):
Demo
Is this to be expected, or is it some sort of undefined behavior with the constexpr interpreter?
These are the definitions of counter and defines_fn:
template <size_t Value>
struct counter {
static constexpr size_t value = Value;
};
template <typename T, typename Arg, class = void>
struct defines_fn { static constexpr bool value = false; };
template <typename T, typename Arg>
struct defines_fn<T, Arg, std::void_t<decltype(T::fn(std::declval<Arg>()))> >
{
static constexpr bool value = true;
};
| The section of the standard that is supposed to govern this kind of code is [temp.point]. Unfortunately, it's considered to be defective. CWG 287
The standard technically says that in your example, where count_fns<U> is referenced inside the definition of U, the point of instantiation is considered to be right after the definition of U. However, this leads to absurdities; what should happen if, for example, we had the following declaration inside U:
static void fn(counter<2 * C0>);
Now it seems that we have a circular dependency.
CWG 287 concerned class template specializations. The issue with those is a bit different because [temp.point] says that (for example) if you were to reference a class template specialization within the definition of U then the point of instantiation would be before the definition of U. (I haven't yet figured out why the rules are different for class templates and function templates.)
To solve the issues in both cases, it seems the "common sense" approach is that both template and non-template constructs referenced from inside a class definition should be able to see previously declared members of the class (and this holds for both function and class template specializations). (If the context from which they're referenced is a complete-class context, they should be able to see all members of the class. Is that possible or does it lead to other issues? I'm not sure. So I'm going to just avoid this issue for now.)
Following that principle, if the initializer of C0 requires a template specialization, compilers seem to place the point of instantiation either right before or right after the declaration of C0. There is implementation divergence on whether it's before or after, but in any case, it's after the member declarations that precede C0, and before the member declarations that follow C0. All major compilers seem to agree on this point.
The second instantiation of count_fns<U>, in the static_assert declaration, references the same set of specializations of the defines_fn class template as the first instantiation did. Class template specializations, unlike function template specializations, are not re-instantiated every time they are referenced; the first instantiation is "cached". See [temp.point] p4 and p7. So the second call to count_fns<U> returns the same result as the first.
So that seems to be the reason why you're seeing the behaviour you're seeing. Whether it's right or wrong, we can't say, until CWG 287 is fixed.
|
72,382,695 | 72,383,055 | Issue when calling template function that returns a pointer to base class | My goal is to create many objects of derived classes and store them in a std::map with a std::string as a key and the pointer to that object as the value. Later in the flow, I access all the keys and values and call some virtual functions re-implemented in the derived classes.
I ended up in a situation where I had to call a template within a template.
Model.h
#include<Base.h>
class myClass {
template<typename T>
Base* createT() { new T; }
typedef std::map<std::string, Base*(*)()> map_type;
static map_type* getMap() {
if (!map) {
map = new map_type;
}
return map;
}
template<typename T>
void registerT(std::string& s) {
getMap()->insert(std::make_pair(s, createT<T>())); // problem is here 1 of 2
}
};
Model.cc
#include <Model.h>
#include <DerivedA.h>
registerT<DerivedA>("DerivedA"); // problem is here 2 of 2
registerT<DerivedB>("DerivedB");
// To be implemented getValue(). Eventual goal is this.
auto objA = getValue("DerivedA");
objA->init(); // virtual
objA->run(); // virtual
The createT is supposed to create an object and return me the pointer. But it is not working and the compiler is throwing this error:
error: cannot call member function ‘HB::Base* myClass::createT() [with T = HB::DerivedA]’ without object
getMap()->insert(std::make_pair(s, createT<R>()));
~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
What am I doing wrong?
| Your map expects pointers to free-standing functions, but your createT() is a non-static class method, so it is not compatible (also, your createT() is not actually return'ing anything).
When insert()'ing into your map, you are calling createT() and then trying to insert its returned object pointer, when you should instead be inserting the address of createT() itself, eg:
Model.h
#include <Base.h>
#include <memory>
class myClass {
template<typename T>
static std::unique_ptr<Base> createT() { return std::make_unique<T>(); }
typedef std::map<std::string, std::unique_ptr<Base>(*)()> map_type;
static map_type& getMap() {
static map_type instance;
return instance;
}
template<typename T>
static void registerT(const std::string& s) {
getMap().emplace(s, &myClass::createT<T>);
}
static auto getValue(const std::string& s) {
return getMap()[s];
}
};
Model.cc
#include <Model.h>
#include <DerivedA.h>
myClass::registerT<DerivedA>("DerivedA");
myClass::registerT<DerivedB>("DerivedB");
auto createA = myClass::getValue("DerivedA");
auto objA = createA();
objA->init(); // virtual
objA->run(); // virtual
However, you said in your description that you want to store object pointers in the map, not function pointers. Your code does not match your description. In which case, you would need something more like this instead:
Model.h
#include <Base.h>
#include <memory>
class myClass {
template<typename T>
static std::unique_ptr<Base> createT() { return std::make_unique<T>(); }
typedef std::map<std::string, std::unique_ptr<Base>> map_type;
static map_type& getMap() {
static map_type instance;
return instance;
}
template<typename T>
static void registerT(const std::string& s) {
getMap().emplace(s, createT<T>());
}
static auto& getValue(const std::string& s) {
return getMap()[s];
}
};
Model.cc
#include <Model.h>
#include <DerivedA.h>
myClass::registerT<DerivedA>("DerivedA");
myClass::registerT<DerivedB>("DerivedB");
auto &objA = myClass::getValue("DerivedA");
objA->init(); // virtual
objA->run(); // virtual
|
72,382,940 | 72,383,585 | I get a warning when I try to run the recursion program with return keyword | I was expecting 1 2 3 as output, but when I try to run this code:
#include <iostream>
using namespace std;
int fun(int x){
if (x>0){
return fun(x-1);
cout<<x<<endl;
}
}
int main()
{
int x=3;
fun(x);
return 0;
}
I get this warning:
warning: control reaches end of non-void function
Why doesn't it return the value and call fun(x-1)?
But the below code works perfectly. I get 3 2 1 as output.
#include <iostream>
using namespace std;
int fun(int x){
if (x>0){
cout<<x<<endl;
return fun(x-1);
}
}
int main()
{
int x=3;
fun(x);
return 0;
}
| Once a function has return'ed, it can't execute any more code:
if (x>0){
return fun(x-1);
cout<<x<<endl; // <-- NEVER EXECUTED
}
The warning is because your function has a non-void return type, but is not return'ing any value when x is <= 0, thus causing undefined behavior.
Try this instead:
#include <iostream>
using namespace std;
int fun(int x){
if (x>0){
int ret = fun(x-1);
cout << x << endl;
return ret;
}
return 0;
}
int main()
{
fun(3);
return 0;
}
Online Demo
|
72,383,004 | 72,383,449 | Initialze a member of a C++ templated class only for specific type | Suppose I have a templated class like this:
template <typename C>
class ValArray
{
ValArray() = default;
ValArray(const ValArray&) = delete;
C& operator[](size_t pos) { return _values[pos]; }
...
private:
std::array<C, ARRAY_SIZE> _values;
};
This is instantiated with lots of different types. What I would like to do is initialize _values only for type bool but not for other types. So, if I create ValArray<bool> val then I want all elements to be false, for example:
std::array<bool, ARRAY_SIZE> _values = {false};
But for any other type, I don't want to initialize _values at all.
Is there some template magic I haven't been able to find that will allow this? I'm hoping to not have to create a separate class for this, as this would cascade to many other places where I'd have to create specializations.
| In C++17 and later, you can use if constexpr inside the constructor to assign the array elements, eg:
template <typename C>
class ValArray
{
public:
ValArray() {
if constexpr (std::is_same_v<C, bool>) {
_values.fill(false);
}
}
...
private:
std::array<C, ARRAY_SIZE> _values;
};
Online Demo
If C is bool, the constructor will be compiled as:
ValArray() { _values.fill(false); }
Otherwise it will be compiled as:
ValArray() {}
Prior to C++17, you can accomplish the same thing using SFINAE via std::enable_if, eg:
template <typename C>
class ValArray
{
public:
template<typename T = C, typename std::enable_if<std::is_same<T, bool>::value, int>::type = 0>
ValArray() { _values.fill(false); }
template<typename T = C, typename std::enable_if<!std::is_same<T, bool>::value, int>::type = 0>
ValArray() { }
// ...
private:
std::array<C, ARRAY_SIZE> _values;
};
Online Demo
|
72,383,007 | 72,383,327 | Speed of native R function vs C++ equivalent | When I compare the speed of the native Gamma function gamma in R to the C++ equivalent std::tgamma I find that the latter is about 10-15x slower. Why? I expect some differences, but this is huge, isn't it?
My implementation:
library("Rcpp")
library("microbenchmark")
cppFunction("
double gammacpp(double x) {
return(std::tgamma(x));
}
")
x = max(0, rnorm(1, 50, 25))
microbenchmark(gamma(x), gammacpp(x))
Results on my machine:
Unit: nanoseconds
expr min lq mean median uq max neval cld
gamma(x) 100 101 124.91 101 102 1001 100 a
gammacpp(x) 1000 1101 1302.98 1200 1300 9401 100 b
| Look at the code of gamma() (for example by typing gamma<Return>): it just calls a primitive.
Your Rcpp function is set up to be convenient. All it took was a two-liner. But it has some overhead is saving the state of the random-number generator, setting up the try/catch block for exception handling and more. We have documented how you can skip some of these steps, but in many cases that is ill-advised.
In a nutshell, my view is that you have a poorly chosen comparison: too little happens in the functions you benchmark. Also note the unit: nanoseconds. You have a lot of measurement error here.
But the morale is that with a 'naive' (and convenient) C++ function as the one you wrote as a one-liner, you will not beat somewhat optimised and tuned and already compiled code from inside R. That is actually a good thing because if you did, you would have to now rewrite large chunks of R .
Edit: For kicks, here is a third variant 'in the middle' where we use Rcpp to call the same C API of R.
Code
#include <Rcpp.h>
// [[Rcpp::export]]
double gammaStd(double x) { return (std::tgamma(x)); }
// [[Rcpp::export]]
Rcpp::NumericVector gamma_R(Rcpp::NumericVector x) { return (Rcpp::gamma(x)); }
/*** R
set.seed(123)
x <- max(0, rnorm(1, 50, 25))
res <- microbenchmark::microbenchmark(R = gamma(x), Cpp = gammaStd(x), Sugar = gamma_R(x) )
res
*/
Output
> Rcpp::sourceCpp("~/git/stackoverflow/72383007/answer.cpp")
> set.seed(123)
> x <- max(0, rnorm(1, 50, 25))
> res <- microbenchmark::microbenchmark(R = gamma(x), Cpp = gammaStd(x), Sugar = gamma_R(x) )
>
res
Unit: nanoseconds
expr min lq mean median uq max neval cld
R 102 112.0 136.95 124 134.5 1068 100 a
Cpp 1111 1155.5 11930.02 1186 1260.0 1054813 100 a
Sugar 1142 1201.0 6355.92 1246 1301.5 506628 100 a
>
|
72,383,405 | 72,383,570 | Question on while (true), while (cin >> x && x), while (cin >> x, x) | I have encountered a problem with this task:
your input is a number and the output is from 1 to the input number. If the number is zero, the output will be nothing.
For instance your input is
5
10
3
0
Your output will be
1 2 3 4 5
1 2 3 4 5 6 7 8 9 10
1 2 3
So, there are apparently three answers.
The first solution uses this:
#include <iostream>
using namespace std;
int main()
{
int x;
while (true)
{
cin >> x;
if (!x) break;
for (int i = 1; i <= x; i ++ ) cout << i << ' ';
cout << endl;
}
return 0;
}
The other two solutions replace this:
while (true)
{
cin >> x;
if (!x) break;
with this:
while (cin >> x && x)
or this:
while (cin >> x, x)
I understand the first solution, but not the other two.
Can someone help me?
| The >> operator, by convention, when applied to an istream object should return the istream object itself. So the return value of cin >> x is the cin object itself. When used as a Boolean, a stream object returns truthy if there are no errors in input/output.
while (cin >> x && x)
This says "while the loop successfully reads a value without errors and that value is not zero".
The comma operator is one of the more obscure pieces of C++ syntax. a , b evaluates a and then b and returns the result of b, discarding the result of a (this is assuming the comma doesn't do something else; for instance, in a function argument list the comma is part of that syntax, not its own operator). So cin >> x, x says "do the cin part, ignore the return value of that, and then check x".
while (cin >> x, x)
This says "get input and run as long as the input is nonzero". Crucially, errors in the input process are ignored here.
Minor note: Technically, programmers can overload the comma operator to call an arbitrary function. So if a programmer (whose mental health we might call into question) wrote a function like
void operator,(const istream& in, int x) {
// Something really stupid ...
}
Then that function would get called by cin >> x, x. But every C++ style guide I've ever seen recommends against ever overloading the comma operator, so this is pathological at best.
|
72,383,571 | 72,384,031 | Deducing a shared base of two classes in C++ | I am almost certain that what I'm looking for cannot be done without reflection, which is not yet in the language. But occasionally I'm getting surprised with exceptional answers in SO, so let's try.
Is it possible to deduce the "common_base" of two types that have a common shared base class, so the following would be possible (pseudo code! -- there is no common_base_t in the language, this is the magic I'm trying to achieve):
template<typename T1, typename T2>
const common_base_t<T1, T2>& foo(const T1& a1, const T2& a2) {
if(a1 < a2) return a1;
return a2;
}
Note that a1 and a2 above do not share a common_type, just by being siblings (sharing the same base) thus we cannot use the ternary operator.
Note also that changing the above return type to const auto& doesn't do the trick (it would not compile: inconsistent deduction for auto return type).
Here is a the naïve implementation, requiring the caller to state the expected return type:
template<typename R>
const R& foo(const auto& a1, const auto& a2) {
if(a1 < a2) return a1;
return a2;
}
Then we can call it with:
MyString1 s1 = "hello"; // MyString1 derives from std::string
MyString2 s2 = "world"; // MyString2 also derives from std::string
std::cout << foo<std::string>(s1, s2); // ok we return const lvalue ref
// pointing to one of the above objects
There are many reasons for why this probably cannot be achieved without providing the expected return value. But maybe it could be achieved somehow?
| The standard library's std::common_reference<> is tantalizingly close to what you want, and arguably what your foo() function should be using, as it clearly expresses the desired semantics:
template<typename T1, typename T2>
std::common_reference_t<const T1&, const T2&> foo(const T1& a1, const T2& a2) {
if(a1 < a2) return a1;
return a2;
}
Unfortunately, it doesn't work out of the box for this specific use-case, as it cannot detect common bases unless one of the types derives from the other.
However, you can give it a hint by specializing std::common_type. Like so:
namespace std {
template<>
struct common_type<MyString1, MyString2> {
using type = std::string;
};
}
And it will "just work". You can see it in action here: https://gcc.godbolt.org/z/e3PrecPac.
Edit:
It's worth mentioning that, depending on your circumstances, you could also create a general purpose specialization of std::common_type for all types that derive from a given base:
struct SomeBase {};
namespace std {
template<std::derived_from<SomeBase> T1, std::derived_from<SomeBase> T2>
struct common_type<T1, T2> {
using type = SomeBase;
};
}
However, I would thread lightly with this. It's a potentially very broad and wide-ranging partial specialization. It could easily lead to ambiguities, especially if done more than once.
|
72,383,979 | 72,384,080 | Dynamically allocate buffer[] for URLOpenBlockingStreamW() output | I'm super new to C++ and I'm trying to download an executable file from a URL and write it to disk.
I have the below code which successfully downloads the file and stores it in memory. The issue I am having is then writing that to disk.
I am pretty sure this is down to where I am creating the buffer where the downloaded data will be written to before being going to the new file.
char buffer[4096];
The 4096 is an arbitrary number from the template code I got elsewhere. What I can't figure out or don't know is how to dynamically allocate that buffer size based on the size of the data at &pStream.
I have tried using functions such as sizeof() but these just get me the memory address size rather than the value itself.
Alternatively, is there better way to try and accomplish this download and write?
#include <Windows.h>
#include <Urlmon.h> // URLOpenBlockingStreamW()
#include <atlbase.h> // CComPtr
#include <iostream>
#include "download.h"
#include <fstream>
#include <assert.h>
#include <chrono>
#include <thread>
#pragma comment( lib, "Urlmon.lib" )
struct ComInit
{
HRESULT hr;
ComInit() : hr(::CoInitialize(nullptr)) {}
~ComInit() { if (SUCCEEDED(hr)) ::CoUninitialize(); }
};
int download_file()
{
ComInit init;
HRESULT hr;
// use CComPtr so you don't have to manually call Release()
CComPtr<IStream> pStream;
bool success = false;
while (success == false)
{
try {
// Open the HTTP request.
hr = URLOpenBlockingStreamW(nullptr, L"https://www.foo.bar/download/somefile.exe", &pStream, 0, nullptr);
if (FAILED(hr))
{
std::cout << "ERROR: Could not connect. HRESULT: 0x" << std::hex << hr << std::dec << "\n";
}
else
{
success = true;
}
}
catch (const std::exception& ex) {
std::cout << ex.what();
}
}
// Download the response and write it to stdout.
char buffer[4096]; // Issue is here I think
do
{
DWORD bytesRead = 0;
hr = pStream->Read(buffer, sizeof(buffer), &bytesRead);
if (bytesRead > 0)
{
//std::cout.write(buffer, bytesRead);
std::ofstream file;
file.open("some_path_dot_exe", std::ios_base::binary);
assert(file.is_open());
for (int i = 0; i < sizeof(buffer) / sizeof(buffer[0]); ++i)
file.write((char*)(buffer + i * sizeof(buffer[0])), sizeof(buffer[0]));
file.close();
}
} while (SUCCEEDED(hr) && hr != S_FALSE);
if (FAILED(hr))
{
std::cout << "ERROR: Download failed. HRESULT: 0x" << std::hex << hr << std::dec << "\n";
return 2;
}
std::cout << "\n";
return 0;
}
| The IStream that URLOpenBlockingStreamW() gives you isn't guaranteed to be able to give you the full file size up front, so if you want to hold the entire file in memory, you will have to use std::vector or other dynamically-growing buffer.
Though, you don't actually need to hold the entire file in memory just to save it to disk, you can use a fixed array and write it to disk as it is being downloaded, as you already are doing.
The real problem is, you are opening and closing the file on every Read(), wiping out all previous data written. And you are ignoring the bytesRead value that Read() gives you.
You need to open the file one time, leave it open until you are done with the download, and don't write more than is actually in the buffer on each write().
Try this:
#include <Windows.h>
#include <Urlmon.h> // URLOpenBlockingStreamW()
#include <atlbase.h> // CComPtr
#include <iostream>
#include "download.h"
#include <fstream>
#include <assert.h>
#include <chrono>
#include <thread>
#pragma comment( lib, "Urlmon.lib" )
struct ComInit
{
HRESULT hr;
ComInit() : hr(::CoInitialize(nullptr)) {}
~ComInit() { if (SUCCEEDED(hr)) ::CoUninitialize(); }
};
int download_file()
{
ComInit init;
HRESULT hr;
// use CComPtr so you don't have to manually call Release()
CComPtr<IStream> pStream;
do
{
try {
// Open the HTTP request.
hr = URLOpenBlockingStreamW(nullptr, L"https://www.foo.bar/download/somefile.exe", &pStream, 0, nullptr);
if (SUCCEEDED(hr)) break;
std::cout << "ERROR: Could not connect. HRESULT: 0x" << std::hex << hr << std::dec << "\n";
}
catch (const std::exception& ex) {
std::cout << ex.what();
}
}
while (true);
std::ofstream file("some_path_dot_exe", std::ios_base::binary);
if (!file.is_open()) {
std::cout << "ERROR: Download failed. Unable to create output file.\n";
return 1;
}
// Download the response and write it to file.
char buffer[4096];
DWORD bytesRead;
do
{
hr = pStream->Read(buffer, sizeof(buffer), &bytesRead);
if (bytesRead > 0)
file.write(buffer, bytesRead);
} while (SUCCEEDED(hr) && hr != S_FALSE);
file.close();
if (FAILED(hr))
{
std::cout << "ERROR: Download failed. HRESULT: 0x" << std::hex << hr << std::dec << "\n";
return 2;
}
std::cout << "\n";
return 0;
}
|
72,384,300 | 72,384,883 | Access Violation when using OpenSSL's Camellia | I'm trying to write a camellia decryption program in windows using c++ as the language and OpenSSL as the cryptographic provider. When attempting to execute the code I get the following error Exception thrown at 0x00007FFABB31AEF8 (libcrypto-3-x64.dll) in Lab8.exe: 0xC0000005: Access violation reading location 0x0000000000000028.
The code is:
#include <iostream>
#include <windows.h>
#include <openssl/camellia.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <string.h>
#pragma warning(disable : 4996)
unsigned char iv[] = "\xd4\xc5\x91\xad\xe5\x7e\x56\x69\xcc\xcd\xb7\x11\xcf\x02\xec\xbc";
unsigned char camcipher[] = "\x00\xf7\x41\x73\x04\x5b\x99\xea\xe5\x6d\x41\x8e\xc4\x4d\x21\x5c";
const unsigned char camkey[] = "\x92\x63\x88\x77\x9b\x02\xad\x91\x3f\xd9\xd2\x45\xb1\x92\x21\x5f\x9d\x48\x35\xd5\x6e\xf0\xe7\x3a\x39\x26\xf7\x92\xf7\x89\x5d\x75";
unsigned char plaintext;
CAMELLIA_KEY finalkey;
int main()
{
Camellia_set_key(camkey, 256, &finalkey);
Camellia_cbc_encrypt(camcipher, (unsigned char*)plaintext, CAMELLIA_BLOCK_SIZE,&finalkey, iv, 0);
std::cout << plaintext;
}
The Key and IV were generated using urandom from python3 and then used to create the cipher text using the PyCryto library camellia.
I purposefully left the cipher text at 16 Bytes to avoid padding. I'm really not sure what I'm doing wrong at all. Any help would be awesome.
The plaintext should read "a secret message"
| Looks like you need to declare unsigned char plaintext; to be unsigned char plaintext[17];, otherwise you're overwriting uninitialized memory.
|
72,384,353 | 72,384,703 | How to get value from a vector by value from another vector? | I have two vectors:
one contains numbers and names of things;
second collects numbers that have already been showed to the user;
I'm trying to make a history list of all objects that have been shown.
Here is my code:
class palettArchive{
private:
std::vector<std::pair<int,std::string>> paletts;
int palletsCounter;
std::vector<int> choosen;
public:
//...
void history(){
auto printHist = [](int& i){
int tmp = i;
std::pair<int,std::string> tempPair = paletts[tmp];
std::cout << tempPair.first << " " << tempPair.second;
return 0;
};
std::for_each(choosen.begin(), choosen.end(), printHist);
}
};
There is an error:
error: 'this' cannot be implicitly captured in this context
std::pair<int,std::string> tempPair = paletts[tmp];
I can't make a third vector with the list that is created already. I need to make it by calling a function and printing at the time.
| for_each and lambda are just making your life difficult. The simpler code is explicit iteration:
void history()
{
for (auto i : choosen) {
auto tempPair = paletts[i];
std::cout << tempPair.first << " " << tempPair.second;
// did you mean to send a newline "\n" also?
}
}
|
72,384,672 | 72,384,696 | How can I avoid circular dependency in my Makefile compiling obj file with g++ and gcc? | I tried to create a makefile for a project that use c++ and c.
I need to compile those file in order to make de .o file, but when I compile using make I have circular dependency that is dropped.
I don't know why this error occurs as I tried to separate the building of .o files that comes from .c and .o files that comes froms .cpp files.
Here is my makefile :
SRC = $(wildcard *.c)
SRC++ = $(wildcard *.cpp)
OBJ = $(SRC++:.cpp=.o) $(SRC:.c=.o)
DEP = $(SRC:.c=.d) $(SRC++:.cpp=.d)
CC=gcc
CXX=g++
CFLAGS = -Wall
CXXFLAGS = -Wall
all: $(OBJ)
%.c : %.o
$(CC) -c $(CFLAGS) $< -o $@
%.cpp : %.o
$(CXX) -c $(CXXFLAGS) $< -o $@
# Clean the project
clean:
@rm -f $(OBJ) $(DEP)
-include $(DEP)
Do you have any idea of what I am doing wrong ?
| The rules you wrote are %.cpp : %.o and %.c : %.o. You wrote those rules the wrong way around. The target being built must be to the left of the colon, and the things it depends on must be to the right.
The error message tells you about a circular dependency because GNU Make defines an implicit rule where the dependencies are defined in the correct direction.
|
72,385,584 | 72,385,656 | C++ Linked list, program stuck when calling the next pointer in the list | I have made a linked list with c++.
I have no idea when trying to point to the next element of the list, the program stops.
My Node Class as follows:
class Node {
friend class List;
private :
Node* next;
public:
int value;
Node()
{
value = 0;
next = nullptr;
}
Node(int data)
{
this->value = data;
this->next = nullptr;
}
};
My List class has next and delete methods. Whenever there is calling for the next attributes in the Node class. The program stucks.
For my List Class I made them as follows:
class List {
private:
Node* head;
public:
List ()
{
head = 0; // create an empty list
}
~List ()
{
delete head; // clean up the list and all nodes
}
Node* first () const
{
return head;
}
Node* next(const Node* n) const{
return n->next;
}
void append(int i)
{
Node* newNode = new Node(i);
if (head == nullptr){
head = newNode;
}
else
{
Node *ptr = head;
// the loop sets ptr to last node of the linked list
while (ptr->next != nullptr){
ptr = ptr->next;
}
// ptr now points to the last node
// store temp address in the next of ptr
ptr->next = newNode;
}
}
void insert(Node* n, int i)
{
Node *ptr = head;
Node *newNode = new Node(i);
newNode->next = n;
if(n==head)
{
head = newNode;
}
else
{
while(ptr->next != n)
{
ptr = ptr->next;
}
ptr->next = newNode;
}
}
void erase( Node* n)
{
Node *ptr = head;
Node *before ;
if (n->next == nullptr)
{
free(n);
return ;
}
if(head == n)
{
head = n->next;
free(n);
return ;
}
else
{
while(ptr!= n)
{
before = ptr;
ptr = ptr->next ;
}
before->next = ptr;
free(ptr);
free(n);
return ;
}
}
void printLst()
{
while(head != nullptr)
{
std::cout<<head->value<<" ";
head = head->next;
}
}
};
and to get a full vision of program. I made the main function very simple:
int main()
{
List list;
list.append(55);
list.append(50);
list.append(20);
list.append(30);
list.insert(list.first(), 22);
list.insert(list.first(), 87);
list.printLst();
list.erase(list.first());
list.printLst();
}
Any suggestions ?
| in erase you never assign a value to 'before'
Node* before;
then you do
before->next = ptr;
Error C4703 potentially uninitialized local pointer variable 'before' used ConsoleApplication1 C:\work\ConsoleApplication1\ConsoleApplication1.cpp 124
also - more importantly your printLst function sets head to null
void printLst()
{
while (head != nullptr)
{
std::cout << head->value << " ";
head = head->next; <<========
}
}
your print function should not change head
so list.first then returns null so this
list.erase(list.first());
calls erase with null
Exception thrown: read access violation.
n was nullptr.
|
72,386,389 | 72,441,304 | Does a range based for loop over an array ODR-use the array? | When a range based for loop is used to iterate over an array, without binding a reference to each element, does this constitute an ODR-use of the array?
Example:
struct foo {
static constexpr int xs[] = { 1, 2, 3 };
};
int test(void) {
int sum = 0;
for (int x : foo::xs) // x is not a reference!
sum += x;
return sum;
}
// Definition, if needed
///constexpr foo::xs;
Is the definition of foo::xs necessary?
While this code, and variations of it, appear to work fine, that doesn't mean the definition is never necessary. Lack of a definition of an ODR-used variable rarely produces a diagnostic, since the variable could be defined in another translation unit. A linker error is the usual result, but it's quite possible to not get the error if the compiler is able to optimize away every use, which is what happens to the above code. The compiler effectively reduces test() to return 6;.
Binding a reference to an element would be an ODR-use, but that isn't done.
I was under impression that subscripting an array was not ODR-use in C++14 or later. But the range based for is not exactly subscripting.
In C++17, I believe this example avoids the problem because constexpr class data members are implicitly inline. And thus the declaration in the class also serves to define xs and an additional namespace scope definition isn't needed to satisfy ODR.
Some additional versions of the same question:
What if we use std::array?
constexpr std::array<int, 3> xs = { 1, 2, 3 };
What if we avoid the range based for?
for (int i = 0; i < foo::xs.size(); i++) sum += foo::xs[i];
|
Is the definition of foo::xs necessary?
Yes, because as NathanOliver points out in the comments, a reference is implicitly bound to foo::xs by the range-based for loop. When you bind a reference to an object, the object is odr-used. The same would occur if an std::array were used rather than a raw array.
What if we avoid the range based for?
Well, if you use a raw array and get its size using a technique that doesn't require binding a reference to it, then you can avoid providing a definition:
for (int i = 0; i < sizeof(foo::xs)/sizeof(foo::xs[0]); i++) {
sum += foo::xs[i];
}
In this case, the references inside sizeof are not odr-uses because they are unevaluated, and foo::xs is an element of the set of potential results of foo::xs[i]; this latter expression is of non-class type and immediately undergoes an lvalue-to-rvalue conversion, so it does not odr-use foo::xs.
|
72,386,590 | 72,386,897 | C++ unhandled Exception while checking ARGV values | Can someone tell me why this code worked 10 minutes ago but keeps failing now?
I keep getting unhandled exception error. In the debug menu I am entering 32 and 12.5.
The code fails each time I try to check i > 0;
bool CheckArgInputs(char* inputs[], int numInputs)
{
const char validChars[] = ".,+-eE0123456789";
bool tester = false;
for (int i = 0; *inputs[i] != 0; i++)
{
tester = false;
for (int j = 0; j < sizeof(validChars); j++)
{
if (*inputs[i] == validChars[j])
{
tester = true;
}
}
if (tester == false)
return false;
//else
// cout << "Good Input" << endl;
}
}
int main(int argc, char* argv[])
{
bool validInput = true;
for (int i = 1; i < argc; i++)
{
validInput = CheckArgInputs(&argv[i], argc);
if (validInput == false)
{
cout << "X" << endl;
return 0;
}
}
return 0;
}
| Your CheckArgInputs() function is coded to act like it is being given a pointer to an individual string, but main() is actually giving it a pointer to a pointer to a string. And then the function is not coded correctly to iterate the individual characters of just that string, it is actually iterating through the argv[] array one string at a time until it goes out of bounds of the array.
You are also not actually return'ing anything from CheckArgInputs() if the input string were valid.
Try this instead:
bool CheckArgInput(const char* input)
{
const char validChars[] = ".,+-eE0123456789";
for (int i = 0; input[i] != 0; i++)
{
for (int j = 0; j < sizeof(validChars)-1; j++)
{
if (input[i] != validChars[j])
{
return false;
}
}
}
return true;
}
int main(int argc, char* argv[])
{
bool validInput = true;
for (int i = 1; i < argc; i++)
{
validInput = CheckArgInput(argv[i]);
if (!validInput)
{
cout << "X" << endl;
return 0;
}
}
return 0;
}
|
72,387,132 | 72,387,238 | How to use void parameter when using template in C++ | I want to make a function to test the running time of the incoming function.
I use templates to make it applicable to many functions.
I omitted the code for counting time.
like this:
template<typename F>
void get_run_time(F func)
{
//time start
func;
//time end
}
But if a function I pass in is void, an error will be report and prompt me to add F=void.
I tried to add it, but it didn't work. I can change void to bool, but it's very strange.
Another problem is that I want to test a function time and run my whole code normally .So I increased the return value.
like this:
template<typename F>
F get_run_time(F func)
{
//time start
F tf=func;
//time end
return tf;
}
But the actual test time is obviously wrong. I guess it starts to run the function when it return .How can it get the running results before continuing with the following code?
| First, you need to call the passed function to actually time its execution. Note, in your code you do not call it, using the () call operator:
template <typename Func>
void timer1 (Func func)
{
// start timer
func();
// stop timer
}
Second, note these nuances:
// Will take the same time as the timer1
template <typename Func>
Func timer2 (Func func1)
{
// func2 is a copy of func1
// This copying won't increase the time as you thought it will
Func func2 = func1;
// You still need to call the function
func2();
// Returns pointer to function
return func2;
}
void foo() { std::cout << "foo()" << std::endl; }
int main() {
// Func, here, is a type void (*)()
// Prints "foo()"
timer2(foo);
}
Third, you may want to look toward this approach:
// Since C++14
auto timer3 = [](auto&& func, auto&&... args)
{
// start timer
// Forward the func and invoke the call operator
// with however many forwarded arguments passed to the timer3
std::forward<decltype(func)>(func)(std::forward<decltype(args)>(args)...);
// stop timer
};
void foo(int, int) {}
int main()
{
timer3(foo, 21, 42);
}
Even more proper and concise way to do the job, as noted by the @JHBonarius, is to use the std::invoke (since C++17), which was covered in this thread: What is std::invoke in C++?
|
72,387,375 | 72,387,391 | Error array bound is not an integer constant before ']' token | What am I doing wrong in this?
Error array bound is not an integer constant before ']' token
using namespace std;
bool cars_present[20];
int count = 0;
void sortArrayIntegers(int IDs[count]);
struct date
{
int day, month, year;
};
struct car
{
int ID;
char owner_name[20], owner_surname[20], make[20], model[20], phone_number[10];
struct date reg_date, ns_date;
}car_directory[100];
| void sortArrayIntegers(int IDs[count]);
Please try changing this line to
void sortArrayIntegers(int IDs[]);
You dont need to provide a value here
|
72,387,756 | 72,388,139 | supply custom hashing/equal func to unordered_map | I have this following code:
typedef std::size_t (*hash_func)(const sp_movie& movie);
typedef bool (*equal_func)(const sp_movie& m1,const sp_movie& m2);
typedef std::unordered_map<sp_movie, double, hash_func, equal_func> rank_map;
These are my actual functions I want to use in my unordered_map:
std::size_t sp_movie_hash(const sp_movie& movie);
bool sp_movie_equal(const sp_movie& m1,const sp_movie& m2);
How ever, I can't create a rank_map with my custom hash function and equal function I made.
I don't want to do it using classes for hash and equal, I just want to pass to the unordered_map the functions I've made.
I tried this code:
rank_map check (sp_movie, double, sp_movie_hash, sp_movie_equal);
rank_map check (sp_movie_hash, sp_movie_equal);
both of them didn't work
| The only suitable constructor is the one that also accepts bucket_count. Passing 0 seems to work:
rank_map check(0, sp_movie_hash, sp_movie_equal);
However, if you don't want to select the hash/equality functions at runtime, you should make them into functors (default-constructible classes). If you don't want to write the classes yourself, you can wrap the functions (surprisingly) in std::integral_constant:
using rank_map = std::unordered_map<sp_movie, double,
std::integral_constant<decltype(&sp_movie_hash), sp_movie_hash>,
std::integral_constant<decltype(&sp_movie_equal), sp_movie_equal>
>;
This makes your hash maps default-constructible, and removes the overhead of storing function pointers.
|
72,387,774 | 72,388,169 | Strange behavior about WEXITSTATUS with `G++ 4.9.4` | This code snippet below does compiles,
#include<sys/types.h>
#include<sys/wait.h>
#include<iostream>
int main()
{
int ret = 0xFFFF;
std::cout << WEXITSTATUS(ret);
}
whereas this code snippet does not compile indeed with G++ 4.9.4:
#include<sys/types.h>
#include<sys/wait.h>
#include<iostream>
int main()
{
std::cout << WEXITSTATUS(0xFFFF);
}
Here is what the compiler complains:
In file included from /usr/include/x86_64-linux-gnu/sys/wait.h:77:0,
from t.cpp:2:
t.cpp: In function ‘int main()’:
t.cpp:7:22: error: lvalue required as unary ‘&’ operand
std::cout << WEXITSTATUS(0xFFFF);
^
Here is the detail info about the compiler:
g++ --version
g++ (Ubuntu 4.9.4-2ubuntu1~16.04) 4.9.4
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
And the compiler is installed on Ubuntu16.04 by the commands below
sudo apt-get install gcc-4.9
sudo apt-get install g++-4.9
sudo update-alterntives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 20
sudo update-alterntives --install /usr/bin/g++ g++ /usr/bin/g++-4.9 20
Note:
I have to use g++-4.9, I have no other choice.
And It's strange that I could not reproduce the said phenomenon on godbolt.org. It compiles on godbolt.org with gcc 4.9.3(gcc 4.9.4 is not available).
Here is the output of g++ -E the_said_code_snippet_does_not_compile.cpp
//omit
# 4 "t.cpp" 2
int main()
{
std::cout << ((((*(const int *) &(0xFFFF))) & 0xff00) >> 8);
}
Could anybody shed some light on this matter?
UPDATED:
I can reproduce the error now!See this link.
UPDATED:
It's just a simplified example. What am I actually face is WEXITSTATUS(pclose(fp)) does not compile.
| The WEXITSTATUS macro is a matter of the C standard library implementation, not the compiler per se. Typically (and in the case of GCC) the compiler doesn't supply the C standard library implementation. It is an independent package.
Most Linux distributions, including Ubuntu, use glibc as C standard library implementation.
In glibc until version 2.23, inclusive, the macro was defined in the following way when using C++ and __USE_MISC is set (see commit link below):
# define __WAIT_INT(status) (*(const int *) &(status))
// ...
# define WEXITSTATUS(status) __WEXITSTATUS (__WAIT_INT (status))
The actual implementation of the macro is inside __WEXITSTATUS, but the use of __WAIT_INT seems to be for the purpose of supporting the non-POSIX "union wait" variant of the wait interface. With this definition, a prvalue cannot be used with the macro, because it tries to take the address of status.
In 2016, with commit b49ab5f4503f36dcbf43f821f817da66b2931fe6 support for union wait - according to the NEWS entry deprecated in the early 1990s - has been removed and now the definition is simply
# define WEXITSTATUS(status) __WEXITSTATUS (status)
Now it would work with a prvalue as well.
It seems that Ubuntu 16.04 still uses a glibc version from before that change, which isn't surprising since it was released at the time of the commit.
I don't know what POSIX has to say about whether or not it should be possible to use the macro with a int rvalue rather than the name of a variable.
That WEXITSTATUS can't always be used directly on a call to pclose seems to be known issue. Apparently the above-mentioned extension, which is now not present in glibc anymore, was (is?) also present in (some?) BSDs (and may originate from them?). See e.g. this question, in which the answer also expresses doubts about POSIX-compliance. However, OpenBSD, mentioned in the linked question, also removed union wait in 2014. According to the changelog it had been deprecated since 4.3BSD (released 1986).
|
72,387,925 | 72,387,973 | How to use an abstract class as the type of the index variable of a for each loop? | I was translating a Java program of mine to C++. I got to a problem trying to use polymorphism the same way as in Java.
My code looks something like this:
class Base
{
public:
virtual void print() = 0;
};
class Derived_1 : public Base
{
public:
void print()
{
std::cout << "1" << std::endl;
}
};
class Derived_2 : public Base
{
public:
void print()
{
std::cout << "2" << std::endl;
}
};
The next are two versions of my main method that I have tried, both give me compiler errors:
1:
int main(int argc, char const *argv[])
{
std::vector<Base> v;
v.push_back(Derived_1());
v.push_back(Derived_2());
for(Base i: v)
{
i.print();
}
return 0;
}
Error:
object of abstract class type "Base" is not allowed:C/C++(322)
main.cpp(35, 14): function "Base::print" is a pure virtual function
2:
int main(int argc, char const *argv[])
{
std::vector<Base*> v;
v.push_back(new Derived_1());
v.push_back(new Derived_2());
for(Base* i: v)
{
i.print();
}
return 0;
}
Error:
expression must have class type but it has type "Base *"C/C++(153)
How would you guys solve this?
| Coming from java to c++, there are a lot to take-care; Especially memory management!
In your first shown case, you are slicing the objects. See What is object slicing?
In order to access the virtual functions, you should have used std::vector<Base*> (i.e. vector of pointer to Base), or std::vector<std::unique_ptr<Base>> or std::vector<std::shared_ptr<Base>>(i.e. vector of smart pointer to Base).
In your second shown code, your v is a vector of pointer to Base, meaning you need to access the members via the -> operator.
i.e. You should have accessed the print() as follows:
i->print();
^^^
Or alternatively:
(*i).print();
^^^^^
Also note that:
In your second case, whatever you newed must be deleted, so that the program doesn't leak memory. Alternately, we have smart memory management
The Base is missing a virtual destructor, which will lead to undefined behavior when deleteing the ovjects. You should add one for defined behavior. See: When to use virtual destructors?
Using std::unique_ptr, your code will look like (example code):
#include <memory> // std::unique_ptr, std::make_unique
class Base
{
public:
virtual void print() /* const */ = 0;
// add a virtual destructor to the Base
virtual ~Base() = default;
};
class Derived_1 : public Base
{
public:
void print() override /* const */ {
std::cout << "1" << std::endl;
}
};
class Derived_2 : public Base
{
public:
void print() override /* const */ {
std::cout << "2" << std::endl;
}
};
int main()
{
std::vector<std::unique_ptr<Base>> v;
v.reserve(2); // for unwanted re-allocations of memory
v.emplace_back(std::make_unique<Derived_1>());
v.emplace_back(std::make_unique<Derived_2>());
for (const auto& i : v) // auto == std::unique_ptr<Base>
{
i->print();
}
return 0;
}
|
72,388,684 | 72,390,558 | Find the missing numbers in the given array |
Implement a function which takes an array of numbers from 1 to 10 and returns the numbers from 1 to 10 which are missing. examples input: [5,2,6] output: [1,3,4,7,8,9,10]
C++ program for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function to find the missing elements
void printMissingElements(int arr[], int N)
{
// Initialize diff
int diff = arr[0] - 0;
for (int i = 0; i < N; i++) {
// Check if diff and arr[i]-i
// both are equal or not
if (arr[i] - i != diff) {
// Loop for consecutive
// missing elements
while (diff < arr[i] - i) {
cout << i + diff << " ";
diff++;
}
}
}
}
Driver Code
int main()
{
// Given array arr[]
int arr[] = { 5,2,6 };
int N = sizeof(arr) / sizeof(int);
// Function Call
printMissingElements(arr, N);
return 0;
}
How to solve this question for the given input?
| By this approach we are using space to reduce execution time. Here the time complexity is O(N) where N is the no of elements given in the array and space complexity is O(1) i.e 10' .
#include<iostream>
void printMissingElements(int arr[], int n){
// Using 1D dp to solve this
int dp[11] = {0};
for(int i = 0; i < n; i++){
dp[arr[i]] = 1;
}
// Traverse through dp list and check for
// non set indexes
for(int i = 1; i <= 10; i++){
if (dp[i] != 1) std::cout << i << " ";
}
}
int main() {
int arr[] = {5,2,6};
int n = sizeof(arr) / sizeof(int);
printMissingElements(arr, n);
}
|
72,388,932 | 72,389,046 | Why does printf output characters instead of data? | Why does printf output characters instead of data?
Looking at the code, you can relatively understand what I want to do, but it is unclear why the output is like this
#include <vector>
#include <string>
#include <cstdio>
class Person
{
public:
Person(const std::string& name, uint16_t old)
: m_Name(name)
, m_Old(old)
{
}
public:
std::string GetName() const { return m_Name; }
uint16_t GetOld() const { return m_Old; }
private:
std::string m_Name;
uint16_t m_Old;
};
int main()
{
std::vector<Person> person = { Person("Kyle", 26), Person("Max", 20), Person("Josiah", 31) };
for (uint16_t i = 0; i < person.size(); ++i)
{
printf("Name: %s Old: %u\n", person[i].GetName(), person[i].GetOld());
}
return 0;
}
> // output
> Name: Ь·╣ Old: 1701607755
> Name: Ь·╣ Old: 7889229
> Name: Ь·╣ Old: 1769172810
| Using printf() with "%s" requires a (const) char* (or something that decays into a (const) char*, like (const) char[]).
std::string has a c_str() method which returns a char const* that you can pass to printf().
Therefore, your printf() line should be:
printf("Name: %s Old: %hu\n", person[i].GetName().c_str(), person[i].GetOld());
Note: I also changed %u to %hu - see @RemyLebeau's comment.
Alternatively, you can use C++'s std::cout stream to print the std::string as-is:
#include <iostream>
std::cout << "Name: " << person[i].GetName() << " Old: " << person[i].GetOld() << std::endl;
|
72,389,210 | 72,389,267 | I want to print all the data in the text file into the edit controller | I can take the text file string with "fgets" and print it out one line using "SetWindowTextA". Like This code
FILE *p_file = fopen("Test.txt", "r");
if (p_file != NULL) {
text = fgets(temp, sizeof(temp), p_file);
m_Edit_load.SetWindowTextA(text);
fclose(p_file)
}
But I want to print out all the lines. I've used the code at the bottom, but only the last line printed
FILE *p_file = fopen("Test.txt", "r");
if (p_file != NULL) {
while(NULL != fgets(temp, sizeof(temp), p_file){
m_Edit_load.SetWindowTextA(temp);
}
fclose(p_file);
}
How can I print out all the rows?
| Problem here is, SetWindowTextA is setting text, not appending. Hence, your window might be ending up with last line. To remove this problem, first create a dynamic array, append all characters, then call SetWindowTextA at last.
|
72,389,382 | 72,389,668 | Binary representation of a number, why so | int DecimalToBinary (int number){
int binary = 0, remainder = 0, i = 1;
while (number != 0){
remainder = number % 2;
number /= 2;
binary += remainder * i;
i *= 10;
}
return binary;
}
There is a function that represents numbers from decimal to binary. With the first two lines of the while loop everything seems clear, but then, I don't understand why we need binary += remainder * i, and why i *= 10.
Please explain why this is the case.
| Although comments have already explained the answer. Consider the following number i.e. abcd. This number can also be represented as
a*1000+b*100+c*10+d. This is the only purpose of line binary += remainder * i; and after every iteration we are multiplying i by 10 to increase the multiple. Hope it answered your query.
|
72,389,788 | 72,389,930 | Why can an array of char be a template parameter but a const char* can't | I'm trying to pass a literal string as a template parameter in a C++14 project. Google told me that I can do as below:
struct Test {
static const char teststr[];
template<const char* str>
void p() {std::cout << str;}
};
const char Test::teststr[] = "Hello world!";
int main() {
Test t;
t.p<Test::teststr>();
}
It did work.
However, if I use const char*, instead of const char []. It won't work.
struct Test {
static const char* teststr;
template<const char* str>
void p() {std::cout << str;}
};
const char* Test::teststr = "Hello world!";
int main() {
Test t;
t.p<Test::teststr>();
}
Now it doesn't work. The compiler told me that 'Test::teststr' is not a valid template argument because 'Test::teststr' is a variable, not the address of a variable.
Well, I don't know what it meant.
| The error message from the compiler is clear enough:
error: 'Test::teststr' is not a valid template argument because 'Test::teststr' is a variable, not the address of a variable
So you need:
#include <iostream>
struct Test {
static const char* teststr;
template<const char **str>
void p() {std::cout << *str;}
};
const char* Test::teststr = "Hello world!";
int main() {
Test t;
t.p <&Test::teststr>();
}
And then it works - the point being that [the contents of] a variable is not a compile-time constant, whereas the address of a variable (if it's a static or global variable) is.
|
72,390,142 | 72,393,426 | What happens if two distinct processes use mmap to map the same region of file (one with MAP_SHARED, another with MAP_PRIVATE)? | Can two distinct(not parent/child) processes use mmap to map the same region of file, the process A with flag MAP_SHARED, the process B with MAP_PRIVATE)?
If process A changes something in the region, can the process B see it?
| Then A gets the file mapped and B gets the file mapped but any writes will not be written back to the file.
From the manpage:
It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.
|
72,390,151 | 72,390,819 | How to use a 2d texture array in opengl | I am trying to load textures into a 2d array and than apply them.
But the screen only shows Black.
This is my code.
Creating Textures.
void int loadTexture(char const* path)
{
glCreateTextures(GL_TEXTURE_2D_ARRAY, 1, &textureID);
int width, height, nrComponents;
unsigned char* data1 = stbi_load("C:\\Temp\\RED.png" , &width, &height, &nrComponents, 0); // Load the first Image of size 512 X 512 (RGB)
unsigned char* data2 = stbi_load("C:\\Temp\\BLUE.png", &width, &height, &nrComponents, 0); // Load the second Image of size 512 X 512 (RGB)
glTextureStorage3D(textureID, 1, GL_RGB8, width, height, 2);
GLenum format;
format = GL_RGB;
glTextureSubImage3D(textureID, 1 , 0 , 0 , 1 , width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data1);
glTextureSubImage3D(textureID, 1 , 0, 0, 2, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data2);
glTextureParameteri(textureID, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(textureID, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTextureParameteri(textureID, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTextureParameteri(textureID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data1);
stbi_image_free(data2);
glBindTextureUnit(0, textureID);
}
Using the textures.
while (!glfwWindowShouldClose(window))
{
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Shader.use();
Shader.setFloat("textureUnit", 1); // Bind the first texture unit of the texture array
glBindTextureUnit(0, textureID);
renderQuad();
glfwSwapBuffers(window);
glfwPollEvents();
}
Vertex Shader.
#version 460 core
layout( location = 0)in vec2 aPos;
layout( location = 1 )in vec2 a_uv;
out vec2 f_uv;
void main() {
f_uv = a_uv;
gl_Position = vec4(aPos ,0.0, 1.0 );
};
Fragment Shader.
#version 460 core
uniform sampler2DArray u_tex;
in vec2 f_uv;
out vec4 FragColor;
uniform float textureUnit;
in vec2 TexCoord2;
void main() {
vec3 texCoordTest = vec3( f_uv.x , f_uv.y , textureUnit);
vec4 color = texture(u_tex , texCoordTest);
FragColor = color ;
};
| The 5th argument of glTextureSubImage3D is the zoffset. This is 0 for the 1st texture and 1 for the 2nd texture. The 2nd argument is the level not the number of levels:
glTextureSubImage3D(textureID, 1 , 0 , 0 , 1 , width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data1);
glTextureSubImage3D(textureID, 1 , 0, 0, 2, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data2);
glTextureSubImage3D(textureID, 0, 0, 0, 0, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data1);
glTextureSubImage3D(textureID, 0, 0, 0, 1, width, height, 1, GL_RGB, GL_UNSIGNED_BYTE, data2);
|
72,390,543 | 72,484,394 | Error C7626: Unnamed class used in typedef name cannot declare members other than non-static data members, | I am using C++ in VS2022 to build a project. I have to include a header file from an sdk named eve.h. I have added the include folder holding this file into the project properties.
However, when I build this project, I get a number of C7626 errors stating the following, and pointing to certain lines of the eve.h file.
Error C7626 unnamed class used in typedef name cannot declare members other than non-static data members, member enumerations, or member classes (compiling source file main.cpp)
The code in one of the lines the error points to is this:
typedef struct
{
int isOpen;
int clearAll;
int clearSome;
int buttonFifty=-1;
int buttonTwenty=-1;
}ALL_Buttons;
This is a header file in the sdk, it is not my code. And I have never come across this error before. How can I work this out? Thanks
| I solved this problem by giving the structures in the sdk names. As follows:
Before:
typedef struct
{
int isOpen;
int clearAll;
int clearSome;
int buttonFifty = -1;
int buttonTwenty = -1;
}
After:
typedef struct a
{
int isOpen;
int clearAll;
int clearSome;
int buttonFifty = -1;
int buttonTwenty = -1;
}
|
72,391,023 | 72,391,144 | istringstream skip next (n) word(s) | Is there a propper way in an isstrinstream to skip/ ignore the next, or even the next n words?
The possibility to read n times a variable seems to work, but is very clunky:
for (int i = 0; i < n; ++i)
{
std::string tmp;
some_stream >> tmp;
}
std::istream::ignore doesn't seem to do the job, as only n letters are skipped.
| It's clunky because it's not common enough to have gotten the appropriate attention to get a standard algorithm in place.
{
std::string tmp;
for(size_t i = 0; i < number_of_words_to_skip; ++i) some_stream >> tmp;
}
You can make it fancier by creating a null receiver:
std::copy_n(std::istream_iterator<std::string>(some_stream),
number_of_words_to_skip,
std::back_inserter(instance_of_something_that_does_not_do_anything));
Since the std library is void of such a receiver and adding it for this one case is likely to cause more confusion than your original solution., I'd say that the idiomatic approach, Today, is just to make a loop like above.
|
72,391,384 | 72,391,546 | Template parameter type `void` vs explicit use of `void` | In the following code why does the explicit expansion of template function foo fail to compile, yet the expansion of bar compiles successfully ? Live link - https://godbolt.org/z/o8Ea49KEb
template <typename T1, typename T2>
T1 foo(T2) { T2(42); return T1{}; };
template <typename T1, typename T2>
T1 bar(void) { T2(42); return T1{}; };
int main()
{
foo<int, void>(); // fails
bar<int, void>(); // works
}
Note that the template parameter T2 is used in the body of both functions and the only difference is that the function parameter to bar has been manually substituted.
This question was inspired after reading std::conditional - Invalid parameter type ‘void’ even when testing for 'void' and trying to simplify the issue.
| The rule saying a parameter list (void) is the same as the empty parameter list () is found in C++ Standard [dcl.fct]/4:
A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list. Except for this special case, a parameter shall not have type cv void.
The important piece for this question is "non-dependent type". The template parameter T is type-dependent, so it doesn't trigger the rule.
I presume the Standard has this rule because it would also be quite confusing (I'd say worse) if a template function which normally takes one parameter could suddenly become a zero-parameter function if an instantiation happens to make that parameter type void. With this rule, we know when a template is declared with a parameter, it really has one parameter.
|
72,392,699 | 72,398,871 | How to call a parameterless function using boost::json::value | I'm modifying from here code:
#include <boost/describe.hpp>
#include <boost/mp11.hpp>
#include <boost/json.hpp>
#include <boost/type_traits.hpp>
#include <boost/utility/string_view.hpp>
#include <stdexcept>
#include <string>
#include<iostream>
template<class C1, class C2, class R, class... A, std::size_t... I>
boost::json::value
call_impl_(C1& c1, R(C2::* pmf)(A...), boost::json::array const& args,
std::index_sequence<I...>)
{
return boost::json::value_from(
(c1.*pmf)(
boost::json::value_to< boost::remove_cv_ref_t<A> >(args[I])...));
}
template<class C1, class C2, class R, class... A>
boost::json::value
call_impl(C1& c1, R(C2::* pmf)(A...), boost::json::array const& args)
{
if (args.size() != sizeof...(A))
{
throw std::invalid_argument("Invalid number of arguments");
}
return call_impl_(c1, pmf, args, std::index_sequence_for<A...>());
}
template<class C>
boost::json::value
call(C& c, boost::string_view method, boost::json::value const& args)
{
using Fd = boost::describe::describe_members<C,
boost::describe::mod_public | boost::describe::mod_function>;
bool found = false;
boost::json::value result;
boost::mp11::mp_for_each<Fd>([&](auto D) {
if (!found && method == D.name)
{
result = call_impl(c, D.pointer, args.as_array());
found = true;
}
});
if (!found)
{
throw std::invalid_argument("Invalid method name");
}
return result;
}
struct Object
{
std::string greet(std::string const& who)
{
return "Hello, " + who + "!";
}
int add(int x, int y)
{
return x + y;
}
int foobar()
{
std::cout << "I'm stupid!" << std::endl;
return 1;
}
};
BOOST_DESCRIBE_STRUCT(Object, (), (greet, add, foobar))
int main()
{
Object obj;
std::cout << call(obj, "greet", { "world" }) << std::endl;
std::cout << call(obj, "add", { 1, 2 }) << std::endl;
boost::json::value sc{};
std::cout << call(obj, "add", sc) << std::endl;
}
The part I added is
int foobar()
{
std::cout << "I'm stupid!" << std::endl;
return 1;
}
and
boost::json::value sc{};
std::cout << call(obj, "foobar", sc) << std::endl;
output:
error C2672: 'call_impl': no matching overloaded function found
I know I can add an overload of call_impl and modify call to:
boost::mp11::mp_for_each<Fd>([&](auto D) {
if (!found && method == D.name)
{
auto temp = args.as_array();
std::cout << typeid(temp).name() << std::endl;
if (!temp.empty())
result = call_impl(c, D.pointer,temp );
else
result = call_impl(c, D.pointer);
found = true;
}});
my question here is:
how to construct a boost::json::value that contains empty values,so I can use it to call that function.
I think I've described my problem clearly, so many of my attempts and manipulations are so wrong that they don't need to be written, but it still warns me "It looks like your post is mostly code; please add some more details." ...
OS:windows11
IDE:visual studio2019
| The arguments are required to be passed as a JSON array. The simplest way to to fullfill the requirement is:
std::cout << call(obj, "foobar", boost::json::array{}) << std::endl;
See it Live On Coliru
#include <boost/describe.hpp>
#include <boost/json.hpp>
#include <boost/json/src.hpp> // for Coliru
#include <boost/mp11.hpp>
#include <boost/type_traits.hpp>
#include <boost/utility/string_view.hpp>
#include <iostream>
#include <stdexcept>
#include <string>
template <class C1, class C2, class R, class... A, std::size_t... I>
boost::json::value call_impl_(C1& c1, R (C2::*pmf)(A...),
boost::json::array const& args,
std::index_sequence<I...>) {
return boost::json::value_from((c1.*pmf)(
boost::json::value_to<boost::remove_cv_ref_t<A>>(args[I])...));
}
template <class C1, class C2, class R, class... A>
boost::json::value call_impl(C1& c1, R (C2::*pmf)(A...),
boost::json::array const& args) {
if (args.size() != sizeof...(A)) {
throw std::invalid_argument("Invalid number of arguments");
}
return call_impl_(c1, pmf, args, std::index_sequence_for<A...>());
}
template <class C>
boost::json::value call(C& c, boost::string_view method,
boost::json::value const& args) {
using Fd =
boost::describe::describe_members<C,
boost::describe::mod_public |
boost::describe::mod_function>;
bool found = false;
boost::json::value result;
boost::mp11::mp_for_each<Fd>([&](auto D) {
if (!found && method == D.name) {
result = call_impl(c, D.pointer, args.as_array());
found = true;
}
});
if (!found) {
throw std::invalid_argument("Invalid method name");
}
return result;
}
struct Object {
std::string greet(std::string const& who) {
return "Hello, " + who + "!";
}
int foobar() {
std::cout << "I'm not so stupid after all!" << std::endl;
return 42;
}
int add(int x, int y) {
return x + y;
}
};
BOOST_DESCRIBE_STRUCT(Object, (), (greet, add, foobar))
#include <iostream>
int main() {
Object obj;
std::cout << call(obj, "greet", {"world"}) << std::endl;
std::cout << call(obj, "add", {1, 2}) << std::endl;
std::cout << call(obj, "foobar", boost::json::array{}) << std::endl;
}
Prints
"Hello, world!"
3
I'm not so stupid after all!
42
Of course you can make that the default argument value: Live Demo but in reality, you would only use this in generic code, where you don't know in advance that a function has no parameters. So I don't think that adds any value.
|
72,392,738 | 72,393,748 | Any way to create an anonymous reference container in C++? | In python, we can simply using such code:
a = [1,2,3]
b = [4,5,6]
for m in [a, b]:
for e in m:
print(e)
"[a, b]" is an "anonymous" container which contains the "reference" of a and b, during the traverse, none of additional list is created so that the traverse is very effective.
Is there any way to do the same thing in C++? I've tried using vector to do it, but vector always copies objects instead of inferencing, and I haven't found such an "anonymous" way to do it.
| Not sure what C++ you're on.
C++17 onwards it can be done like this:
#include <vector>
#include <functional>
#include <iostream>
int main(int, char*[])
{
std::vector a{1,2,3};
std::vector b{3,4,5};
for ( auto&& v : std::vector{std::ref(a), std::ref(b)}) {
for (int& el : v.get()) {
std::cout <<el<<'\n';
}
}
}
https://godbolt.org/z/8rvh6snz1
C++11 and C++14 version is actually the same, except for the lack of template deduction, so it all gets longer:
std::vector<int> a{1,2,3};
std::vector<int> b{3,4,5};
std::vector<std::reference_wrapper<std::vector<int>>> m{std::ref(a), std::ref(b)};
A for C++98... there is no ranged for loop, reference wrapper is provided by Boost:
#include <vector>
#include <iostream>
#include <boost/core/ref.hpp>
int main(int, char*[])
{
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
std::vector<int> b;
b.push_back(4);
b.push_back(5);
b.push_back(6);
std::vector<boost::reference_wrapper<std::vector<int> > > m;
m.push_back(boost::ref(a));
m.push_back(boost::ref(b));
for(std::vector<boost::reference_wrapper<std::vector<int> > >::iterator it=m.begin(), e=m.end();
it!=e; ++it) {
for(std::vector<int>::iterator ii=(*it).get().begin(), ie=(*it).get().end();
ii!=ie; ++ii) {
std::cout << *ii << '\n';
}
}
}
https://godbolt.org/z/3n8jobz4h
Lots of other convenience functions are also provided by Boost, so feel free to have a closer look at it. I just wanted to limit its usage to the bare minimum.
|
72,393,020 | 72,393,091 | How to split a path to subpaths and store it in std::vector? | My question is how could I split my main path into several separate sub-paths and store it in a vector or list?
Example
I have path for example:
Assets/A/B/C
And I need to break them into separate sub-paths (or just strings):
Assets
A
B
C
And then stores it in std::vector. The last part i know how to do just push_back(s) where s is each subpath/string, but how to get this s?
Is there such a possibility in the standard library std::filesystem or do I need to find positions of two slashes myself and get a string within the boundaries of the first and next slash?
| A std::filesystem::path is iterable, so you can simply write:
for(auto p:path)
vector.push_back(p.string());
Or even shorter:
std::vector(path.begin(),path.end());
If you do not need strings, but a vector of subpaths is also accaptable.
|
72,393,147 | 72,401,259 | Nested ListView in Qml | I am trying to achieve this output [Refer snapshot :
click here]
I tried Using, since I am new to Qt not sure whether my approach of using repeater is right or wrong.
ListView {
id: outer
model: model1
delegate: model2
anchors.fill: parent
}
Component {
id: model1
Item {
Column{
Repeater {
model: 3
Rectangle {
id: rect
anchors.top: parent.bottom
width: 300
height: 30
color: listColor2[index]
}
}
}
}
}
Component {
id: model2
Column{
Repeater {
model: 4
Rectangle {
id: rect
width: 150
height: 30
color: listColor[index]
}
}
}
}
| I have found the solution to my problem.
Obtained output click here
Rectangle {
width: 360
height: 360
ListView {
id: outer
model: 4
delegate:
Rectangle {
id: rect
color: listColor[index]
width: 60
implicitHeight: col.height
Column{
id: col
anchors.left: rect.right
Repeater {
id: lv2
model: 4
Rectangle {
id: rect2
color: listColor2[index]
width: 200
height: 20
}
}
}
}
anchors.fill: parent
}
}
|
72,393,507 | 72,442,074 | Determine number of AVX-512 FMA units | Is there a possibility to determine the number of AVX-512 FMA units during runtime using C++?
I already have codes to determine if a CPU is capable of AVX-512, but I cannot determine the number of FMA units.
| The Intel® 64 and IA-32 Architectures Optimization Reference Manual, February 2022, Chapter 18.21 titled: Servers with a Single FMA Unit contains assembly language source code that identifies the number of AVX-512 FMA Units per core in an AVX-512 capable processor. See Example 18-25. This works by comparing the timing of two functions: one with FMA instructions and another with both FMA and shuffle instructions.
Intel's optimization manual can be downloaded from: https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html#inpage-nav-8.
The source code from this manual is available at: https://github.com/intel/optimization-manual
|
72,393,594 | 72,402,065 | How to set app icon for linux revisited and how does xfreerdp do it | I discovered that my appimag-ed application does not show any app icon in the window manager when launched, even though it has the icon inside itself. By the way, e.g., Obsidian app does suffer from this problem. In general, from searching on the Web, it looks like appimage fails with icons. Here e.g., a person also answers that appimage fails to provide app icons for a window manager: Electron Linux: .AppImage is not showing the icon, while .deb is. And also, when I load any app from https://appimage.github.io/apps/ -- at least on Fedora 33 and 35 -- I can see no app icons when launching them.
I tried to use workarounds like QMainWindow::setWindowIcon() or setting env variable XDG_DATA_DIRS, but it did not help -- these approaches can be found on appimage-related sites.
I discovered answers on SO like by these links:
Qt Creator - how to set application icon for ubuntu linux?
How do I give a C++ program an icon?
The idea of the answers is that you could not do such a thing and you have to install your .desktop file and icons to /usr/share via deb/rpm/etc. packages.
However, I discovered that it looks like xfreerdp carries its icon with it: I tried to change my system paths to icons (/usr/share/icons to /usr/share/icons_) temporarily and the xfreerdp's icon was still there in the window manager, while those of other apps grayed out. Also, I searched for .svg or .png icons of xfreerdp on the whole os and have not found anything.
So I an just curious how they can do it? I looked into its source code on Github, but could not understand. It's just an enigma for me really. Maybe, anybody has an idea how they do it or how this can be achieved at all?
| Here is an incomplete answer, since it only cover the X11 case and does not describe how to translate from QT object to X11 handles. I don't even know if this method will solve your specific problem.
The idea is to talk directly with X server to set the window icon, here, using the XCB API (same thing can be achieved using Xlib).
The X server need the bitmap data to be provided as 32 bit ARGB format, with two 32 bit unsigned integers ahead for image width and height. In a visual way, this what X server wait for:
4 bytes 4 bytes 4 bytes 4 bytes 4 bytes
[ WIDTH ][ HEIGHT ][ ARGB ][ ARGB ][ ARGB ]...
Indeed, if you load image from common encoded image format like PNG, JPEG or other, you'll need to properly decode image data to RGB(A), then convert bitmap to the proper ARGB format...
Here is the function to set the icon of any X windows. The first parameter c is the handle to the X server connection, the second w the handle/identifier (actually it is a simple integer) to X window. The third parameter icon_data is the icon data buffer as described above and the last parameter icon_size is the size, in bytes, of the buffer pointed by icon_data.
setWindowIcon(xcb_connection_t* c, xcb_window_t w, uint32_t* icon_data, size_t icon_size)
{
// get the _NET_WM_ICON atom
xcb_intern_atom_reply_t* r;
r = xcb_intern_atom_reply(c, xcb_intern_atom(c,1,12,"_NET_WM_ICON"), 0);
xcb_atom_t _NET_WM_ICON = r->atom;
free(r);
// get the CARDINAL atom
r = xcb_intern_atom_reply(c, xcb_intern_atom(c,1,8,"CARDINAL"), 0);
xcb_atom_t CARDINAL = r->atom;
free(r);
// change window property
xcb_change_property(c, XCB_PROP_MODE_REPLACE, w, _NET_WM_ICON, CARDINAL, 32, icon_size, icon_data);
// make sure everything is done
free(xcb_get_input_focus_reply(c, xcb_get_input_focus(c), NULL));
}
As you can see, the main purpose of this code is to modify/set a specific window property identified by _NET_WM_ICON. You'll find some information about this X specific protocol and syntax here :
https://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html
https://tronche.com/gui/x/xlib/window-information/properties-and-atoms.html
Notice that, I am not personally a great expert of X server protocols, I only digged some time ago this specific section for some low-level window management purpose.
|
72,393,901 | 72,394,038 | Passing 2D array as class parameter | I am trying to set up a class that initializes with a 2d array of an unknown size at compile time. I figured the best way to do this would be to pass the array as a pointer. This works as expected with a 1d array, but when I try to do the same with a 2d array. I get an error that states that it cannot convert argument 2 from 'char [3][3]' to 'char*'. Does anyone have a simple explanation on how I can get this to work? Here is my code.
TestClass.h:
#pragma once
#include <iostream>
class TestClass
{
public:
std::string name;
char *data;
TestClass(std::string name, char *data);
};
TestClass.cpp:
#include "TestClass.h"
TestClass::TestClass(std::string name, char *data)
{
this->name = name;
this->data = data;
}
Main.cpp:
#include "TestClass.h"
int main()
{
char TestArray[3][3] = {{ 'A', 'B', 'C' },
{ 'D', 'E', 'F' },
{ 'G', 'H', 'I' }};
TestClass Test("TestName", TestArray);
std::cout << Test.data[2] << std::endl;
return 1;
}
| You can pass a 2D array by passing the address of the first element:
TestClass Test("TestName", &TestArray[0][0]);
But how is TestClass supposed to know the dimensions of the array? There is no way to query the data or to guess. You have to also pass num_rows and num_cols.
But then I see:
std::cout << Test.data[2] << std::endl;
So now you want the 2D array to be a 1D array of C-style strings? That's is not what your data represents.
You really should forget about all the C-style cruft and use modern C++ construct. Use std::vector<std::string> to store a variable number of strings.
|
72,394,010 | 72,394,688 | How to choose an operator when making a simple calculator in C++? | I'm making a simple calculator in C++, but I'm having trouble choosing an operator, I wonder who can help me?
I'm using this code:
include <iostream>
using namespace std;
int main()
{
string operation = "";
cout << "enter operation:";
if(operation = "/"){
int x;
cin >> x;
int y;
cin >> y;
int sum = x / y;
}
if(operation = "+"){
int x;
cin >> x;
int y;
cin >> y;
int sum = x + y;
}
if(operation = "*"){
int x;
cin >> x;
int y;
cin >> y;
int sum = x * y;
}
if(operation = "-"){
int x;
cin >> x;
int y;
cin >> y;
int sum = x - y;
}
}
I dont know more programming. Who can help me?
| I think you're missing a line to read in the operation the user enters. After the line cout << "enter operation:";, you probably need cin >> operation.
A couple of other code improvements worth doing:
consider moving setting X and y outside the if statements, as you repeat the same code 4 times
consider using a switch statement rather than 4 if statements, as currently it will perform all 4 checks every time
as others have said, use == rather than =
|
72,394,948 | 72,395,509 | Use of operator()() without parentheses? | The following code is a dumbed down version of a wrapper around an object. I would like to be able to access the underlying Object seamlessly, that is, without the need for parentheses, as the comments describe:
struct A
{
void Func() {}
};
template <typename Object>
struct ObjectWrapper
{
ObjectWrapper(Object& o) : object_(&o) {}
operator Object& () { return *object_; }
Object& operator ()() { return *object_; }
Object* object_;
};
int main()
{
A a;
ObjectWrapper<A> obj(a);
//
// Trying to call Func() on the A object that 'obj' wraps...
//
obj.operator A& ().Func(); // Messy
obj().Func(); // Better but still has parentheses
// I really want to be able to say this:
// obj.Func()
// ...but cannot see how!
}
Can anyone please suggest a way of doing this?
| I think you need overload operator -> and/or * (this is how smart pointers are done):
template <typename Object>
struct ObjectWrapper {
ObjectWrapper(Object& o)
: object_(&o)
{
LOG();
}
Object* operator->() const
{
LOG();
return object_;
}
Object& operator*() const
{
LOG();
return *object_;
}
Object* object_;
};
int main()
{
A a;
ObjectWrapper<A> obj { a };
obj->Func();
(*obj).Func();
}
https://godbolt.org/z/ErEbxWE4P
|
72,395,229 | 72,395,816 | Trying to add an element to a dynamic array | i've tried to add an element from class type to an empty dynamic array, but nothing happens, nor it changes the counter after adding one element.
This is the function
void Bank::addCustomer(const Customer& newCustomer) {
Customer* temp = new Customer[getCustomerCount()+1];
for (int i = 0; i < getCustomerCount() + 1 ; ++i) {
if (getCustomerCount() != 0) {
temp[i] = customers[i];
}
}
++customerCount;
setCustomerCount(customerCount);
delete[] customers;
customers = temp;
customers[customerCount] = newCustomer;
//log
}
| Your loop is exceeding the bounds of the old array if it is not empty. And your assignment of the newCustomer is exceeding the bounds of the new array.
Try this instead:
void Bank::addCustomer(const Customer& newCustomer) {
int count = getCustomerCount();
Customer* temp = new Customer[count + 1];
for (int i = 0; i < count; ++i) {
temp[i] = customers[i];
}
temp[count] = newCustomer;
delete[] customers;
customers = temp;
++customerCount;
//log
}
|
72,395,266 | 72,395,390 | C++ Impossible nullptr call mystery | So I decided to get rid of singletons in my project and introduce dependency injection. I did all the necessary changes, and I got a little problem: no matter what I did, my NetworkService was called anyway, regardless of the fact it was initialised to nullptr. I started to investigate, and I got an impossible scenario. I'm feeling powerless, and I give up. I don't know how THIS code gets executed without issues:
auto impossible_response = ((NetworkService*)nullptr)->post(
format_url("/api/data/fetch/"),
payload.dump(),
headers);
log.crit("How did this succeeded? Please help me, StackOverflow");
Log message
I'm compiling my code on ArcoLinux with G++ (C++20) via Gradle. I've already tryied to rebuild it from scratch without any cache from previous builds.
|
Even If I try to dereference it on purpose, it DOES succeed.
No, the program has undefined behavior meaning it is still in error even if it doesn't say so explicitly and "seems to be working". This is due to the use of -> for dereferencing in your program.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
1For a more technically accurate definition of undefined behavior see this, where it is mentioned that: there are no restrictions on the behavior of the program.
|
72,395,426 | 72,395,635 | tbb::parallel_invoke excuting the functions only once | So I started learning TBB just today. I'm working on Ubuntu system, so installed TBB using sudo apt
sudo apt-get install libtbb-dev
now I'm trying to compile and run HELLO_TBB
#include <iostream>
#include <tbb/tbb.h>
int main() {
tbb::parallel_invoke(
[]() { std::cout << " Hello " << std::endl; },
[]() { std::cout << " TBB! " << std::endl; }
);
return 0;
}
and when trying to compile it I get the next note:
$ g++ Hello_TBB.cpp -o test -ltbb
In file included from Hello_TBB.cpp:2:
/usr/local/include/tbb/tbb.h:21:154: note: #pragma message: TBB Warning: tbb.h contains deprecated functionality. For details, please see Deprecated Features appendix in the TBB reference manual.
21 | ee Deprecated Features appendix in the TBB reference manual.")
and when running the code it actually prints Hello TBB only once!
is that how it works? or am I missing something? and what the deal with that note?
| Regarding the output:
tbb::parallel_invoke is a:
Function template that evaluates several functions in parallel.
As you can see in the link, you can pass several functions, and the tbb framework will attempt to run them in parallel (each function in a separate thread). Each of the functions will be executed once.
Note BTW that the level of parallelism is not guaranteed, and depends on your system properties and hardware.
In your case you passed 2 functions. One prints " Hello " and the other " TBB! ". they might run in parallel, but each will run once. So overall they will print these 2 strings once.
Regarding the note:
I am not familiar with it specifically. In general depracated functions are those which are discouraged to use since they will probably be removed in future versions. I don't think it is the case with tbb::parallel_invoke but you can verify in the documentation link above.
|
72,395,483 | 72,396,611 | How should I approach parsing the network packet using C++ template? | Let's say I have an application that keeps receiving the byte stream from the socket. I have the documentation that describes what the packet looks like. For example, the total header size, and total payload size, with the data type corresponding to different byte offsets. I want to parse it as a struct. The approach I can think of is that I will declare a struct and disable the padding by using some compiler macro, probably something like:
struct Payload
{
char field1;
uint32 field2;
uint32 field3;
char field5;
} __attribute__((packed));
and then I can declare a buffer and memcpy the bytes to the buffer and reinterpret_cast it to my structure. Another way I can think of is that process the bytes one by one and fill the data into the struct. I think either one should work but it is kind of old school and probably not safe.
The reinterpret_cast approach mentioned, should be something like:
void receive(const char*data, std::size_t data_size)
{
if(data_size == sizeof(payload)
{
const Payload* payload = reinterpret_cast<const Payload*>(data);
// ... further processing ...
}
}
I'm wondering are there any better approaches (more modern C++ style? more elegant?) for this kind of use case? I feel like using metaprogramming should help but I don't have an idea how to use it.
Can anyone share some thoughts? Or Point me to some related references or resources or even relevant open source code so that I can have a look and learn more about how to solve this kind of problem in a more elegant way.
| There are many different ways of approaching this. Here's one:
Keeping in mind that reading a struct from a network stream is semantically the same thing as reading a single value, the operation should look the same in either case.
Note that from what you posted, I am inferring that you will not be dealing with types with non-trivial default constructors. If that were the case, I would approach things a bit differently.
In this approach, we:
Define a read_into(src&, dst&) function that takes in a source of raw bytes, as well as an object to populate.
Provide a general implementation for all arithmetic types is provided, switching from network byte order when appropriate.
Overload the function for our struct, calling read_into() on each field in the order expected on the wire.
#include <cstdint>
#include <bit>
#include <concepts>
#include <array>
#include <algorithm>
// Use std::byteswap when available. In the meantime, just lift the implementation from
// https://en.cppreference.com/w/cpp/numeric/byteswap
template<std::integral T>
constexpr T byteswap(T value) noexcept
{
static_assert(std::has_unique_object_representations_v<T>, "T may not have padding bits");
auto value_representation = std::bit_cast<std::array<std::byte, sizeof(T)>>(value);
std::ranges::reverse(value_representation);
return std::bit_cast<T>(value_representation);
}
template<typename T>
concept DataSource = requires(T& x, char* dst, std::size_t size ) {
{x.read(dst, size)};
};
// General read implementation for all arithmetic types
template<std::endian network_order = std::endian::big>
void read_into(DataSource auto& src, std::integral auto& dst) {
src.read(reinterpret_cast<char*>(&dst), sizeof(dst));
if constexpr (sizeof(dst) > 1 && std::endian::native != network_order) {
dst = byteswap(dst);
}
}
struct Payload
{
char field1;
std::uint32_t field2;
std::uint32_t field3;
char field5;
};
// Read implementation specific to Payload
void read_into(DataSource auto& src, Payload& dst) {
read_into(src, dst.field1);
read_into<std::endian::little>(src, dst.field2);
read_into(src, dst.field3);
read_into(src, dst.field5);
}
// mind you, nothing stops you from just reading directly into the struct, but beware of endianness issues:
// struct Payload
// {
// char field1;
// std::uint32_t field2;
// std::uint32_t field3;
// char field5;
// } __attribute__((packed));
// void read_into(DataSource auto& src, Payload& dst) {
// src.read(reinterpret_cast<char*>(&dst), sizeof(Payload));
// }
// Example
struct some_data_source {
std::size_t read(char*, std::size_t size);
};
void foo() {
some_data_source data;
Payload p;
read_into(data, p);
}
An alternative API could have been dst.field2 = read<std::uint32_t>(src), which has the drawback of requiring to be explicit about the type, but is more appropriate if you have to deal with non-trivial constructors.
see it in action on godbolt: https://gcc.godbolt.org/z/77rvYE1qn
|
72,395,705 | 72,397,515 | c++: arithmetic operator overload | I have a class called HealthPoints that has hp and max_hp members. I want to overload the + operator so it will work like this:
HealthPoints healthPoints1;
healthPoints1 -= 150; /* healthPoints1 now has 0 points out of 100 */
HealthPoints healthPoints2(150);
healthPoints2 -= 160; /* healthPoints2 now has 0 points out of 150 */
healthPoints2 = healthPoints1 + 160; /* healthPoints2 now has 100 points out of 100 */
I succeeded in making it work, but only in a specific order. If I put the number before the object, is there any way to make it recognize the number between the two of them and act accordingly? The way it works at the moment, I get that healthPoints2 now has 160 points out of 160.
HealthPoints class:
class HealthPoints {
public:
static const int DEFAULT_MAXHP=100;
static const int DEFAULT_HP=100;
static const int MINIMUM_MAXHP=1;
static const int MINIMUM_HP=0;
explicit operator int() const;
HealthPoints(int maxHP=HealthPoints::DEFAULT_MAXHP);
~HealthPoints() = default; // Destructor set to default
HealthPoints(const HealthPoints&) = default; // Copy Constructor set to default
HealthPoints& operator=(const HealthPoints&) = default; // Assignment operator set to default
HealthPoints& operator+=(const HealthPoints& HP);
HealthPoints& operator-=(const HealthPoints& HP);
class InvalidArgument {};
private:
int m_maxHP;
int m_HP;
friend bool operator==(const HealthPoints& HP1, const HealthPoints& HP2);
friend bool operator<(const HealthPoints& HP1, const HealthPoints& HP2);
friend std::ostream& operator<<(std::ostream& os, const HealthPoints& HP);
};
HealthPoints::HealthPoints(int maxHP) {
if(maxHP < HealthPoints::MINIMUM_MAXHP) {
throw HealthPoints::InvalidArgument();
}
this->m_maxHP=maxHP;
this->m_HP=m_maxHP;
}
HealthPoints operator+(const HealthPoints& HP1, const HealthPoints& HP2) {
return HealthPoints(HP2)+=HP1;
}
HealthPoints operator-(const HealthPoints& HP1, const HealthPoints& HP2) {
return HealthPoints(HP1)-=HP2;
}
HealthPoints& HealthPoints::operator+=(const HealthPoints& HP) {
if(this->m_HP+HP.m_HP>this->m_maxHP) {
this->m_HP=this->m_maxHP;
} else {
this->m_HP+=HP.m_HP;
}
return *this;
}
HealthPoints& HealthPoints::operator-=(const HealthPoints& HP) {
if(this->m_HP-HP.m_HP>HealthPoints::MINIMUM_HP) {
this->m_HP-=HP.m_HP;
} else {
this->m_HP=HealthPoints::MINIMUM_HP;
}
return *this;
}
| In this statement:
healthPoints2 = healthPoints1 + 160;
Your + operator is creating a new HealthPoints object that is a copy of healthPoints1, thus the object's m_maxHP is set to 100. Then you are adding 160 to that object, increasing its m_HP but preserving its m_maxHP. Then you are assigning that object to healthPoints2, copying both m_HP and m_maxHP values. That is why the m_maxHP of healthPoints2 changes from 150 to 100.
In this statement:
healthPoints2 = 160 + healthPoints1;
Your + operator is creating a new HealthPoints object whose m_maxHP is set to 160. Then you are adding healthPoints1 to that object, increasing its m_HP but preserving its m_maxHP. Then you are assigning that object to healthPoints2, copying both m_HP and m_maxHP values. That is why the m_maxHP of healthPoints2 changes from 150 to 160.
If you want your operators to update only the m_HP and not change the m_maxHP, you need to add overloads that accept int values instead of HealthPoints objects, eg:
HealthPoints& HealthPoints::operator+=(int value) {
m_HP = std::min(m_HP + value, m_maxHP);
return *this;
}
HealthPoints& HealthPoints::operator-=(int value) {
m_HP = std::max(m_HP - value, HealthPoints::MINIMUM_HP);
return *this;
}
HealthPoints operator+(const HealthPoints& HP, int value) {
return HealthPoints(HP) += value;
}
HealthPoints operator+(int value, const HealthPoints& HP) {
return HealthPoints(HP) += value;
}
HealthPoints operator-(const HealthPoints& HP, int value) {
return HealthPoints(HP) -= value;
}
HealthPoints operator-(int value, const HealthPoints& HP) {
return HealthPoints(HP) -= value;
}
And then, mark the HealthPoints(int) constructor as explicit to avoid unwanted implicit conversions when passing int values to parameters that are expecting HealthPoints objects.
|
72,396,340 | 72,396,596 | OpenGL shader reader returns garbage characters | Why does this function:
string Utils::readShaderFile(const char* filePath) {
string content;
ifstream fileStream(filePath, ios::in);
string line = "";
while (!fileStream.eof()) {
getline(fileStream, line);
content.append(line + "\n");
}
fileStream.close();
return content;
}
returns
■#version 430
void main(void)
{
if (gl_VertexID == 0) gl_Position = vec4(0.25, -0.25, 0.0, 1.0);
else if (gl_VertexID == 1) gl_Position = vec4(-0.25, -0.25, 0.0, 1.0);
else gl_Position = vec4(0.25, 0.25, 0.0, 1.0);
}
with some garbage character at the first line?
I believe this is the reason why I get shader compilation errors:
Vertex Shader compilation error.
Shader Info Log: 0(1) : error C0000: syntax error, unexpected $undefined at token "<undefined>"
| So, the problem was with the fact that I created my shader .glsl files with Command's Prompt echo "" >> shader.glsl, which set some weird character at the beginning of the file.
After I have created the file through VS2019 add item option it worked well.
|
72,396,391 | 72,399,728 | compile-time variable-length objects based on string | Related SO questions:
variable size struct
string-based generator
Sadly neither one (or other similar ones) provide the solution I'm looking for.
Background
USB descriptors are (generally) byte-array structures. A "string descriptor" is defined as an array of bytes, that begins with a standard "header" of 2 bytes, followed by a string of UNICODE (16-bit) characters.
For example a USB string descriptor of value "AB" would have the following sequence of bytes:
0x06 0x03 0x41 0x00 0x42 0x00
where 0x06 is the total size of the descriptor (including the header), 0x03 is its "type" (defined by the standard)
Current (unsatisfactory) approach:
// other types omitted for clarity
enum UsbDescriptorType: uint8_t { USB_DESCR_STRING = 0x03 };
struct UsbDescrStd {
uint8_t bLength;
UsbDescriptorType bDescriptorType;
};
template<size_t N>
struct UsbDescrString final: UsbDescrStd {
char str[N * 2];
constexpr UsbDescrString(const char s[N]) noexcept
: UsbDescrStd{sizeof(*this), UsbDescriptorType::USB_DESCR_STRING}
, str {}
{
for(size_t i = 0; i < N; ++i)
str[i * 2] = s[i];
}
};
Below are the examples of its usage and short comments on why they are "not good enough" for me:
// requires size information
constexpr UsbDescrString<9> uds9{"Descr str"};
// string duplication
constexpr UsbDescrString<sizeof("Descr str")-1> udsa{"Descr str"};
// requires an explicit string storage
constexpr auto UsbDescrStrTxt{"Descr str"};
constexpr UsbDescrString<sizeof(UsbDescrStrTxt)-1> udsa2{UsbDescrStrTxt};
// ugly use of a macro
#define MAKE_UDS(name, s) UsbDescrString<sizeof(s)-1> name{s}
constexpr MAKE_UDS(udsm, "Descr str");
"String argument to template" is explicitly prohibited as of C++20, cutting that solution off as well.
What I'm trying to achieve
Ideally I'd love to be able to write code like the following:
constexpr UsbDescrString uds{"Descr str"}; // or a similar "terse" approach
It is simple, terse, error-resistant, and to the point. And I need help writing my UsbDescrString in a way that allows me to create compile-time objects without unnecessary code bloat.
| Adding a CTAD to UsbDescrString should be enough
template<size_t N>
struct UsbDescrString final: UsbDescrStd {
char str[N * 2];
constexpr UsbDescrString(const char (&s)[N+1]) noexcept
: UsbDescrStd{sizeof(*this), UsbDescriptorType::USB_DESCR_STRING}
, str {}
{
for(size_t i = 0; i < N; ++i)
str[i * 2] = s[i];
}
};
template<size_t N>
UsbDescrString(const char (&)[N]) -> UsbDescrString<N-1>;
Note that in order to prevent array to pointer decay, const char (&) needs to be used as the constructor parameter.
Demo
"String argument to template" is explicitly prohibited as of C++20,
cutting that solution off as well.
However, thanks to P0732, with the help of some helper classes such as basic_fixed_string, now in C++20 you can
template<fixed_string>
struct UsbDescrString final: UsbDescrStd;
constexpr UsbDescrString<"Descr str"> uds9;
|
72,396,857 | 72,396,951 | Optimization for specific argument without template | I ran into some optimized code that is fast, but it makes my code ugly.
A minimal example is as follows:
enum class Foo : char {
A = 'A',
B = 'B'
};
struct A_t {
constexpr operator Foo() const { return Foo::A; }
};
void function_v1(Foo s){
if(s == Foo::A){
//Run special version of the code
} else {
//Run other version of the code
}
}
template<class foo_t>
void function_v2(foo_t s){
if(s == Foo::A){
//Run special version of the code
} else {
//Run other version of the code
}
}
int main(){
// Version 1 of the function, simple call, no template
function_v1(Foo::A);
// Version 2 of the function, templated, but call is still simple
function_v2(Foo::A);
// Version 2 of the function, the argument is now not of type Foo, but of type A_t
const A_t a;
function_v2(a);
}
For that last function call function_v2 will be instantiated with a specific version for A_t. This may be bad for the size of the executable, but in experiments, I notice that the compiler is able to recognize that switch == Foo::A will always evaluate to true and the check is optimized away. Using gcc, This check is not optimized away in the other versions, even with -O3.
I'm working on an extremely performance intensive application, so such optimizations matter. However, I don't like the style of function_v2. To protect against calling the function with the wrong type, I would have to do something like enable_if to make sure the function isn't called with the wrong type. It complicates autocompletion because the type is now templated. And now the user needs to keep in mind to call the function using that specifically typed variable instead of the enum value.
Is there a way to write a function in the style of function_v1, but still have the compiler make different instantiations? Maybe a slightly different coding style? Or a compiler hint in the code? Or some compiler flag that will make the compiler more likely to make multiple instantiations?
|
Is there a way to write a function in the style of function_v1, but still have the compiler make different instantiations?
If we expand your example a bit to better reveal the compiler's behavior:
enum class Foo : char {
A = 'A',
B = 'B'
};
struct A_t {
constexpr operator Foo() const { return Foo::A; }
};
void foo();
void bar();
void function_v1(Foo s){
if(s == Foo::A){
foo();
} else {
bar();
}
}
template<class foo_t>
void function_v2(foo_t s){
if(s == Foo::A){
foo();
} else {
bar();
}
}
void test1(){
function_v1(Foo::A);
}
void test2(){
function_v2(Foo::A);
}
void test3(){
const A_t a;
function_v2(a);
}
And compile with -O3, we get:
test1(): # @test1()
jmp foo() # TAILCALL
test2(): # @test2()
jmp foo() # TAILCALL
test3(): # @test3()
jmp foo() # TAILCALL
See on godbolt.org: https://gcc.godbolt.org/z/443TqcczW
The resulting assembly for test1(), test2() and test3() are the exact same! What's going on here?
The if being optimized out in function_v2() has nothing to do with it being a template, but rather the fact that it is defined in a header (which is a necessity for templates), and the full implementation is visible at call sites.
All you have to do to get the same benefits for function_v1() is to define the function in a header and mark it as inline to avoid ODR violations. You will effectively get the exact same optimizations as are happening in function_v2().
All this gives you is equivalence though. If you want guarantees, you should forcefully provide the value at compile time, as a template parameter:
template<Foo s>
void function_v3() {
if constexpr (s == Foo::A) {
foo();
}
else {
bar();
}
}
// usage:
function_v3<Foo::A>();
If you still need a runtime-evaluated version of the function, you could do something along these lines:
decltype(auto) function_v3(Foo s) {
switch(s) {
case Foo::A:
return function_v3<Foo::A>();
case Foo::B:
return function_v3<Foo::B>();
}
}
// Forced compile-time switch
function_v3<Foo::A>();
// At the mercy of the optimizer.
function_v3(some_val);
|
72,398,772 | 72,398,929 | Is this quote from cppreference.com about implicit throw from a destructor a typo? | Does this quote from https://en.cppreference.com/w/cpp/language/function-try-block have a typo?
Reaching the end of a catch clause for a function-try-block on a destructor also automatically rethrows the current exception as if by throw;, but a return statement is allowed.
It seems hard to believe that a destructor automatically re-throws, when every article by every expert I've ever read says that destructors should never, ever throw under any circumstance. In fact, the example code above the quote shows an implicit throw from a constructor, not a destructor.
Therefore, I wonder, is the statement wrong and should have indicated that behavior for a constructor instead?
I had been reviewing this other StackOverflow article when I started thinking about this: C4297 warning in Visual Studio while using function-try-block (function assumed not to throw an exception but does). It already had an answer, but nobody questioned whether the quote was accurate in the first place.
| The answer is no, it is not a typo.
The cppreference article did not show an example of a destructor function try block, so I crafted one myself and tested it. Below is the same code. I tested with Microsoft VS2019, using the v142 platform toolset and C++20 dialect.
If you execute this, an abort will be called, which is consistent with the warning that the compiler issues. This suggests that the function catch block does automatically re-throw, even for a destructor. If you uncomment the return statement, it will not throw. Although, I find that to be counter-intuitive, writing a return statement provides a workaround to prevent the implicit throw, just as the referenced StackOverflow article suggests.
#include <iostream>
#include <string>
struct S
{
std::string m;
S(const std::string& str, int idx) try : m(str, idx)
{
std::cout << "S(" << str << ", " << idx << ") constructed, m = " << m << '\n';
}
catch (const std::exception& e)
{
std::cout << "S(" << str << ", " << idx << ") failed: " << e.what() << '\n';
} // implicit "throw;" here
~S() try
{
if (m.length() > 5) {
throw std::exception("shouldn't have been that big!");
}
std::cout << "destroyed!" << std::endl;
}
catch (const std::exception& e)
{
//return;
}
};
int main()
{
S s1{ "ABC", 1 }; // does not throw (index is in bounds)
try
{
S s2{ "ABC", 4 }; // throws (out of bounds)
}
catch (std::exception& e)
{
std::cout << "S s2... raised an exception: " << e.what() << '\n';
}
try
{
S s3("123456", 0);
}
catch (std::exception& e)
{
std::cout << "S s2... raised an exception: " << e.what() << '\n';
}
}
|
72,398,925 | 72,398,935 | error: use of deleted function 'Hund4::Hund4()' | I am a newbie in C++. I wrote this code to understand the difference between public, protected and private. The problem is, when I create an object of Hund4, I get this error:
use of deleted function
This error is in the last line.
Can you please help me to solve this problem?
#include <iostream>
#include <iostream>
#include <string>
using namespace std;
class Tier
{
public:
void wieMachtDasTier()
{
cout << "Hello\n";
}
protected:
void foo()
{
cout << "foo\n";
}
private:
void baz()
{
cout << "baz\n";
}
};
class Hund: public Tier
{
private:
string name;
public:
Hund(string newname):name(newname){}
string getname()
{
return this->name;
}
void test()
{
foo();
}
};
class Hund2: protected Tier
{
public:
void test()
{
foo();
}
};
class Hund3: private Tier
{
public:
void test()
{
foo();
}
};
class Hund4 : public Hund
{
};
int main()
{
Hund ace("ace");
ace.wieMachtDasTier();
Tier Haustier;
ace.test();
Hund2 ace2;
ace2.test();
Hund3 ace3;
ace3.test();
Hund4 ace4;
return 0;
}
| The Hund class that Hund4 derives from has no default constructor, so Hund4 has no default constructor. You can construct a Hund4 from a std::string or a Hund, though:
Hund4 ace4(std::string{"ace4"});
Hund4 ace4(Hund{"ace4"});
using std::literals;
Hund4 ace("Waldi"s);
For some reason, somebody else please explain why a const char * is sufficient for Hund but doesn't work for Hund4.
Or, you have to give Hund4 a constructor:
class Hund4 : public Hund
{
public:
Hund4(string newname) : Hund(newname) { }
};
Hund4 ace4("ace4");
|
72,399,427 | 72,399,535 | C++ Is it possible to overload a function so that its argument accept literal and reference respectively? | I'm having a problem with using C++ overloading and was wondering if anybody could help.
I'm trying to overload functions so that its argument accept reference and literal respectively.
For example, I want to overload func1 and func2 to func:
int func1 (int literal);
int func2 (int &reference);
and I want to use func in this situations:
func(3); // call func1
int val = 3;
func(val); // I want func2 to be called, but ambiguous error
Is there any way to overload these functions?
thanks! Any help would be appreciated!
sorry for poor english.
| Literals and temporary values can only be passed as const references while named values will prefer a non-const reference if available. You can use this with either & or && to create the 2 overloads.
For why and more details read up on rvalues, lvalues, xvalues, glvalues and prvalues.
The code below shows which function overload will be used for the most common cases, the first 2 being the ones you asked about:
#include <iostream>
void foo1(int &) { std::cout << "int &\n"; }
void foo1(const int &) { std::cout << "const int &\n"; }
void foo2(int &) { std::cout << "int &\n"; }
void foo2(const int &) { std::cout << "const int &\n"; }
void foo2(int &&) { std::cout << "int &&\n"; }
void foo2(const int &&) { std::cout << "const int &&\n"; }
int bla() { return 1; }
int main() {
int x{}, y{};
std::cout << "foo1:\n";
foo1(1);
foo1(x);
foo1(std::move(x));
foo1(bla());
std::cout << "\nfoo2:\n";
foo2(1);
foo2(y);
foo2(std::move(y));
foo2(bla());
}
Output:
foo1:
const int &
int &
const int &
const int &
foo2:
int &&
int &
int &&
int &&
|
72,399,510 | 72,400,381 | How to specify a default argument for a template parameter pack? | I have the following method
template <std::size_t N, std::size_t... Indices>
void doSomething()
{
...
};
It seems not possible to supply default values for Indices, e.g.
template <std::size_t N, std::size_t... Indices = std::make_index_sequence<N>>
void doSomething()
{
...
};
Compiler complains that
error: expected primary-expression before '>' token
template <std::size_t N, std::size_t... Indices = std::make_index_sequence<N>>
^~
error: template parameter pack 'Indices' cannot have a default argument
template <std::size_t N, std::size_t... Indices = std::make_index_sequence<N>>
^~~
Is there any way around this?
| There's already two excellent answers so far (including NathanOliver's comment). I think that having a couple of overloads that act as wrappers is really the simplest solution here, but just for completeness, let's provide your desired functionality in one function:
Often it's best to take as much of the template logic out of the parameter list as possible (separating inputs from logic):
template <std::size_t N, std::size_t... Indices>
void doSomething()
{
using Ints
= std::conditional_t<
/* if */ (sizeof...(Indices) > 0),
std::index_sequence<Indices...>,
/* else */
std::make_index_sequence<N>>;
// ...
};
demo
|
72,400,779 | 72,400,878 | Question about custom conversion of "lambda []void ()->void" | TestCase2 and TestCase3 can compile normally. However, in TestCase1 I get the following error:
E0312, Custom conversion from "lambda []void ()->void" to
"EventHandler" is not appropriate.
Why am I getting this error? I want to know how to solve it.
#include <functional>
#include <iostream>
class EventHandler
{
std::function<void()> _func;
public:
int id;
static int counter;
EventHandler() : id{ 0 } {}
EventHandler(const std::function<void()>& func) : _func{ func }
{
id = ++EventHandler::counter;
}
};
int EventHandler::counter = 0;
int main()
{
EventHandler TestCase1 = []() {};
EventHandler TestCase2([]() {});
EventHandler TestCase3 = static_cast<std::function<void()>>([]() {});
}
|
Why am I getting this error?
The lambda []() {} is not the same as std::function<void()>. That means
decltype([]() {}) != std::function<void()>
and it has to be implicitly or explicitly converted.
At the line
EventHandler TestCase1 = []() {};
copy initialization take place, where compiler first has to convert the lambda to a std::function<void()> and then a EventHandler object. Compiler can not do double implicit conventions.
Therefore, you need to be explicit here, like in TestCase3 for instance.
I want to know how to solve it.
One way is to provide a templated constructor (if you willing to)
#include <type_traits> // std::is_convertible_v
class EventHandler
{
std::function<void()> _func;
public:
template<typename Func> EventHandler(Func func)
: _func{ func }
{
static_assert(std::is_convertible_v<Func, decltype(_func)>
, "is not valid arg!");
// ....
}
// or in C++20 with <concepts> header
// template<typename Func> EventHandler(Func func)
// requires std::convertible_to<Func, decltype(_func)>
// : _func{ func }
// { ... }
};
Now you can
EventHandler TestCase1 = []() {}; // works
Demo
|
72,400,955 | 72,400,979 | Can i give a parameters on "cmd console?" | I want to utilize CMD console.
For example
If a.cpp is like below
int main(int argc, char* argv[]) {
for (int i = 0; i < argc; i++) {
cout << "argv : " << argv[i] << endl;
}
string path = "c:\\test";
vector<fs::path> v;
vector<fs::path>::iterator it;
for (auto& entry : fs::recursive_directory_iterator(path))
v.push_back(entry.path());
for (it = v.begin(); it != v.end(); ++it) {
cout << *it << endl;
}
and if I want to run a.exe by CMD console
it can be
C:\users> a.exe
and the result would be
"c:\\test\\test1"
"c:\\test\\test1\\test2"
"c:\\test\\test1\\test2\\lastdir"
"c:\\test\\test1\\test2\\lastdir2"
"c:\\test\\test1_1"
"c:\\test\\test1_1\\test1_txt.txt"
But What if I want to change path by CMD console
For example
C:\users> a.exe c:\\temp
and outputs will be
"c:\\temp\\temp_dir"
"c:\\temp\\temp_dir\\temp.txt"
"c:\\temp\\temp_dir2"
| You can do this portably since C++17 using
#include <filesystem>
std::filesystem::current_path(std::filesystem::path(path));
|
72,401,100 | 72,401,254 | Trying to understand why my C++ program is slowing down after running for long time | None of the threads close to the topic that I could find (like this one) helped me so far.
I have a C++ program that reads some data from a file, runs pretty complex and intensive operations and then writes outputs to new files. When I let the process run for few hours, here are the behaviours that I noticed:
The CPU usage is quite constant, but the RAM is slowly increasing until it reaches a sort of ceiling, then it becomes constant too.
The RAM usage 'ceiling' seems to increase depending on computer's RAM configuration. For example 3~4GB on a computer of 16GB of RAM, but 10~11GB on a computer of 64GB).
The average time to generate files of similar complexity increases over time and at some point becomes huge (giving the impression that the program is not running anymore).
When it starts slowing down that way, I kill the process and restart the generation of the same file (from scratch) with a fresh run of the program, and what took 3h before is finished in about 5min.
What can it be? I suspected memory leaking, but then wouldn't the RAM keep increasing indefinitely? What else can cause a program to progressively slow down, even when resources are available (CPU, RAM, disk space, etc.)?
|
I suspected memory leaking, but then wouldn't the RAM keep increasing
indefinitely?
It is increasing indefinitely, you just don't see it in the RAM usage statistics that you are looking at.
What happens is that the OS will keep allocating new physical RAM pages up until the observed ceiling point. At that point whenever your program requests new memory it will swap out some of the already allocated memory to disk before allocating a new physical memory in RAM. Thereby you free physical RAM by swapping to disk at about the same rate as you are allocating virtual memory due to your leak. Since the swapped out memory probably only contains leaked data, it is unlikely that it will ever be touched again by your program, so it just keeps sitting on the disk indefinitely. If you let the program run long enough, eventually you will run out of swap space on disk as well.
The constant I/O to the disk caused by the swapping is likely the root cause for the observed slowdown.
Use a memory analysis tool like LeakSanitizer or Valgrind to detect the memory leak. Once your program's memory consumption stops growing constantly, the performance problems should go away.
|
72,401,352 | 72,401,620 | How to draw grid line only in a circle using QGraphicsItem | Please forgive the poor English in advance.
hello! I am currently implementing view widget using QGraphicsView & QGraphicsItem.
Is there any way to draw gridlines only inside a circle?
Rectangles are fine, but trying to draw them inside a circle is a pain.
Below is sample code.
for(int x = rect.left(); x <= rect.right(); ++x) {
painter->drawLine(QPointF(x, rect.top()), QPointF(x, rect.bottom()));
}
for(int y = rect.top(); y <= rect.bottom(); ++y) {
painter->drawLine(QPointF(rect.left(), y), QPointF(rect.right(), y));
}
here is my current state --> Current grid line result
result what i want is looks like -->
Reuslt example what I want
I don't want to show grid line out of circle bound.
If you have any good ideas, please reply.
thank you!
| It's just a matter of tigronometry calculation. From the position on the X or Y axis you can calculate the angle to go to the point on the circle using arc sin and arc cosine. The code below should work
#include <math.h>
class Point
{
public:
double X = 0.0;
double Y = 0.0;
};
int main()
{
double radius = 10.0;
double stepx = 2.0;
double stepy = 2.0;
int stepsInX = radius / stepx;
int stepsInY = radius / stepy;
// this is just for positive X (need another loop for negative X)
for (int i = 0; i <= stepsInX; i++)
{
double angle = acos(i*stepx / radius);
double y = radius * sin(angle);
Point p1;
p1.X = i * stepx;
p1.Y = y;
Point p2;
p2.X = i * stepx;
p2.Y = -y;
drawLine(p1, p2);
}
// this is just for positive Y (need another loop for negative Y)
for (int i = 0; i <= stepsInY; i++)
{
double angle = asin(i * stepy / radius);
double x = radius * cos(angle);
Point p1;
p1.X = x;
p1.Y = i * stepy;
Point p2;
p2.X = -x;
p2.Y = i * stepy;
drawLine(p1, p2);
}
}
void drawLine(Point const& p1, Point const& p2)
{
// your code to draw line here
}
|
72,401,947 | 72,402,076 | Can std::future cause coredump without get or wait | void func() {
std::future<int> fut = std::async(std::launch::async, []{
std::this_thread::sleep_for(std::chrono::seconds(10));
return 8;
});
return;
}
Let's say that I have such a function. An object fut of std::future<int> is initialized with a std::async job, which will return an integer in the future. But the fut will be immediately released after the function func returns.
Is there such an issue: When the std::async job returns and try to assign the 8 to the object fut, the object has already been released...
If so, a coredump about SIGSEGV may occur...
Am I right about it? Or std::future has some mechanism to avoid this issue?
| Futures created with std::async have a blocking destructor that waits for the task to finish.
Even if you instead create a future from std::promise, the docs for ~future() don't mention the problem you're asking about.
The docs use the term "shared state" a lot, implying that a promise and a future share a (heap-allocated?) state, which holds the return value, and isn't destroyed until both die.
|
72,402,850 | 72,403,015 | If I declare the 'val' variable inside the loop then the code is not showing the desired output but when i put it outside loop it works fine. Reason? | In the below code, If I declare the variable val inside the loop then the code is not showing the desired output but when I put it outside the loop it works fine.
What can be the Reason?
#include <iostream>
using namespace std;
int main(){
int n ;
cin>>n ;
int row=1;
char val = 'A';
while(row<= n){
int col=1;
while(col<=n){
cout<< val ;
val = val+1;
col=col+1;
}
cout<<endl;
row=row+1 ;
}
}
| Your variable gets recreated in every iteration for while loop.
The scope of the variable is local inside the loop so whenever another iteration starts it creates a new copy.
In your case, if you put variable val inside the loop, it will be getting recreated with A as its value every time. But in global scope it only gets initialized once thus fulfilling your purpose.
You can refer to this Scope of variables for a better understanding.
|
72,403,492 | 72,403,609 | Why passing a string literal to a template calling std::format fails to compile? | The following code snippet fails to compile on the latest version of MSVC (Visual Studio 2022 17.2.2). The same snippet seemed to work just fine on previous compiler versions.
#include <iostream>
#include <format>
template <typename First, typename... Args>
inline auto format1(First&& first, Args&&... args) -> decltype(std::format(first, std::forward<Args>(args)...))
{
return std::format(std::forward<First>(first), std::forward<Args>(args)...);
}
int main()
{
std::cout << format1("hi {} {}", 123, 456);
}
The compiler emits the following error:
1>ConsoleApplication3.cpp(10,24): message : failure was caused by a
read of a variable outside its lifetime
1>ConsoleApplication3.cpp(10,24): message : see usage of 'first'
1>ConsoleApplication3.cpp(14): message : see reference to function
template instantiation 'std::string format<const
char(&)[9],int,int>(First,int &&,int &&)' being compiled 1>
with 1> [ 1> First=const char (&)[9] 1> ]
It seems that somehow forwarding a string literal to std::format makes the compiler think that they are used outside of their lifetime. I tried changing the function to accept const First& first and all sorts of other variants but the error remains.
As far as I understand, when First is deduced to a const reference, its lifetime should be extended to the scope of the invoked function.
So why do I get this error? How can I fix this?
Further investigating this, it seems like something specific to the use of std::format.
This snippet works fine when provided with a string literal:
template <std::size_t COUNT>
inline auto format2(const char (&first)[COUNT])
{
std::cout << first;
}
Wheras this one doesn't:
template <std::size_t COUNT>
inline auto format2(const char (&first)[COUNT])
{
std::format(first);
}
| After P2216, std::format requires that the format string must be a core constant expression. In your case, the compilation fails because the function argument First is not a constant expression.
The workaround is to use std::vformat, which works for runtime format strings
template<typename First, typename... Args>
auto format1(First&& first, Args&&... args) {
return std::vformat(
std::forward<First>(first),
std::make_format_args(std::forward<Args>(args)...));
}
Demo
If you really want to use std::format, you can pass in a lambda that returns a string literal
template<typename First, typename... Args>
auto format1(First first, Args&&... args) {
return std::format(first(), std::forward<Args>(args)...);
}
int main() {
std::cout << format1([]{ return "hi {} {}"; }, 123, 456);
}
Demo
|
72,403,729 | 72,403,924 | Why text.size() returns std::size_t and not std::string::size_type | I am studying c++ and currently reading C++ Primer (5th ed). I am on the topic about std::string. The size member returns the length of the string. The book says (p. 88)
auto len = line.size(); // len has type string::size_type
But Visual Studio Code identifies len as having the type std::size_t. Why is it different?
|
identifies len as having the type std::size_t. Why is it different?
From microsoft's basic_string documentation:
typedef typename allocator_type::size_type size_type;
Remarks
it's equivalent to allocator_type::size_type.
For type string, it's equivalent to size_t.
(emphasis mine)
Thus, as can be seen from the above quoted remark, for std::string, it is equivalent to size_t.
|
72,403,979 | 72,404,277 | Writing a clock(loop) that is triggered in the mhz consistently and effeciently for an emulator in modern C++ | I'm currently developing an emulator for an old CPU (intel 8085). Said CPU clock is 3.2mhz. I'm trying to be as accurate as possible, and as cross-platform as possible
To me, that means I need a clock that gets called with a frequency of 3.2mhz. I don't care about it being too accurate, anything within 10% accuracy is good enough.
The easy way is
auto _PrevCycleTime = std::chrono::high_resolution_clock::now();
double _TimeBetweenClockCycles = 1.0 / 3200000;
while (1)
{
auto now = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> t = std::chrono::duration_cast<std::chrono::duration<double>>(now - _PrevCycleTime);
if (t.count() >= _TimeBetweenClockCycles)
{
_PrevCycleTime = now;
//Clock trigger
}
}
That produces a clock that's called 2.4 million times a second.
The bigger problem is that I realised is that even running a while(1) {} uses 50-60% of my CPU. So that won't do.
My next approach is using a sleep function.
long long _TimeBetweenClockCyclesNS = 1000000000 / 3200000
double _TimeBetweenClockCycles = 1.0 / 3200000;
auto now = std::chrono::high_resolution_clock::now();
while (_Running)
{
std::chrono::duration<double> t = std::chrono::duration_cast<std::chrono::duration<double>>(now - _PrevCycleTime);
if (t.count() >= _TimeBetweenClockCycles)
{
_PrevCycleTime = now;
//Clock trigger
}
else
{
std::this_thread::sleep_for(std::chrono::nanoseconds(_TimeBetweenClockCyclesNS));
}
}
while that (somewhat) works, it's not consistent at all. I want it to be just "close enough", but the above code gets called:
100.000 times / second in Visual Studio debug mode (<3% cpu usage)
1.7 million times / second in Visual Studio debug mode using 1 nanosecond sleep time instead but again ~30% cpu usage.
100 times / second (yes, only 100, no other change in code) in Visual Studio Release mode (<1% cpu usage)
Even using std::this_thread::sleep_for(std::chrono::nanoseconds(1)) the clock is only triggered 1200 times a second.
I'm most likely missing something obvious and I'm over-complicating it but I'm sure there must be a better way, since other emulators of much "heavier" systems seem to use less CPU while requiring much more accuracy.
In my use case, I mostly care about:
Being cross-platform, but I don't mind writing different code for different OS
Not using an absurd amount of resources
I don't care about it not being very accurate, as long as it does not have too much of an effect on the timing of the CPU. (For example, if a "wait" routine is supposed to wait for 1 second, I don't really mind if it's 0.8 or 1.2 seconds)
What are my options?
(Note: Without any clock limiting logic, my clock can run more than 30 million times a second. Again, using about 50-60% of my CPU. So it should be able to run at 3million times at a much lower CPU usage)
(Note: The code runs in a separate std::thread if that matters)
| The important thing to recognize is that nobody can notice if some things happen at the wrong time. You have a CPU talking to some peripherals. Let's say the peripherals are GPIO pins. As long as the CPU turns the GPIO pins on and off at the right time, nobody can actually notice if the CPU is running too quickly in between those times. If it drives a display output, nobody can notice if the display pixels are calculated too quickly, as long as they are displayed at the right frame rate. And so on.
One technique used by emulators is to count up the number of clock cycles used by the CPU instructions. If you're using an interpreted design you can write clockCycles += 5; in the instruction handler. If you're using a JIT design you can do it at the end of each basic block. If you're not using a JIT design and you don't know what a basic block is, you can ignore the previous sentence.
Then, when the CPU actually does something that matters, like changing the GPIO pins, you can sleep to catch up. If 3,200,000 clock cycles happened since the last sleep, but it's only been 0.1 seconds of real time, then you can sleep for 0.9 seconds before updating the screen.
The less "sleep points" you have, the less accurate timing you have, and the less time you waste trying to maintain accurate timing. A video game emulator will typically render the whole frame as fast as possible. In fact since the N64/PS1 era, many emulators don't even bother emulating CPU timing at all. The timing on these systems is so complicated that every game already knows it has to wait for the next frame to start, so the emulator just has to start frames at the correct rate.
Another idea is to calculate and send timing information to the peripheral without actually timing it. Emulators for earlier systems (e.g. SNES) where games do rely on precise display timing can run the CPU at full speed and then tell the display code "at clock cycle 12345 the CPU wrote 0x6789 to register 12." The display code can then calculate which pixel the display was drawing on that clock cycle, and change how it's drawn. There's still no need to actually synchronize the CPU and display timing.
If you want precise timing without horribly slowing down the program, you might want to use an FPGA instead of a CPU.
|
72,404,136 | 72,405,335 | Read vector from file | I have a large vector of length 650 million. I wish to store this vector on disk (5 GB), then load the entire vector into memory so that various functions can quickly access its elements.
Here is my attempt to do this in Rcpp on a smaller scale. The following code simply causes my R session to crash, with no error messages. What am I doing wrong?
R code:
output_file = file(description="test.bin",open="a+b")
writeBin(runif(10), output_file,size=8)
close(output_file)
Rcpp code:
#include <Rcpp.h>
#include <fstream>
using namespace Rcpp;
std::vector<double> read_vector_from_file(std::string filename)
{
std::vector<char> buffer{};
std::ifstream ifs(filename, std::ios::in | std::ifstream::binary);
std::istreambuf_iterator<char> iter(ifs);
std::istreambuf_iterator<char> end{};
std::copy(iter, end, std::back_inserter(buffer));
std::vector<double> newVector(buffer.size() / sizeof(double));
memcpy(&newVector[0], &buffer[0], buffer.size());
return newVector;
}
std::vector<double> LT = read_vector_from_file("test.bin");
// [[Rcpp::export]]
double Rcpp_test() {
return LT[3];
}
| Over the years I have implemented something like the above a few times for quick and dirty data story. These days I no longer recommend it as we have fabulous packages such as fst and qs who do this better, with parallelisation, and compression, and other whistles.
But as you asked, an answer follows. I have found the C API for files to be simpler, and closer to what you do in R. So here we just open, and read 10 items of size 8 (for double) as that is what we know you wrote. I have at time generalized that and written two int values for an enum of types as well as numbers.
Code
#include <Rcpp.h>
#include <fstream>
using namespace Rcpp;
// [[Rcpp::export]]
Rcpp::NumericVector Rcpp_test(std::string filename, size_t size) {
Rcpp::NumericVector v(size);
FILE *in = fopen(filename.c_str(), "rb");
if (in == nullptr) Rcpp::stop("Cannot open file", filename);
auto nr = fread(&v[0], sizeof(double), size, in);
if (nr != size) Rcpp::stop("Bad payload");
Rcpp::Rcout << nr << std::endl;
fclose(in);
return v;
}
/*** R
set.seed(123)
rv <- runif(10)
filename <- "test.bin"
if (!file.exists(filename)) {
output_file <- file(description="test.bin",open="a+b")
writeBin(rv, output_file, size=8)
close(output_file)
}
nv <- Rcpp_test(filename, 10)
data.frame(rv, nv)
all.equal(rv,nv)
*/
Output
The code is a slight generalization by fixing the seed and comparing written and read data.
> Rcpp::sourceCpp("answer.cpp")
> set.seed(123)
> rv <- runif(10)
> filename <- "test.bin"
> if (!file.exists(filename)) {
+ output_file <- file(description="test.bin",open="a+b")
+ writeBin(rv, output_file, size=8)
+ close(output_file .... [TRUNCATED]
> nv <- Rcpp_test(filename, 10)
10
> data.frame(rv, nv)
rv nv
1 0.2875775 0.2875775
2 0.7883051 0.7883051
3 0.4089769 0.4089769
4 0.8830174 0.8830174
5 0.9404673 0.9404673
6 0.0455565 0.0455565
7 0.5281055 0.5281055
8 0.8924190 0.8924190
9 0.5514350 0.5514350
10 0.4566147 0.4566147
> all.equal(rv,nv)
[1] TRUE
>
|
72,404,916 | 72,411,340 | Reacting to each tick events from the websocket | I would like to design my trading system reacting to each tick events from the websocket stream i subscribed to.
So basically i have two options :
void WebsocketClient::on_write(beast::error_code ec,
std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
ws_.async_read(buffer_,
beast::bind_front_handler(&WebsocketClient::on_message,
shared_from_this()));
}
void WebsocketClient::on_message(beast::error_code ec,
std::size_t bytes_transferred) {
// signal generation and sending http request to place new orders here
// first before calling async_read() below
std::cout << "Received: " << beast::buffers_to_string(buffer_.cdata())
<< std::endl;
ws_.async_read(buffer_,
beast::bind_front_handler(&WebsocketClient::on_message,
shared_from_this()));
}
Or i could
void WebsocketClient::on_message(beast::error_code ec,
std::size_t bytes_transferred) {
ws_.async_read(buffer_,
beast::bind_front_handler(&WebsocketClient::on_message,
shared_from_this()));
// signal generation and sending http request to place new orders here after
// calling async_read()
std::cout << "Received: " << beast::buffers_to_string(buffer_.cdata())
<< std::endl;
}
please give me your suggestions and other ideas i could look at! advance thanks!
| There would be no tangible difference, unless
// signal generation and sending http request to place new orders here
// first before calling async_read() below
either
takes significant amount of time (design smell on IO threads)
exits the function by return/exception
That's because async_read by definition always returns immediately
|
72,404,944 | 72,409,615 | C++ exit code 3221225725, Karatsuba multiplication recursive algorithm | The Karatsuba multiplication algorithm implementation does not output any result and exits with code=3221225725.
Here is the message displayed on the terminal:
[Running] cd "d:\algorithms_cpp\" && g++ karatsube_mul.cpp -o karatsube_mul && "d:\algorithms_cpp\"karatsube_mul
[Done] exited with code=3221225725 in 1.941 seconds
Here is the code:
#include <bits/stdc++.h>
using namespace std;
string kara_mul(string n, string m)
{
int len_n = n.size();
int len_m = m.size();
if (len_n == 1 && len_m == 1)
{
return to_string((stol(n) * stol(m)));
}
string a = n.substr(0, len_n / 2);
string b = n.substr(len_n / 2);
string c = m.substr(0, len_m / 2);
string d = m.substr(len_m / 2);
string p1 = kara_mul(a, c);
string p2 = kara_mul(b, d);
string p3 = to_string((stol(kara_mul(a + b, c + d)) - stol(p1) - stol(p2)));
return to_string((stol(p1 + string(len_n, '0')) + stol(p2) + stol(p3 + string(len_n / 2, '0'))));
}
int main()
{
cout << kara_mul("15", "12") << "\n";
return 0;
}
And after fixing this I would also like to know how to multiply two 664 digit integers using this technique.
| There are several issues:
The exception you got is caused by infinite recursion at this call:
kara_mul(a + b, c + d)
As these variables are strings, the + is a string concatenation. This means these arguments evaluate to
n and m, which were the arguments to the current execution of the function.
The correct algorithm would perform a numerical addition here, for which you need to provide an implementation (adding two string representations of potentially very long integers)
if (len_n == 1 && len_m == 1) detects the base case, but the base case should kick in when either of these sizes is 1, not necessary both. So this should be an || operator, or should be written as two separate if statements.
The input strings should be split such that b and d are equal in size. This is not what your code does. Note how the Wikipedia article stresses this point:
The second argument of the split_at function specifies the number of digits to extract from the right
stol should never be called on strings that could potentially be too long for conversion to long. So for example, stol(p1) is not safe, as p1 could have 20 or more digits.
As a consequence of the previous point, you'll need to implement functions that add or subtract two string representations of numbers, and also one that can multiply a string representation with a single digit (the base case).
Here is an implementation that corrects these issues:
#include <iostream>
#include <algorithm>
int digit(std::string n, int i) {
return i >= n.size() ? 0 : n[n.size() - i - 1] - '0';
}
std::string add(std::string n, std::string m) {
int len = std::max(n.size(), m.size());
std::string result;
int carry = 0;
for (int i = 0; i < len; i++) {
int sum = digit(n, i) + digit(m, i) + carry;
result += (char) (sum % 10 + '0');
carry = sum >= 10;
}
if (carry) result += '1';
reverse(result.begin(), result.end());
return result;
}
std::string subtract(std::string n, std::string m) {
int len = n.size();
if (m.size() > len) throw std::invalid_argument("subtraction overflow");
if (n == m) return "0";
std::string result;
int carry = 0;
for (int i = 0; i < len; i++) {
int diff = digit(n, i) - digit(m, i) - carry;
carry = diff < 0;
result += (char) (diff + carry * 10 + '0');
}
if (carry) throw std::invalid_argument("subtraction overflow");
result.erase(result.find_last_not_of('0') + 1);
reverse(result.begin(), result.end());
return result;
}
std::string simple_mul(std::string n, int coefficient) {
if (coefficient < 2) return coefficient ? n : "0";
std::string result = simple_mul(add(n, n), coefficient / 2);
return coefficient % 2 ? add(result, n) : result;
}
std::string kara_mul(std::string n, std::string m) {
int len_n = n.size();
int len_m = m.size();
if (len_n == 1) return simple_mul(m, digit(n, 0));
if (len_m == 1) return simple_mul(n, digit(m, 0));
int len_min2 = std::min(len_n, len_m) / 2;
std::string a = n.substr(0, len_n - len_min2);
std::string b = n.substr(len_n - len_min2);
std::string c = m.substr(0, len_m - len_min2);
std::string d = m.substr(len_m - len_min2);
std::string p1 = kara_mul(a, c);
std::string p2 = kara_mul(b, d);
std::string p3 = subtract(kara_mul(add(a, b), add(c, d)), add(p1, p2));
return add(add(p1 + std::string(len_min2*2, '0'), p2), p3 + std::string(len_min2, '0'));
}
|
72,405,012 | 72,405,396 | Is it safe to pass this pointer in the initializer list in C++? | Edit: Code compiling now. Also added more detailed code to depict exact scenario.
Is it safe to pass this pointer in the initializer list ? Are there any chances of segmentation fault in case object methods are called before object is constructed? Or better to pass this pointer in constructor ? following are the example classes.
#include "iostream"
using namespace std;
class Observer
{
public:
Observer() = default;
protected:
Observer(const Observer& other) = default;
Observer(Observer&& other) = default;
Observer& operator=(const Observer& other) = default;
Observer& operator=(Observer&& other) = default;
public:
virtual ~Observer() = default;
virtual void method() const
{
}
};
class ThirdClass
{
public:
ThirdClass(const Observer* const first) : firstPtr{first}
{
// register for some events here.
// that events will call someMethod and someMethod is calling FirstClass's method, before initializer list of FirstClass gets executed.
}
void someMethod()
{
firstPtr->method();
}
static ThirdClass& getInstance(const Observer* const first)
{
static ThirdClass instance = ThirdClass(first);
return instance;
}
private:
const Observer* firstPtr{};
};
class FirstClass: public Observer
{
public:
FirstClass():third(ThirdClass::getInstance(this))
// init
// init
// some big initializer list which will take time to inilialize
{
}
virtual void method() const override
{
}
private:
const ThirdClass& third;
};
int main()
{
FirstClass firstObj;
return 0;
}
Assume the scenario like, Initializer list of FirstClass is very big and before its complete execution, event is fired(For which, third class is registered) and that event calls the someMethod() of ThirdClass. Does this will cause undefined behavior. Or there are not at all chances of Undefined Behaviour ?
PS: there is similar question here Is it safe to use the "this" pointer in an initialization list? But that mentions some parent child relationship.
| If the first variable, in ThirdClass's constructor is not used, only stored for future use, then this is safe and well defined. If you attempt to use/dereference the pointer in the constructor, then it would be undefined behaviour, since the FirstClass object has not been constructed yet.
In your example, you wrote:
register for some events here.
that events will call someMethod and someMethod is calling FirstClass's method, before initializer list of FirstClass gets executed.
Since this means that the object's method will be called, then this is likely not valid, and will be Undefined Behaviour, since you cannot call method of an uninitialized object (unless all members that function relies upon are initialized).
|
72,405,122 | 72,405,619 | Creating an Iterator with C++20 Concepts for custom container |
C++20 introduces concepts, a smart way to put constraints on the types a
template function or class can take in.
While iterator categories and properties remain the same, what changes is how you enforce them:
with tags until C++17, with concepts since C++20. For example, instead of the std::forward_iterator_tag tag
you would mark your iterator with the std::forward_iterator concept.
The same thing applies to all iterator properties.
For example, a Forward Iterator must be std::incrementable.
This new mechanism helps in getting better iterator definitions and makes errors from the compiler
much more readable.
This piece of text it's taken from this article:
https://www.internalpointers.com/post/writing-custom-iterators-modern-cpp
But the author didn't upgrade the content on how to make a custom iterator on C++20 with concepts, it remains the <= C++17 tags version.
Can someone make an example on how to write a custom iterator for a custom container in a C++20 version with the concept features?
| By and large, the C++20 way of defining iterators does away with explicitly tagging the type, and instead relies on concepts to just check that a given type happens to respect the iterator category's requirements.
This means that you can now safely duck-type your way to victory while supporting clean overload resolution and error messages:
struct my_iterator {
// No need for tagging or anything special, just implement the required interface.
};
If you want to ensure that a given type fulfills the requirements of a certain iterator category, you static_assert the concept on that type:
#include <iterator>
static_assert(std::forward_iterator<my_iterator>);
Enforcing that a function only accepts a certain iterator category is done by using the concept in your template arguments.
#include <iterator>
template<std::forward_iterator Ite, std::sentinel_for<Ite> Sen>
void my_algorithm(Ite begin, Sen end) {
// ...
}
std::sentinel_for<> is now used for the end iterator instead of using Ite twice. It allows to optionally use a separate type for the end iterator, which is sometimes convenient, especially for input iterators.
For example:
struct end_of_stream_t {};
constexpr end_of_stream_t end_of_stream{};
struct my_input_iterator {
// N.B. Not a complete implementation, just demonstrating sentinels.
some_stream_type* data_stream;
bool operator==(end_of_stream_t) const { return data_stream->empty(); }
};
template<std::input_iterator Ite, std::sentinel_for<Ite> Sen>
void my_algorithm(Ite begin, Sen end) {
while(begin != end) {
//...
}
}
void foo(some_stream_type& stream) {
my_algorithm(my_input_iterator{&stream}, end_of_stream);
}
|
72,405,350 | 72,405,537 | Error while printing structure array contents | Below code is not printing after 1st element of array. After printing first structure content the subsequent values are containing garbage values
#include <iostream>
using namespace std;
#define SMALL_STRING_LEN 20
#define TINY_STRING_LEN 10
enum data_item_type_t {
TYPE_FLOAT,
TYPE_INT,
TYPE_UINT
};
enum agent_type_t {
LOCATION,
};
enum sensor_type_t {
NOT_APPLICABLE,
};
typedef struct data_holder_conf {
int16_t data_id;
char description[SMALL_STRING_LEN];
int16_t num_items;
char unit[TINY_STRING_LEN];
data_item_type_t data_type;
agent_type_t agent;
sensor_type_t sensor;
/* pull frequency in milliseconds*/
uint32_t pull_freq;
} data_holder_conf_t;
data_holder_conf_t data_holder_conf_arr[] = {
{ 101, "altitude", 1, "metres", TYPE_FLOAT, LOCATION, NOT_APPLICABLE, 100 },
{ 102, "latitude", 1, "metres", TYPE_FLOAT, LOCATION, NOT_APPLICABLE, 100 },
{ 103, "longitude", 1, "metres", TYPE_FLOAT, LOCATION, NOT_APPLICABLE, 100 },
{ 104, "velocity", 1, "kmph", TYPE_FLOAT, LOCATION, NOT_APPLICABLE, 100 }
};
int main() {
data_holder_conf_t *ptrLocal = (data_holder_conf_t *)malloc(4 * sizeof(data_holder_conf_t));
memcpy(ptrLocal, data_holder_conf_arr, 4 * sizeof(data_holder_conf_t));
cout << "..........................................\n";
data_holder_conf_t *ptrTemp;
for (int i = 0; i < 4; i++) {
ptrTemp = (i * sizeof(data_holder_conf_t)) + ptrLocal;
cout << " data_id = " << ptrTemp->data_id << endl;
cout << " description = " << ptrTemp->description << endl;
cout << " num_items = " << ptrTemp->num_items << endl;
cout << " unit = " << ptrTemp->unit << endl;
cout << " data_type =" << ptrTemp->data_type << endl;
cout << " agent = " << ptrTemp->agent << endl;
cout << " sensor = " << ptrTemp->sensor << endl;
cout << " pull_freq = " << ptrTemp->pull_freq << endl;
}
free(ptrLocal);
}
I think there is problem while calculating the ptrTemp value.
But I am not able to figure out what is the mistake.
|
I think there is problem while calculating the ptrTemp value.
You presume right: your pointer arithmetic is incorrect: to get a pointer to the i-th entry, just use:
ptrTemp = ptrLocal + i;
or
ptrTemp = &ptrLocal[i];
|
72,405,712 | 72,414,275 | Unreal Engine 5 - C++ Classes disappear after exiting the editor | Whenever I exit the Unreal Engine 5 editor, I've noticed that when I open it up again, my various C++ classes disappear.
Fortunately, all I have to do is re-compile and they will be added back in again. However, it does become a serious inconvenience since I will have to re-attach it to any actors it was a component of and I have to re-do any Detail panel edits I did.
Let's say I'm trying to make a series of moving platforms move for my parkour game, so I make an ActorComponent called PlatformMover. I attach it to different platforms with their own velocities and directions. I then exit the Editor for the day and when I re-open it the next day, PlatformMover is gone. I then re-compile my project and PlatformMover is back, but I now have to re-attach it and re-configure it for every platform again.
It's really inconvenient, so is there any fix for this?
| I managed to find out that this is a rather common bug with live coding. Fortunately, the Unreal Engine course I've been taking actually has a video earlier in the course catalog that deals with this, and I can report that the solution provided worked for me.
Close the editor immediately but leave the IDE open.
Build the code with [Project Name]Editor Win64 Development Build.
(Emphasis on the "Editor" part at the end. I thought this didn't work until I realized that I was actually using "[Project Name] Win64" instead of "[ProjectName]Editor Win64"
Open the project again.
|
72,406,065 | 72,406,332 | Counter and ID attribute of class stored in vector | I have a dilemma regarding my removing database function code.
Whenever I remove the database in vector with unique, I cannot think of writing the code that could fill the gap with the removed number (like I removed database ID3 and I want that the IDs of further databases would increment to have a stable sequence, so the database with ID4 would become ID3).
I also don't know how to decrement my static int counter.
File:
**void Database::Rem()
{
int dddddet;
cin >> dddddet;
if (iter != DbMain.end())
{
DbMain.erase(iter);
}
}**
std::istream &operator>>(std::istream &re, Base &product)
{
}
}
std::ostream &printnames(std::ostream &pr, Base &pro)
{
pr << "\nID:" << pro.ID << "\nName:" << pro.name;
return pr;
}
Header file:
"
| The thing you're doing here is called a design anti-pattern: Some structural idea that you could easily come up with in a lot of situations, but that's going to be a lot of trouble (i.e., bad). It's called a singleton: You're assuming there's only ever going to be one DbMain, so you store the length of that in a "global-alike" static member. Makes no sense! Simply use the length of DbMain. You should never need a global or a static member to count objects that you store centrally, anyways.
You never actually need the ID to be part of the object you store – its whole purpose is being the index within the dBMain storage. A vector is already ordered! So, instead of printing your .ID when you iterate through the vector, simply print the position in the vector. Instead of "find the base with ID == N and erase" you could do "erase the (DbMain.begin() + N) element" and be done with it.
|
72,406,475 | 72,406,610 | 'cd ..' is not working in system("") in c++ code running in ubantu environment | Currently I am in test directory and I am trying to change directory from test to src and run another .so file
below is the code
system("cd ..");
system("cd src");
system("./shapessenderros2");
folder structure is
test and src folders are in same directory
| Each system call creates a new sub shell and whatever you do to the envionment of such a shell will not affect any other sibling shells. Each process inherits the environment from the parent process. You could get around the problem by running all the commands in the same shell:
system("cd ../src;./shapessenderros2");
or, only execute the command if cd succeeds:
system("cd ../src && ./shapessenderros2");
Or set the correct directory before calling system:
#include <cstdlib>
#include <filesystem>
// ...
auto owd = std::filesystem::current_path(); // save the current directory
std::filesystem::current_path("../src"); // change directory
std::system("./shapessenderros2"); // run the command
std::filesystem::current_path(owd); // set the directory back
|
72,406,614 | 72,406,718 | Passing the address of an array into a function in C++ | I'm new to c++ and I am confused by the idea of passing a pointer array into a function.
Here's the function
void func(int *a){ a[0]=999;}
which is used by the main
int main()
{
int a[5]={1,2,3,4,5};
func(a);
std::cout << a[0]<< std::endl;
}
I understand this works perfectly as the name of an array is just the address of its first element.
Based on my understanding, &a refers to the address of the entire array while a refers to the address of the first element of the array, which should be identical to &a.
However, if I use
int main(){
int a[5]={1,2,3,4,5};
func(&a);
cout<< a[0]<< endl;
}
It returns the compiler error: no known conversion from 'int (*)[10]' to 'int *' for 1st argument; remove &
Could anyone please explain what's going on here?
| Case 1
I understand this works perfectly as the name of an array is just the address of its first element.
The above statement is not technically correct. The first example worked because in many contexts(including when passing an array as an argument by value to a function) the array decays to a pointer to its first element due to type decay. This means, in example 1, when you passed a as an argument, there was an implicit array-to-pointer conversion which converted your array a of type int[5] to a pointer to its first element which is the type int*. Thus in example 1, the type of the argument and the type of the parameter matches and example 1 succeeded.
Note also that even though the decayed pointer and the address of the array both have the same value their types are different. The decayed pointer is of type int* while the &a is of type int (*)[5].
Case 2
Could anyone please explain what's going on here?
This is because a is of type int [5] which means &a is of type int (*)[5] which doesn't match with the type of the parameter int*.
That is, when you modified your code, you were passing &a which is of type int (*)[5] but the function parameter is of type int* and hence there is a mismatch in the type of the parameter and the argument you're passing and as there is no implicit conversion from a int (*)[5] to an int* we get the mentioned error saying:
no known conversion from 'int (*)[5]' to 'int *'
|
72,406,830 | 72,407,185 | How to correctly forward and use a nested tuple of constexpr struct with standard tuple operations | I want to store passed data via constexpr constructor of a struct, and store the data in a std::tuple, to perform various TMP / compile time operations.
Implementation
template <typename... _Ts>
struct myInitializer {
std::tuple<_Ts...> init_data;
constexpr myInitializer(_Ts&&... _Vs)
: init_data{ std::tuple(std::forward<_Ts>(_Vs)...) }
{}
};
Stored data uses a lightweight strong type struct, generated via lvalue and rvalue helper overload:
template <typename T, typename... Ts>
struct data_of_t {
using type = T;
using data_t = std::tuple<Ts...>;
data_t data;
constexpr data_of_t(Ts&&... _vs)
: data(std::forward<Ts>(_vs)...)
{}
};
template<typename T, typename... Ts>
constexpr auto data_of(Ts&&... _vs) {
return data_of_t<T, Ts...>(std::forward<Ts>(_vs)...);
};
template<typename T, typename... Ts>
constexpr auto data_of(Ts&... _vs) {
return data_of_t<T, Ts...>(std::forward<Ts>(_vs)...);
};
It's implemented like
template <typename T = int>
class test {
public:
static constexpr auto func(int p0=0, int p1=1, int p2=3) noexcept {
return data_of <test<T>>
(data_of<test<T>>(p0, p1));
}
};
int main() {
constexpr // fails to run constexpr // works without
auto init = myInitializer (
test<int>::func()
,test<int>::func(3)
,test<int>::func(4,5)
);
std::apply([&](auto&&... args) {
//std::cout << __PRETTY_FUNCTION__ << std::endl;
auto merged_tuple = std::tuple_cat(std::forward<decltype(args.data)>(args.data)...);
}
, init.init_data);
}
Getting to the point
std::tuple_cat fails if myInitializer instance is constexpr.
std::apply([&](auto&&... args) {
auto merged_tuple = std::tuple_cat(std::forward<decltype(args.data)>(args.data)...);
It appears to be related to the const qualifier added via constexpr.
How can this be fixed?
See full example at https://godbolt.org/z/j5xdT39aE
| In addition of the forwarding problem denoted by Barry, there's a different reason why you cannot have constexpr on init. This is because you contain a reference to a temporary inside data_of_t.
You see, you are containing a type obtained from overload resolution from a forwarding reference:
template<typename T, typename... Ts>
constexpr auto data_of(Ts&&... _vs) {
return data_of_t<T, Ts...>(std::forward<Ts>(_vs)...);
};
The Ts... in this case could be something like int, float const&, double&. You send those reference type and then you contain them inside of the std::tuple in data_of_t.
Those temporaries are local variables from the test function:
template <typename T = int>
class test {
public:
static constexpr auto func(int p0=0, int p1=1, int p2=3) noexcept {
return data_of <test<T>>
(data_of<test<T>>(p0, p1));
}
};
The problem here is that p0, p1, p2 are all local variable. You send them in test_of_t which will contain references to them, and you return the object containing all those reference to the local variable. This is maybe the cause of the MSVC crash. Compiler are required to provide diagnostic for any undefined behaviour in constexpr context. This crash is 100% a compiler bug and you should report it.
So how do you fix that?
Simply don't contain references by changing data_of:
template<typename T, typename... Ts>
constexpr auto data_of(Ts&&... _vs) {
return data_of_t<T, std::decay_t<Ts>...>(std::forward<Ts>(_vs)...);
};
This will decay the type thus removing the references and decay any reference to C array to pointers.
Then, you have to change your constructor. You call std::forward in there but it's no forwarding occurring if you decay in the template arguments.
template<typename... Vs> requires((std::same_as<std::decay_t<Vs>, Ts>) && ...)
constexpr data_of_t(Vs... _vs)
: data(std::forward<Vs>(_vs)...)
{}
This will add proper forwarding and also constrain it properly so it always do as data_of intended.
Just doing those change will remove UB from the code, but also change it a bit. The type data_of_t will always contain values, and won't contain references. If you want to send a reference, you will need something like std::ref, just like std::bind have to use to defer parameters.
You will still need to use std::forward<decltype(arg)>(arg).data for proper forwarding as @Barry stated
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.