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
|
|---|---|---|---|---|
74,012,082
| 74,012,573
|
Can you help me debug this c++ program which is supposed to add a node at the end in circular single linked list and print the list?
|
Can you help me debug this c++ program which is supposed to add a node at the end in circular single linked list and print the list?
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
class Lfun
{
public:
virtual void addLast(int x) = 0;
virtual void display() = 0;
virtual ~Lfun(){};
};
class List :public Lfun{
private:
Node* head;
Node* curr;
public:
List()
{
head = NULL;
curr = NULL;
}
void addLast(int x)
{
Node *tmp = new Node(x);
tmp->next = head;
if (head == NULL)
{
head = tmp;
}
else
{
curr = head;
while (curr->next != NULL)
{
curr = curr->next;
}
curr->next = tmp;
}
}
void display()
{
curr = head;
for (int i = 0; i < 5; i++)
{
cout << curr->data << " ";
}
}
};
int main()
{
List* ll = new List();
for (int i = 0; i < 5; i++)
{
cout << i;
ll->addLast(i);
ll->display();
}
}
I have created a class 'Node' to create a node for the linked list and another class 'Lfun' to redefine all the functions in the child class ,that is 'List'.
The program is not giving any output, can you explain why that is happening and how I can fix that problem?
|
Your main problem is this line in List:
tmp->next = head;
With that line, you ensure that the last Node's next will never be NULL, but point back at head, giving you a circular list.
In your while-loop you loop until you find a next member that is NULL, but due to the above problem, this will loop forever.
Your display function is also broken, as it prints the first element 5 times without advancing curr. Another thing is that curr should really not be a member variable, but rather a local variable in functions where it is used.
Also note that in c++, you should use nullptr, not NULL
|
74,012,130
| 74,020,777
|
Why does std::vector copy-construct instead of move-construct when the destructor may throw?
|
Consider the following program:
#include <vector>
#include <iostream>
class A {
int x;
public:
A(int n) noexcept : x(n) { std::cout << "ctor with value\n"; }
A(const A& other) noexcept : x(other.x) { std::cout << "copy ctor\n"; }
A(A&& other) noexcept : x(other.x) { std::cout << "move ctor\n"; }
~A() { std::cout << "dtor\n"; } // (*)
};
int main()
{
std::vector<A> v;
v.emplace_back(123);
v.emplace_back(456);
}
If I run the program, I get (GodBolt):
ctor with value
ctor with value
move ctor
dtor
dtor
dtor
... which is in line with what I would expect. However, if on line (*) I mark the destructor as potentially throwing, I then get :
ctor with value
ctor with value
copy ctor
dtor
dtor
dtor
... i.e. the copy ctor is used instead of the move ctor. Why is this the case? It doesn't seem copying prevents destructions that moving would necessitate.
Related questions:
are std::vector required to use move instead of copy?
How to enforce move semantics when a vector grows?
Vector reallocation uses copy instead of move constructor
|
tl;dr: Because std::vector prefers to offer you a "strong exception guarantee".
(Thanks goes to Jonathan Wakely, @davidbak, @Caleth for links & explanations)
Suppose std::vector were to use move construction in your case; and suppose that an exception were to be thrown during vector-resizing, by one of the A::~A calls. In that case, you would have an unusable std::vector, partially moved.
On the other hand, if std::vector performs copy construction, and an exception occurs in one of the destructors - it can simply ditch the new copy, and your vector will be in the same state it was before the resizing. That is the "strong exception guarantee" for the std::vector object.
The standard library designers chose to prefer this guarantee over optimizing the performance of vector resizing.
This had been reported as an issue/defect with the standard library (LWG 2116) - but after some discussion, it was decided to keep the current behavior as per the above consideration.
See also Arthur O'Dwyr's post: A "Pick any two" triangle for std::vector.
|
74,012,149
| 74,012,265
|
Why Do We Need asio::co_spawn?
|
Usually when working with coroutines, I can think of the way they execute by dividing the coroutine to the part before the first co_await and the part that comes after it.
The part before can usually execute directly on the stack of the calling thread whereas the part after it is scheduled for execution by some executor.
This means that if I have a coroutine, I can simply call it directly from a regular function (in a 'detached' manner).
However, in most examples of asio, a coroutine is invoked via asio::co_spawn.
Take for example this coroutine that communicate between server and client:
awaitable<void> server_to_client(proxy_state_ptr state)
{
std::array<char, 1024> data;
for (;;)
{
auto n = co_await state->server.async_read_some(buffer(data), use_awaitable);
co_await async_write(state->client, buffer(data, n), use_awaitable);
}
}
The function that initiates the read-write sequence does so using asio::co_spawn (always in 'detached' mode). The same goes for the invocation of the coroutine that first accept the connection.
So why and when asio::co_spawn is necessary? When should it be used? What can happen if I invoke an asio coroutine directly without using co_spawn (let's say, from my main thread)?
|
I can simply call it directly from a regular function (in a 'detached' manner)
Yes, but if you don't provide an executor, it never continues.
asio::co_spawn is a simple way of tying an awaitable to an executor, and simple is what you want in an example.
|
74,013,707
| 74,030,966
|
Namespace resolution inside preprocessor
|
I have a .h header shared among a C executable and a large C++ codebase.
#ifdef __cplusplus
namespace my {
#endif
typedef int my_t;
#define MY_OH_MY sizeof(my_t)
typedef my_t alias_t;
// plenty of other typedefs which push me to keep only
// these two bracing #ifdef __cplusplus ...
#ifdef __cplusplus
} // namespace
#endif
The C source works well with the exclusion.
#include "my.h"
int main(int argc, char ** argv)
{
my_t m = 1;
alias_t a = 2;
m += MY_OH_MY;
return 0;
}
However the CXX source fails under Gnu compiler:
#include "my.h"
int main(int argc, char ** argv)
{
my::my_t m = 1;
my::alias_t a = 2;
m += MY_OH_MY;
return 0;
}
my.h:7:25: error: ‘my_t’ was not declared in this scope; did you mean ‘my::my_t’?
7 | #define MY_OH_MY sizeof(my_t)
Basically because (?) at preprocessor time are namespace still not a thing ?
I was expecting that in any case it would have fallen within the namespace { } enclosing group.
I can surely change it to the following, but I still cannot figure out why it doesn't work.
#ifdef __cplusplus
#define MY_OH_MY sizeof(my::my_t)
#else
#define MY_OH_MY sizeof(my_t)
#endif
|
You cannot use namespaces (as it is not a feature of C language) in C identifiers that must be accessed from C. Indeed, you must declare those specially in order for the compiler not to mangle the names. You can only use them in C++, but be carefull as to share code with C, you must inform the C++ compiler which routines and what identifiers will be visible from C (the compiler mangles the names in a different way to include info about operator definitions, parameter lists and overloading, and namespaces) resulting in identifiers completely cryptic to the programmer.
To see an example, just write this function:
char *function1(char *parameter1, int parameter2)
{
return 0;
}
and compile it as C language (naming the file with .c suffix) and with C++ language (using .cc as file suffix). Then use nm(1) to see the names the compiler used to name your function.
###As C code (in file func.c):
$ make func.o
cc -O2 -pipe -c func.c -o func.o
$ nm func.o
0000000000000000 T function1
$ _
###Now as C++ code (in file func.cc):
$ make func.o
c++ -O2 -pipe -c func.cc -o func.o
$ nm func.o
0000000000000000 T _Z9function1Pci
$ _
The _Z indicates something to the compiler, the 9 indicates an identifier 9 characters long (function1), The P is for a pointer, c is for char and i if for integer parameters.
If you have compiled it in C++, but declared it inside an extern "C" { } block, then the name would have been the same as in the first example, but you should not be able to define another function with name function1 and different parameter list, as there's already a C function named function1:
#ifdef __cplusplus
extern "C" {
#endif
/* C++ functions that will be accessible from C code, or C function
* declarations that will be accessed from C++ code, depending on which
* source you include this code */
#ifdef __cplusplus
} /* extern "C" */
#endif
|
74,013,824
| 74,024,421
|
BCG Virtual Grid how to display from a specific row
|
I have a CBCGPGridCtrl with virtual rows enabled (EnableVirtualMode).
No problem with data display.
On some event (right click from another window) I want to move the current visible part of the grid to a specific row.
I couldn't find any specific method to do that.
I tried a couple of different options:
1.
I saw that manually moving the scrollbar cause a change in the values of variable like: m_nFirstVisibleItem, m_nLastVisibleItem and m_nVertScrollOffset, so I thought to replicate that using setScrollPos.
m_grid.SetScrollRange(SB_VERT, 0, size());
//....
m_grid.SetScrollPos(SB_VERT, gotoPosition);
But nothing happened and those variables were not affected.
The other idea I tried was to select the row I was interested in, with:
m_grid.SetCurSel(gotoPosition);
None of those worked.
What is the right way to achieve that?
|
After a day of different attempts, the only solution I was able to get to work is to have a child of CBCGPGridCtrl and intervene explicitly on the value of m_nVertScrollOffset.
So, it was something like this:
class CChildGrid : public CBCGPGridCtrl
{
public:
void SetScrollPos(int gotoPosition)
{
m_nVertScrollOffset = gotoPosition * m_nRowHeight;
}
};
....
void CFoo::SetGridPosition()
{
m_grid.SetScrollPos(125);
m_grid.AdjustLayout();
}
|
74,014,063
| 74,014,254
|
How do I copy a class with a std::vector as a member variable?
|
I have made a simple Matrix class with a std::vector as the underlying container.
My problem is when i use the copy constructor on the Matrix class, the std::vector does not get copied.
My matrix.h:
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
#include <iostream>
template <typename T>
class Matrix
{
private:
int m_rows;
int m_cols;
std::vector<T> m_vector;
public:
// Constructor
Matrix(int rows, int cols)
: m_rows{ rows }, m_cols{ cols }
{
m_vector.reserve(rows * cols);
std::cout << "Constructor. vector capacity = " << m_vector.capacity() << '\n';
}
// Copy constructor
Matrix(const Matrix<T>& old)
: m_rows{ old.m_rows }, m_cols{ old.m_cols }
{
m_vector.reserve(old.m_rows * old.m_cols);
m_vector = old.m_vector;
std::cout << "Copy constructor. vector capacity = " << m_vector.capacity() << '\n';
}
const T& operator()(int row, int col) const
{
return m_vector[row * m_cols + col];
}
T& operator()(int row, int col)
{
return m_vector[row * m_cols + col];
}
}
My test of the class in main.cpp is then:
#include "matrix.h"
int main()
{
// Create new matrix and fill
Matrix<int> matrix(3, 3);
int count = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
matrix(i, j) = count++;
}
}
// Print new matrix
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
std::cout << matrix(i, j) << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
// Copy assignment and print new
Matrix<int> matrix2(matrix);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
std::cout << matrix2(i, j) << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
return 0;
}
I was expecting this to print identical matrices of ints 0-8.
This is the output:
Constructor. vector capacity = 9
0 1 2
3 4 5
6 7 8
Copy constructor. vector capacity = 9
0 0 0
0 0 0
0 0 0
I seems that the copying in the copy constructor doesn't copy the std::vector properly
|
After this constructor has been used
Matrix(int rows, int cols) : m_rows{rows}, m_cols{cols} {
m_vector.reserve(rows * cols);
}
there are exactly zero elements in the vector and trying to access elements in the vector will have undefined behavior. The proper constructor should actually create the elements instead:
Matrix(int rows, int cols) : m_rows{rows}, m_cols{cols}, m_vector(rows * cols) {
}
With that in place, you don't even have to add a user-defined copy constructor. The compiler-generated copy and move constructors will do the right thing.
Demo
|
74,014,725
| 74,045,171
|
How to get unique sequence of types c++: (A, B, A, B, C) =>(A, B, C)
|
I need to exclude double instantiation, therefore I need to exclude the same types from the sequence of types.
#define ENTITY_SEQ (A)(B)(C)(A)(C)
||
\/
#define UNIQUE_ENTITY_SEQ (A)(B)(C)
I want to process it using a boost preprocessor. Is it possible to do that?
|
There is, to my knowledge, no way to check the equality of two unknown identifiers.
But, if you know the list of identifiers ahead of time, then it is certainly is possible.
I had some time to implement the trivial O(n^2) algorithm today, although you could probably do better. I hope the order isn't important to you, because I decided against trying to keep it.
#define CATe(a,b) CAT(a,b)
#define CAT(a,b) a##b
#define LPAREN (
#define CHECK(p,t,f) TUPLE_AT_2(p t,f,)
#define TUPLE_AT_2(a,b,...) b
#define EQ_0end_0end ,
// transform seq to guide
// (1)(2)(0end) -> 1)2)0end)
#define SEQ_TO_GUIDE_A(x) x)CHECK(EQ_0end_##x,,SEQ_TO_GUIDE_B)
#define SEQ_TO_GUIDE_B(x) x)CHECK(EQ_0end_##x,,SEQ_TO_GUIDE_A)
// insert without creating a duplicate
#define DEDUPE1_SCAN(...) __VA_ARGS__
#define DEDUPE1(seq,x) DEDUPE1_SCAN(DEDUPE1_A LPAREN x,SEQ_TO_GUIDE_A seq(0end))
#define DEDUPE1_A(x,y) CHECK(EQ_0end_##y,DEDUPE1_END,DEDUPE1_DO)(DEDUPE1_B,x,y)
#define DEDUPE1_B(x,y) CHECK(EQ_0end_##y,DEDUPE1_END,DEDUPE1_DO)(DEDUPE1_A,x,y)
// always insert (x) at the end
#define DEDUPE1_END(n,x,y) (x)
// keep (y) when x == y
#define DEDUPE1_DO(n,x,y) CHECK(EQ_##x##_##y,DEDUPE1_1,DEDUPE1_0)(n,x,y)
#define DEDUPE1_0(n,x,y) (y) n(x,
#define DEDUPE1_1(n,x,y) n(x,
// successively apply DEDUPE1 on seq with every element of seq
#define DEDUPE_SCAN(...) __VA_ARGS__
#define DEDUPE(seq) DEDUPE_SCAN(DEDUPE_A LPAREN seq,SEQ_TO_GUIDE_A seq(0end))
#define DEDUPE_A(seq,x) CHECK(EQ_0end_##x,DEDUPE_END,DEDUPE_DO)(DEDUPE_B,seq,x)
#define DEDUPE_B(seq,x) CHECK(EQ_0end_##x,DEDUPE_END,DEDUPE_DO)(DEDUPE_A,seq,x)
#define DEDUPE_DO(n,seq,x) n(DEDUPE1(seq,x),
#define DEDUPE_END(n,seq,x) seq
#define EQ_A_A ,
#define EQ_B_B ,
#define EQ_C_C ,
#define EQ_D_D ,
#define EQ_E_E ,
DEDUPE((A)(B)(A)(A)(C)(E)(A)(B)(C)(E)(A))
// expands to: (B)(C)(E)(A)
// 7500 elements with A B C D E took ~1 second
The basic idea is to transform the sequence ((1)(2)(3)) into a terminated guide (1)2)3)0end)), which allows for iteration with a context.
This context is used in DEDUPE1(seq,x) to remove all occurrences of x in seq and append x to the end of seq afterwards.
DEDUPE(seq) uses seq itself as the context and iterates through all elements of seq, and updates the iteration context with DEDUPE1(seq,x).
The above works for sequences of any size, but it is implementation defined if this type of sequence iteration works. Luckily, essentially all preprocessors support it.
Update: Here is a O(n) version, that is shorter, but requires more code for each extra supported identifier:
#define LPAREN (
#define CHECK(p,t,f) TUPLE_AT_2(p t,f,)
#define TUPLE_AT_2(a,b,...) b
#define EQ_0end_0end ,
#define EQ_0_0 ,
// transform seq to guide
// (1)(2)(0end) -> 1)2)0end)
#define SEQ_TO_GUIDE_A(x) x)CHECK(EQ_0end_##x,,SEQ_TO_GUIDE_B)
#define SEQ_TO_GUIDE_B(x) x)CHECK(EQ_0end_##x,,SEQ_TO_GUIDE_A)
// SET_INSERT for every of seq
#define DEDUPE_SCAN(...) __VA_ARGS__
#define DEDUPE(seq) DEDUPE_SCAN(DEDUPE_A LPAREN SET_EMPTY,SEQ_TO_GUIDE_A seq(0end))
#define DEDUPE_A(set,x) CHECK(EQ_0end_##x,DEDUPE_END,DEDUPE_DO)(DEDUPE_B,set,x)
#define DEDUPE_B(set,x) CHECK(EQ_0end_##x,DEDUPE_END,DEDUPE_DO)(DEDUPE_A,set,x)
#define DEDUPE_DO(n,set,x) n(SET_INS_##x set,
#define DEDUPE_END(n,set,x) SET_TO_SEQ set
#define SET_EMPTY (0,0,0,0,0)
#define SET_INS_A(a,...) (A,__VA_ARGS__)
#define SET_INS_B(a,b,...) (a,B,__VA_ARGS__)
#define SET_INS_C(a,b,c,...) (a,b,C,__VA_ARGS__)
#define SET_INS_D(a,b,c,d,e) (a,b,c,D,e)
#define SET_INS_E(a,b,c,d,e) (a,b,c,d,E)
#define SET_TO_SEQ1(x) CHECK(EQ_0_##x,,(x))
#define SET_TO_SEQ(...) SET_TO_SEQ_(SET_TO_SEQ1,__VA_ARGS__)
#define SET_TO_SEQ_(F,a,b,c,d,e) F(a)F(b)F(c)F(d)F(e)
DEDUPE((A)(B)(A)(A)(C)(E)(A)(B)(C)(E)(A))
// expands to: (A)(B)(C)(E)
// 80000 elements with A B C D E took ~1 second
Edit: I updated the CHECK macro, because I realized that I've been using a less ideal implementation.
|
74,015,245
| 74,015,413
|
Boost async_read reads zero bytes from pipe
|
I'm trying to asynchrosouly read from a pipe using boost::asio::async_read, but it reads zero bytes everytime.
However, I can succussfuly read from the pipe using the read function(unistd.h);
here's my code:
auto io = make_shared<boost::asio::io_service>();
auto work = make_shared<boost::asio::io_service::work>(*io);
int read_end = atoi(argv[0]);
auto pipe_read = make_shared<boost::asio::readable_pipe>(*io, read_end);
string message;
boost::thread_group worker_threads;
for(int i = 0; i < 1; i++)
{
// I'm calling io->run() inside the worker thread.
worker_threads.create_thread(boost::bind(&workerThread, io));
}
// The handler function gets the number of bytes read, which is always zero.
boost::asio::async_read(*pipe_read, boost::asio::buffer(message, 5), boost::bind(&handler, _1, _2));
cout << message << endl;
work.reset();
worker_threads.join_all();
return 0;
Any help would be much appreciated.
|
Given a
std::string message;
then asio::buffer(message) has size 0 (because the string is empty).
The overload taking a size asio::buffer(message, 5) can only limit the size, but doesn't provide it. So it is still size 0.
This explains your symptoms. Instead,
std::string message(5, '\0');
auto b = asio::buffer(message);
Or, alternatively,
std::string message;
message.resize(1024); // cue Bill Gates miss-quote
auto b = asio::buffer(message, 5);
Or even use dynamic buffers:
std::string message;
auto b = asio::dynamic_buffer(message/*, 5*/);
Live Demo
Showing a modernized version also fixing the various bugs I remarked:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
namespace asio = boost::asio;
void handler(boost::system::error_code ec, size_t xfr) {
std::cout << "Received " << xfr << " bytes (" << ec.message() << ")\n";
}
int main(int argc, char** argv) {
asio::thread_pool ioc(1); // or more threads
assert(argc > 1);
int read_end = atoi(argv[1]);
auto pipe_read = make_shared<boost::asio::readable_pipe>(ioc, read_end);
std::string message(5, '\0');
boost::asio::async_read(*pipe_read, asio::buffer(message), &handler);
ioc.join();
std::cout << message << std::endl;
}
Prints
./a.out 0 <<< "HELLO WORLD"
Received 5 bytes (Success)
HELLO
|
74,015,435
| 74,016,157
|
How do I sort students ID, name, and marks of students while using for bubble sorting?
|
I got these going which only sort the student's mark on an ascending order, but I can't sort the name and the ID of the students by their marks.
#include <iostream>
using namespace std;
int main()
{
int total;
cin >> total; // How much data you want to input
string ID[100];
string name[100];
int grade[total];
for (int i = 0; i < total; i++) // Inputting the data
{
cin >> ID[i]; // Student ID
cin >> name[i]; // student name
cin >> grade[i]; // student marks
}
for (int i = 0; i < total - 1; i++) {
for (int j = i + 1; j < total; j++) {
if (grade[j] < grade[i]) {
int temp = grade[j];
grade[j] = grade[i];
grade[i] = temp;
}
}
}
for (int i = 0; i < total; i++) {
cout << ID[i] << " " << name[i] << " " << grade[i] << endl;
}
return 0;
}
|
As mentioned by my comment, another alternative is to not sort the arrays themselves, but to sort an index array.
This allows you to keep the arrays separate, and without having to write n sets of "swap code" if you have n arrays to handle.
Below is mostly your code, but with what has been mentioned being applied:
#include <iostream>
#include <string>
int main()
{
int total;
std::cin >> total;
std::string ID[100];
std::string name[100];
int grade[100];
int index[100];
for (int i = 0; i < total && i < 100; i++) //Inputting the data
{
std::cin >> ID[i]; //Student ID
std::cin >> name[i]; //student name
std::cin >> grade[i]; //student marks
index[i] = i; // must be set up (0, 1, 2, 3, ..., total-1)
}
for (int i = 0; i < total-1; i++)
{
for (int j = i + 1; j < total; j++)
{
// If necessary, swap index[i] and index[j] if the
// grades at those locations are out of order
if (grade[index[j]] < grade[index[i]])
{
int temp = index[j];
index[j] = index[i];
index[i] = temp;
}
}
}
// Output the sorted data using the index array
for (int i = 0; i < total; i++) {
std::cout << ID[index[i]] << " " << name[index[i]] << " " << grade[index[i]] << std::endl;
}
// For reference, output the final index array.
std::cout << "\nIndex Array:\n";
for (int i = 0; i < total; i++) {
std::cout << index[i] << " ";
}
}
Input:
4
1 Joe 50
2 Jack 40
3 Mary 80
4 Sam 75
Output:
2 Jack 40
1 Joe 50
4 Sam 75
3 Mary 80
Index Array:
1 0 3 2
|
74,016,474
| 74,016,955
|
Allocator object type conversion
|
Is there a way, having one allocator object for type T, to use the SAME object to allocate memory for any other type. Maybe some magic with static_cast or rebind can help? Because right now I only have an idea of how to use rebind to derive the allocator type for the desired object type from the original allocator, but I don't understand how to use a ready-made allocator object to create any type of object.
|
An allocator a of type A for value type T conforming to the standard requirements can be rebound to an allocator for type U via e.g.
std::allocator_traits<A>::rebind_alloc<U> b(a);
(although an allocator may support only a subset of all possible types U and fail to instantiate with others)
Then b can be used to allocate and deallocate objects of type U. You do not need to store this allocator b in addition to a however. Each time you perform this rebind from the same value of a it is guaranteed that the b objects compare equal, meaning that one can be used to deallocate memory allocated by the other.
Note that I didn't say that correctly in a previous comment: It is not guaranteed that an allocation allocated by a can be deallocated by b. So an allocator may be using e.g. different memory resources for different types, but the memory resources cannot be embedded into the allocator and copied on allocator copy or rebind.
|
74,016,909
| 74,021,667
|
How do I make swig aware of c++ namespaces?
|
Hi I am trying to create a python binding for a little stack machine I wrote and chose to try swig for it.
The problem is that the generated code wont compile because some classes are unknown. The reasons for that is, that my classes are all inside a namespace.
The class I want to create a wrapper for looks like this:
#ifndef STACK_MACHINE_H
#define STACK_MACHINE_H
#include <stack.h>
#include <operand.h>
#include <instruction.h>
#include <program.h>
namespace stackmachine
{
class stack_machine
{
public:
stack_machine() = default;
void run();
void load (instruction* op);
vrml_variable* get_stack_top();
private:
stack m_stack;
program m_code;
};
}
#endif
The first problem is the load method. The instruction class is defined in one of the headers, and is also inside the stackmachine namespace:
#ifndef INSTRUCTION_H
#define INSTRUCTION_H
#include <stack.h>
namespace stackmachine
{
class instruction
{
public:
virtual ~instruction() = 0;
virtual void execute(stack& current_stack) = 0;
};
inline instruction::~instruction()
{
}
}
#endif
Here is a snipped of generated code:
SWIGINTERN PyObject *_wrap_stack_machine_load(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
stackmachine::stack_machine *arg1 = (stackmachine::stack_machine *) 0 ; // namespace used => OK!
instruction *arg2 = (instruction *) 0 ; //namespace ignored => error
void *argp1 = 0 ;
int res1 = 0 ;
void *argp2 = 0 ;
Now the interface definition is as simple as possible and probably the place where I need to make changes, but so far I have not found a hint on what to do:
%module stackmachine
%{
#include <stack_machine.h>
%}
%include <stack_machine.h>
Adding the instruction.h to the includes does not change anything.
It'd be great if someone could point me in the right direction.
Thanks.
EDIT:
I did try using "includeall" and it changed the problem, now the instruction class is known but standard c++ headers like vector and string wont be found. And I don't really want to include all available classes in the wrapper.
|
Any class/function/global in the public interface may need a %include to generated wrapper code. SWIG does not recursively include without -includeall but that's not desirable as that would try to wrap system headers.
Order matters as well. SWIG needs to generate wrapper code for instruction before stack_machine since it is used by stack_machine.
%module stackmachine
%{
#include <stack_machine.h>
%}
// as needed...
%include <stack.h>
%include <operand.h>
%include <instruction.h>
%include <program.h>
%include <stack_machine.h>
|
74,017,073
| 74,017,291
|
Following error when trying to use std::sort: In template: called object type 'bool' is not a function or function pointer
|
I want to reverse sort a custom container with custom objects, so when sorting this way:
(this is part of the .cpp)
bool PictureContainer::isGreater(const Picture& i, const Picture& j) {
return (i.getId() > j.getId());
}
void PictureContainer::sortRev() {
sort(picture, picture + tam, isGreater());
//< If I try with isGreater, without parenthesis, it says I need to make it static and then it gives same error again.
}
this is part of the .h
class PictureContainer {
private:
int size;
Picture *picture;
public:
PictureContainer();
PictureContainer(int maxSize);
bool isGreater (const Picture& i, const Picture& j);
void sortRev();
|
It's impossible to use a non-static member function directly as the comparator for std::sort(). There are a few options:
Mark PictureContainer::isGreater as static, and pass PictureContainer::isGreater to std::sort().
Since the implementation of isGreater does not access anything that's only available from the PictureContainer class, we may also make it a free function and pass isGreater to std::sort().
In case the implementation of isGreater has to access some members (or member functions) that's only available within an instance of PictureContainer, we may use a lambda inside the implementation of PictureContainer::isRev as the argument. This is the most flexible solution. For example:
void PictureContainer::sortRev() {
sort(picture, picture + tam, [this](const Picture& lhs, const Picture& rhs) {
return this.isGreater(lhs, rhs);
});
}
|
74,017,637
| 74,017,799
|
Multithreading with function in other class
|
I'm new to c++ so sorry if obvious answer. I'm trying to get a thread to run a function from another class with an argument.
Here's how my code is laid out:
int main(){
Engine engine;
Sounds sounds;
std::thread t(&Sounds::ManageSounds, &sounds, &engine)
/*some stuff*/
t.join();
}
class Sounds{
void ManageSounds(Engine en){
/*some stuff*/
}
}
If I run this code as is, I get this error:
error: static assertion failed: std::thread arguments must be
invocable after conversion to rvalues 129 |
typename decay<_Args>::type...>::value
If I change ManageSounds() to accept no arguments and remove the &engine in the thread, it works completely fine.
|
Your thread method ManageSounds requires an Engine parameter by value, and you pass it a pointer to Engine (&engine).
To fix it you should do one of the following:
Pass the engine object iteslf (if it is copyable, and it makes sense in your case).
If you actually need pointer/reference semantics (which is quite reasonable), change the thread method accordingly. In this case you need to use std::ref (because the ctor of std::thread copies the arguments). Note: you must ensure the thread does not out-live the engine object.
Complete code example (using copy):
#include <thread>
class Engine { /*...*/ };
class Sounds {
public:
void ManageSounds(Engine en) {
/*some stuff*/
}
};
int main() {
Engine engine;
Sounds sounds;
//--------------------------------------------vvvvvv
std::thread t(&Sounds::ManageSounds, &sounds, engine);
/*some stuff*/
t.join();
}
Complete code example (using a reference):
#include <thread>
class Engine { /*...*/ };
class Sounds {
public:
//-----------------------v
void ManageSounds(Engine & en) {
/*some stuff*/
}
};
int main() {
Engine engine;
Sounds sounds;
//--------------------------------------------vvvvvvvvvvvvvvvv
std::thread t(&Sounds::ManageSounds, &sounds, std::ref(engine));
/*some stuff*/
t.join();
}
|
74,017,739
| 74,018,212
|
C++20 concepts as Interfaces
|
Hey I'm trying to design some Interfaces without any runtime overhead using c++20 concepts.
I came up with the following (simplified) concept
/**
* @brief This concept defines an OSA Interface
*/
template<typename T, typename Task_T>
concept OSA_Layer_T = requires (T a) {
{T::getName(a)} -> std::same_as<std::string>; ///< Returns the name of the task (if no name is available return the ID as string)
{T::getId(a)} ->std::same_as<Task_T>; ///< returns the (underlying) ID of the task
};
Since every OS has it's own internal Task Handle Type (and I do not want to use void*) I need to pass the actual Task Handle as a template parameter to my concept
However I'm unsure how to define a class using this template
I have tried the following
This does not work because Task_T is missing
template<typename String_Type_T, OSA_Layer_T TaskType_T>
class Foo
{
};
This does not work either
template<typename Task_T>
template<typename String_Type_T, OSA_Layer_T<Task_T> TaskType_T>
class Foo
{
};
Could you help me out here?
Thx :)
Edit:
To clarify:
This OSA is supposed to hide embedded RTOS. Most embedded RTOS (like FreeRTOS, EmbOS, RTX) are written in C, therefore the OSA class is just a collection of static members calling the actual RTOS functions written in C)
Usally you would implement this interface using virtual functions. However the goal of this is to reduce the overhead as much as possible. Usually on embedded targets we link statically, therefore all unused template functions are discarded automatically. Removing unused members is not possible if the members are virtual.
(CMSIS from ARM is available as an OSA for embedded RTOS. However IMHO CMSIS has some downsides like the overuse of void*. This is why I'd like to create a type safe OSA)
|
Since every OS has it's own internal Task Handle Type (and I do not want to use void*) I need to pass the actual Task Handle as a template parameter to my concept
The second part of this doesn't actually follow from the first. If every OS has its own internal task handle type, the approach should be to have that be part of the concept. Because there is only one interface: OSA_Layer_T.
This might be easier to appreciate using a more familiar concept: iterators. Iterators have a type that they dereference to (this is, unfortunately, called reference. Unfortunate because it's not always a reference type, it could just be int). But you wouldn't want to define your concept this way:
template <typename I, typename Reference>
concept Iterator = /* ... */;
Because it's not like Iterator<int> and Iterator<string const&> are different interfaces - if a type is an Iterator, then it has some reference type, which you should be able to ask for, and that doesn't really affect any of the rest of this.
This is typically called an associated type.
For the original question, the formulation should be:
template<typename T>
concept OsaLayer = requires (T a) {
{ T::getName(a) } -> std::same_as<std::string>;
typename T::task_type;
{ T::getId(a) } -> std::same_as<typename T::task_type>;
};
If you need to be able to provide the task type non-intrisuviely (if you don't control the types that are OsaLayer), then you could do it this way:
// specialize this for types that need to be OsaLayer's
template <typename T> struct task_type;
template <typename T> using task_type_t = typename task_type<T>::type;
template<typename T>
concept OsaLayer = requires (T a) {
{ T::getName(a) } -> std::same_as<std::string>;
typename task_type_t<T>;
{ T::getId(a) } -> std::same_as<task_type_t<T>>;
};
|
74,017,772
| 74,017,980
|
CMake Linking library with full path and with target_include_directories
|
I came to a problem that I do not understand why this works in such a ways.
I am linking static libraries, specially libgmp-10 and libmpfr-4. These are static libraries from CGAL.
This does not work:
list(APPEND petras_include_paths
#cgal
"${CMAKE_BINARY_DIR}/install/cgal/include"
"${CMAKE_BINARY_DIR}/install/cgal/auxiliary/gmp/include"
"${CMAKE_BINARY_DIR}/install/cgal/auxiliary/gmp/lib"
#"C:/msys64/mingw64/lib/" #GCC
)
target_include_directories(${PROJECT_NAME} PRIVATE "$<BUILD_INTERFACE:${petras_include_paths}>") #header for the library
target_link_libraries(${PROJECT_NAME} PRIVATE
libgmp-10
libmpfr-4
)
This works:
target_link_libraries(${PROJECT_NAME} PRIVATE
"${CMAKE_BINARY_DIR}/install/cgal/auxiliary/gmp/lib/libgmp-10.lib"
"${CMAKE_BINARY_DIR}/install/cgal/auxiliary/gmp/lib/libmpfr-4.lib"
)
Why?
I thought that target_include_directories add the path to libraries, so that in target_link_libraries I should only need to specify the name of the library, not the full path.
|
target_include_directories adds #include directories, not library search paths. target_link_directories adds link directories.
Before proceeding, you might want to read https://doc.cgal.org/latest/Manual/devman_create_and_use_a_cmakelist.html
|
74,017,783
| 74,017,880
|
Defining method with additional template parameters out of line
|
Given a templated class, how do I define a (further templated) method out of line? The syntax
template<class T> class C {
public:
template<class S> void f();
};
template<class S, class T> void C<T>::f<S>(){}
or any variant I have tried does not do the job:
error: use 'template' keyword to treat 'f' as a dependent template name
template<class S, class T> void C<T>::f<S>(){
^
template
error: nested name specifier 'C<T>::' for declaration does not refer into a class, class template or class template partial specialization
|
You need to write two template headers:
template<class T>
template<class S>
void C<T>::f(){}
|
74,017,855
| 74,019,447
|
My code for computing large sums fails this very specific test case and I'm not sure why
|
The point of this exercise was to create code that can compute very large sums by using an algorithm close to how you would do it by hand. My code seems to work just fine, except for one specific test case, which is 9223372036854775808 + 486127654835486515383218192. I'm not sure what is special about this specific test case for it to fail, because the code is totally capable of carrying over, as well as adding numbers that have two different amounts of digits...Help would be greatly appreciated.
Edit: The output for this case is +'2+-0+*.4058858552237994000
// Basic mechanism:
//reverse both strings
//reversing the strings works because ex. 12+12 is the same as 21+21=42->reverse->24
//add digits one by one to the end of the smaller string
//dividing each sum by 10 and attaching the remainder to the end of the result-> gets us the carry over value
// reverse the result.
//ex. 45+45 ->reverse = 54+54 -> do the tens place -> 0->carry over -> 4+4+1 -> result= 09 -> reverse -> 90.
#include <iostream>
#include <cstring>
using namespace std;
string strA;
string strB;
string ResStr = ""; // empty result string for storing the result
int carry =0;
int sum; //intermediary sum
int n1; //length of string 1
int n2; // length of string 2
int rem; // remainder
int main()
{
cout << "enter" << endl;
cin >> strA;
cout << "enter" << endl; // I didn't know how to write this program to use argv[1] and argv[2] so this was my solution
cin >> strB;
// turning the length of each string into an integer
int n1 = strA.length(), n2 = strB.length();
if (n1<n2){
swap(strA,strB);
}//for this part I have no idea why this has to be the case but it only works if this statement is here
// Reversing both of the strings so that the ones, tens, etc. positions line up (the computer reads from left to right but we want it to read from right to left)
reverse(strA.begin(), strA.end());
reverse(strB.begin(), strB.end());
for (int i=0; i<n2; i++)//start at 0, perform this operation until the amount of times reaches the value of n2
{
//get the sum of current digits
int sum = ((strA[i]-'0')+(strB[i]-'0')+carry);
int quotient=(sum/10);
int rem=(sum-10*quotient);
ResStr+=(rem+'0'); //this gets the remainder and adds it to the next row
// Calculate carry for next step. Thus works because carry is an integer type, so it will truncate the quotient to an integer, which is what we want
carry = sum/10;
}
// Add the remaining digits of the larger number
for (int i=n2; i<n1; i++) //start at n1, perform this operation until the amount of times reaches the value of n1
{
int sum = ((strA[i]-'0')+carry);
int quotient=(sum/10);
int rem=(sum-10*quotient);
ResStr+=(rem+'0');
carry = sum/10;
}
// Add remaining carry over value
if (carry)
ResStr+=(carry+'0');
// reverse the resulting string back, because we reversed it at the beginning
reverse(ResStr.begin(), ResStr.end());
cout << "The result is " << ResStr << endl;
return 0;
}
|
After a lot of experimentation, what made the difference for me was replacing n1 and n2 entirely with strA.length() and strB.length() respectively in the for loop declarations. I'm not entirely sure why this happens, so if anyone has an explanation- please forward it.
Anyway, here's my version of the code:
//Basic mechanism: reverse both strings
//reversing the strings works because ex. 12+12 is the same as 21+21=42->reverse->24 (for single-digit sums smaller than 10)
//add digits one by one to the end of the smaller string
//dividing each sum by 10 and attaching the remainder to the end of the result-> gets us the carry over value reverse the result (mod 10 arithetic)
//ex. 45+45 ->reverse = 54+54 -> do the tens place -> 0->carry over -> 4+4+1 -> result= 09 -> reverse -> 90.
//ex. 90+90 ->reverse = 09+09 -> do the tens place -> 0->carry over ->0+ 9+9 ->carry over->1+ result= 081 -> reverse -> 180.
#include <iostream>
using std::cin; using std::cout;
#include <cstring>
using std::string;
#include <algorithm>
using std::reverse;
string strA, strB, ResStr = "";
int carry = 0, sum;
int main() {
//get user input
cout << "Enter first number: "; cin >> strA;
cout << "Enter second number: "; cin >> strB; cout << "\n";
if (length_strA < length_strB){ swap(strA,strB); } //force stringA to be larger (or equal) in size
//Reversing both of the strings so that the ones, tens, etc. positions line up (the computer reads from left to right but we want it to read from right to left)
reverse(strA.begin(), strA.end()); cout << strA << "\n";
reverse(strB.begin(), strB.end()); cout << strB << "\n";
for (int i = 0; i < strB.length(); i++) {
sum = int(strA[i])-48 + int(strB[i])-48 + carry/10;
ResStr += char(sum % 10)+48;
carry = sum - sum%10;
}
// Add the remaining digits of the larger number
//start at strB.length, perform this operation until the amount of times reaches the value of strA.length
for (int i = strB.length(); i < strA.length(); i++) {
sum = int(strA[i])-48 + carry/10;;
ResStr += char(sum % 10)+48;
carry = sum - sum%10;
}
// Add remaining carry over value
if (carry != 0) { ResStr += char(carry)+48; }
// reverse the resulting string back, because we reversed it at the beginning
reverse(ResStr.begin(), ResStr.end());
//return user result
cout << "The result is: " << ResStr << "\n";
return 0; }
To answer why, it's because even once strB ended, it kept iterating through making a new sum in the first loop until strA ended. This meant it was reading null values for strB[i] and adding that to strA[i]+carry- which effectively shifted all the characters into the noisy-looking mess it was.
|
74,018,366
| 74,019,249
|
I used an object in my main file (?) despite having transferred ownership before?
|
I used move semantics a la
class MyC {
public:
Eigen::MatrixXd f_bar_mat;
MyC::MyC(Eigen::MatrixXd f_bar_mat):f_bar_mat(std::move(f_bar_mat))
}
In the main I have:
Eigen::MatrixXd f_bar_mat = Eigen::MatrixXd::Random(10000,200);
MyC MyInst(f_bar_mat);
MyC MyNewInst(MyInst.f_bar_mat); //transfer again
std::cout << "Access some element of the original matrix: " << f_bar_mat(3,2) << std::endl;
I realised only later that I erroneously called f_bar_mat in the body of my main after having transferred ownership.
However, the code still works; I don't get an error message.
Can someone help me understand the behaviour? My guess is that std::move then simply resorts to a deep copy. Alternatively, should I be getting a segmentation fault error or will it reference something other than f_bar_mat and create undefined behaviour?
|
You are not moving main's f_bar_mat anywhere. Nowhere did you call std::move(f_bar_mat) in main.
You are moving only the parameter of the constructor which is also called f_bar_mat but is not the same object as the one in main (since it was not declared as a reference).
Since you are passing f_bar_mat from main as a lvalue to the constructor, the parameter object of the constructor will be copy-constructed from main's f_bar_mat. Only then you will move-construct the class member (also called f_bar_mat) from the parameter object.
Similarly at // transfer again you are not calling std::move on MyInst.f_bar_mat, so you are copy-constructing the constructor's parameter object again.
|
74,018,367
| 74,068,988
|
C++ SFML texture wont load from class
|
I am working on a simple little game in c++ (SFML).
It involves the need to create objects of the Ghost class and store them in an array, each ghost must also be assigned a texture based one their type, something I have as input to the class init function. Overall my class looks like this:
class Ghost{
public:
Sprite sprite;
Texture texture;
int type;
Ghost(int ty=1){
type = ty;
if (type == 1){
texture.loadFromFile("assets/ghost.png");
} else if (type == 2){
texture.loadFromFile("assets/monster.png");
}
sprite.setTexture(texture);
}
};
The thing is, when attempting to create a ghost the texture is not loaded. I know the initializer runs since other code in the method do run, but for some reason not the texture loader. In case it is of any use, here is how I load a ghost:
Ghost ghosts[20];
ghosts[0] = Ghost(1);
int numGhosts = 1;
Why doesn't this approach work?
|
Textures dont mix well with arrays/vectors. The copy operator needs to specified as the default one is not enough to maintain the same functionality in arrays/vectors. Pointers/dynamic textures or a different method needs to be implemented for this to work. I suggest doing the latter and instead of sending a number as an argument to the contructor, sending a premade texture variable.
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
using namespace std;
using namespace sf;
class Ghost{
public:
Sprite sprite;
Ghost(sf::Texture tex){
sprite.setTexture(tex);
}
Ghost(){}
};
int main()
{
Texture gh,mon;
gh.loadFromFile("boy.png");
mon.loadFromFile("girl.png");
Ghost arr[] = {gh, gh, mon, mon, gh};//this
arr[1].sprite.setTexture(gh);//or this
// create the window
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
window.setFramerateLimit(60);
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
}
// clear the window with black color
window.clear(sf::Color::Black);
// draw everything here...
window.draw(arr[1].sprite);
// end the current frame
window.display();
}
return 0;
}
If you NEED the textures to be in the objects, make them as dynamic variables, this should dissolve the problem then.
if you NEED to use arr[1] = Ghost(1), look into operator overloading in c++ and overload the '=' operator
|
74,019,463
| 74,019,727
|
Is it possible to have a variadic argument list for a template or automatically generated specifications based on supplied argument list
|
Let's say I have the following tuple:
std::tuple<int, int, int> setVals(int val)
{
return std::make_tuple(val, val, val);
}
It is really nice to have structured bindings with this: auto [x, y, z] = setVals(42);
Would it be possible to have some kind of variadic signature for setVals, so I could do structured bindings with any number of variables? For instance, auto [x, y] = setVals(42); or auto [x, y, z, x2, y2, z2] = setVals(42);
I know that I could just use a variadic function template where I could just declare some ints and pass them in as references, but the structured bindings are so convenient that I was wondering if something like I just showed is possible. I'm sorry if this question is bad.
|
You can create a function like what you want but you have to specify the number of elements the tuple will have as a template parameter. That would give you code like:
// does the actual creation
template <typename T, std::size_t... Is>
auto create_tuple_helper(const T& initial_value, std::index_sequence<Is...>)
{
// this ueses the comma expression to discard Is and use initial_value instead for each element
return std::tuple{(void(Is), initial_value)...};
// void(Is) is used to get rid of a warning for an unused value
}
// this is a wrapper and makes it easy to call the helper function
template <std::size_t N, typename T>
auto create_tuple(const T& initial_value)
{
return create_tuple_helper(initial_value, std::make_index_sequence<N>{});
}
int main()
{
auto [a, b, c, d] = create_tuple<4>(42);
std::cout << d;
}
Live example
|
74,019,895
| 74,025,501
|
Valgrind - many allocated bytes
|
Installed valgrind on my WSL and I was a bit confused.
Problem: I get a lot of allocated bytes even though my program doesn't do anything.
main.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "I'm testing valgrind!" << endl;
return 0;
}
The result of calling valgrind:
==435== Memcheck, a memory error detector
==435== Copyright (C) 2002-2017, and GNU GPLd, by Julian Seward et al.
==435== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==435== Command: ./start
==435==
==435== error calling PR_SET_PTRACER, vgdb might block
I'm testing valgrind!
==435==
==435== HEAP SUMMARY:
==435== in use at exit: 0 bytes in 0 blocks
==435== total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
==435==
==435== All heap blocks were freed -- no leaks are possible
==435==
==435== For lists of detected and suppressed errors, rerun with: -s
==435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
I actually have two questions:
Why do I get so many allocated bytes?
How do I get rid of this? (In my univercity server valgrind doesn't show these bytes so I was wondering if I could do that too..)
|
If you are curious and want to see what these allocations are, run with
--run-libc-freeres=no --run-cxx-freeres=no -s --leak-check=full --show-reachable=yes
As said in the comments, don't worry about this. All that matters are the errors.
|
74,020,792
| 74,020,924
|
Why does c++(and most other languages) have both 'for' and 'while' loops?/What can you do with one type that you can't with the other?
|
Why do most programming languages have two or more types of loops with almost no difference? In c++, is one of the two better for specific tasks? What about switches and if's; is there any difference there?
If not, then an answer about why they were implemented would be appreciated.
|
There is nothing that you can do with one type that you can't do with the other, because mechanical transformations exist between them:
while (X) { body; }
can be written as
for (;X;) { body; }
and
for (A;B;C) { body; }
can be written as
{ A; while (B) { body; C; } }
The only difference is readability. The for loop puts the update-expression C at the top of the loop, making it easier to recognize certain patterns like looping through a numeric range:
for( i = 0; i < limit; ++i )
or following a linked list
for( ; ptr != nullptr; ptr = ptr->next )
|
74,020,875
| 74,021,128
|
Converting floating point value to string using gcvt(), but when there are no decimals the whole number printed out ends in a dot
|
Just hopefully a simple question about the gcvt() function.
Printing out buffer as a result of gcvt(32.000,10,buffer), results in "32."
Any way I can get rid of that annoying dot after the 32?
|
I don't think you can get gcvt to not do that - you can remove it afterward with
if ((p=strchr(buffer,'.'))
*p='\0';
|
74,020,898
| 74,020,934
|
Is it possible to "overload" an alias template depending on a constraint?
|
Can we have an alias template that points to a type if a constraint is false, or to another type if that constraint is true ?
template < class T >
using MyType = SomeType;
template < class T >
requires SomeConstraint
using MyType = SomeOtherType;
I know doing it this way doesn't compile but is there a workaround ? Because I want to have some types in a class that are set to void if a constraint is not respected, or to something else if the constaint is respected without having to make the whole class require that constraint
|
Yes, either by moving the alias into a class and partially specializing the class (and then aliasing the alias in the class from the outside), or for the case you are showing simpler:
template<typename T>
using MyType = std::conditional_t<requires{ requires SomeConstraint; },
SomeOtherType, SomeType>;
Depending on what SomeConstraint is (I am assuming it to be a placeholder for something more complex than an identifier) probably also just
template<typename T>
using MyType = std::conditional_t<SomeConstraint,
SomeOtherType, SomeType>;
will be fine.
In either case this will require however that both SomeOtherType and SomeType are valid types (again assuming these are placeholders). It will not apply SFINAE to them. If that is not given you need to fall back to the class partial specialization method.
The class template partial specialization method:
template<typename T>
struct MyTypeImpl {
using type = SomeType;
};
template<typename T>
requires SomeConstraint
struct MyTypeImpl<T> {
using type = SomeOtherType;
};
template<typename T>
using MyType = typename MyTypeImpl<T>::type;
|
74,021,054
| 74,021,112
|
Converting json file to json object jumbles up the order of objects
|
I am trying to parse a json file into a json object using nlohmann json library.
This is the json file:
{
"n":1,
"data":
{
"name":"Chrome",
"description":"Browse the internet.",
"isEnabled":true
}
}
This is my code:
#include <nlohmann/json.hpp>
#include <iostream>
#include <fstream>
using namespace std;
using json = nlohmann::json;
int main()
{
ifstream f("/Users/callum/sfucourses/cmpt373/test/example2.json");
json data = json::parse(f);
cout << data << endl;
}
If I don't do the parse and just do cout << f.rdbuf() I get correct output:
./interpret
/Users/callum/sfucourses/cmpt373/build
{
"n":1,
"data":
{
"name":"Chrome",
"description":"Browse the internet.",
"isEnabled":true
}
}
but if I do the parse and print out the json object 'data',then "n":1 and "name":"Chrome" is placed at the end instead of the beginning:
./interpret
{"data":{"description":"Browse the internet.","isEnabled":true,"name":"Chrome"},"n":1}
How do I get it to print in the correct order?
|
JSON is normally not ordered, but the library provides nlohmann::ordered_json that keeps the insertion order:
auto data = nlohmann::ordered_json::parse(f);
Parsing the file like above and printing it like you do produces this output:
{"n":1,"data":{"name":"Chrome","description":"Browse the internet.","isEnabled":true}}
|
74,021,121
| 74,021,223
|
Namespaces and C++ library
|
Is a namespace contained in a library or a library is contained in a namespace?
How many namespaces are there in the C++ standard library ?
|
They are orthogonal. A library can use multiple namespaces and a namespace can be split between multiple libraries. However it is a good practice to scope the contents of a library to a (usually single) namespace (+ namespaces nested therein) specific to that library to avoid name clash between multiple libraries and for clarity.
The standard library uses (aside from the global namespace scope) only the std namespace (+ nested namespaces), although namespaces named std followed by any number of digits and the namespace posix are also reserved to the standard library for future standardization. The standard library also has multiple nested namespaces inside std, e.g. std::filesystem and std::ranges, and certain names are reserved for it in the global namespace scope.
The standard library also explicitly allows user code (including user libraries) to add certain declarations (in particular partial specializations of some classes) to the std namespace. So std is not always completely restricted to the standard library either.
|
74,021,902
| 74,022,136
|
CMake: add a directory prefix to `target_include_directories(...)` file #includes
|
I am using the Crypto++ library in my C++ project, and have installed it with the following (minimised) CMake code:
cmake_minimum_required(VERSION 3.24)
project(CMakeAddLibraryPrefixIncludes)
set(CMAKE_CXX_STANDARD 23)
include(FetchContent)
FetchContent_Declare(CryptoPP
GIT_REPOSITORY https://github.com/weidai11/cryptopp.git
GIT_TAG master)
FetchContent_MakeAvailable(CryptoPP)
add_executable(${PROJECT_NAME} main.cpp)
add_library(CryptoPP INTERFACE)
target_include_directories(CryptoPP INTERFACE ${CMAKE_BINARY_DIR}/_deps/cryptopp-src)
target_link_libraries(${PROJECT_NAME} CryptoPP)
Because the library has every header file in the top-level directory, all these files are accessible as #include <aes.h> for example. Is there a way that I can make it so that every file from CryptoPP is only accessible through a directory prefix like #include <cryptopp/aes.h>?
|
You can specify the folder for downloading sources by providing SOURCE_DIR to FetchContent_Declare. You can then use the parent folder of cryptopp_SOURCE_DIR as your include path.
FetchContent_Declare(CryptoPP
SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/cryptopp-src/cryptopp
GIT_REPOSITORY https://github.com/weidai11/cryptopp.git
GIT_TAG master)
FetchContent_MakeAvailable(CryptoPP)
# ...
target_include_directories(CryptoPP INTERFACE "${cryptopp_SOURCE_DIR}/..")
|
74,022,244
| 74,022,512
|
Regex match all except first instance
|
I am struggling to find a working regex pattern to match all instances of a string except the first.
I am using std::regex_replace to add a new line before each instance of a substring with a new line. however none of the googling I have found so far has produced a working regex pattern for this.
outputString = std::regex_replace(outputString, std::regex("// ~"), "\n// ~");
So all but the first instance of // ~ should be changed to \n// ~
|
In this case, I'd advise being the anti-Nike: "Just don't do it!"
The pattern you're searching for is trivial. So is the replacement. There's simply no need to use a regex at all. Under the circumstances, I'd just use std::string::find in a loop, skipping replacement of the first instance you find.
std::string s = "a = b; // ~ first line // ~ second line // ~ third line";
std::string pat = "// ~";
std::string rep = "\n// ~";
auto pos = s.find(pat); // first one, which we skip
while ((pos=s.find(pat, pos+pat.size())) != std::string::npos) {
s.replace(pos, pat.size(), rep);
pos += rep.size() - pat.size();
}
std::cout << s << "\n";
When you're doing a replacement like this one, where the replacement string includes a copy of the string you're searching for, you have to be a little careful about where you start second (and subsequent) searches, to assure that you don't repeatedly find the same string you just replaced. That's why we keep track of the current position, and each subsequent search we make, we move the starting point far enough along that we won't find the same instance of the pattern again and again.
|
74,022,353
| 74,026,871
|
Move mainwindow while clicking on button
|
I have subclassed a button and I'm trying to move her parent window around while this button is being hold down.
I'm having difficulty in how to proper calculate the new window position in this line:
MoveWindow(hWnd, pt.x, pt.y, width, height, TRUE);
// hWnd represent the button parent window.
switch (message)
{
case WM_LBUTTONDOWN:
{
POINT p{};
GetCursorPos(&p);
x = p.x;
y = p.y;
::SetCapture(hWnd);
mousedown = true;
}
break;
case WM_MOUSEMOVE:
{
if (mousedown)
{
RECT r;
POINT pt;
GetCursorPos(&pt);
GetWindowRect(hWnd, &r);
pt.x -= x;
pt.y -= y;
int width = r.right - r.left;
int height = r.bottom - r.top;
MoveWindow(hWnd, pt.x, pt.y, width, height, TRUE); // this is completely wrong, but im confused about how to proper calculate it
}
}
break;
case WM_LBUTTONUP:
{
ReleaseCapture();
mousedown = false;
}
break;
The code is partially working, the window is being moved, but to an incorrect position relative to where the mouse is.
--Edit new code--
case WM_LBUTTONDOWN:
{
POINT p{};
GetCursorPos(&p);
ScreenToClient(hWnd, &p);
x = p.x;
y = p.y;
dragging = true;
SetCapture(hWnd);
}
break;
case WM_MOUSEMOVE:
{
if (dragging)
{
RECT r;
GetWindowRect(hWnd, &r);
int w = r.right - r.left;
int h = r.bottom - r.top;
POINT p{};
GetCursorPos(&p);
p.x -= w/2;
p.y -= h/2;
MoveWindow(hWnd, p.x, p.y, w, h, TRUE);
}
}
break;
case WM_LBUTTONUP:
{
ReleaseCapture();
dragging = false;
}
break;
It closer, but the window is 'jumping' down when clicked-moved
|
Your calculation seems incorrect to me. When you down the mouse button, you should calculate the difference between the desktop mouse position and the location of the parent window and when you move the mouse, you can add the difference to the desktop mouse position back.
POINT g_deltaXY;
switch (message)
{
case WM_LBUTTONDOWN:
{
POINT p{};
GetCursorPos(&p);
RECT rect;
GetWindowRect(hWnd, &rect);
g_deltaXY.x = rect.left - p.x;
g_deltaXY.y = rect.top - p.y;
::SetCapture(hWnd);
mousedown = true;
}
break;
case WM_MOUSEMOVE:
{
if (mousedown)
{
RECT r;
POINT pt;
GetCursorPos(&pt);
GetWindowRect(hWnd, &r);
int width = r.right - r.left;
int height = r.bottom - r.top;
MoveWindow(hWnd, pt.x + g_deltaXY.x, pt.y + g_deltaXY.y, width, height, TRUE);
}
}
break;
case WM_LBUTTONUP:
{
ReleaseCapture();
mousedown = false;
}
break;
|
74,023,284
| 74,023,407
|
PyInit already defined - PyBind
|
I want to build a module for python, and it compiled fine when I had 1 header, 1 cpp file, but I wanted to extend it to 1 header, 2 cpp files, and now I get errors I don't really understand.
My Header (fast_qs_module.h):
#ifndef FASTCOSINE_MODULE_INCLUDE_H
#define FASTCOSINE_MODULE_INCLUDE_H
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <Python.h>
#include <vector>
std::vector<double> get_dwds_distances(std::vector<std::vector<double>> unlabeled, std::vector<std::vector<double>> labeled, double alpha);
std::vector<double> get_euclidian_distances_to_reference(std::vector<std::vector<double>> unlabeled, std::vector<double> reference);
PYBIND11_MODULE(fast_cosine, mod) {
mod.def("get_dwds_distances", &get_dwds_distances, "Multithreaded DWDS calculations to get the values for each unlabeled sample.");
mod.def("get_euclidian_distances", &get_euclidian_distances_to_reference, "Multithreaded Euclidian distance calculations to get the values for each unlabeled sample.");
}
#endif // FASTCOSINE_MODULE_INCLUDE_H
One cpp file:
#include [...]
#include "fast_qs_module.h"
class EuclidianClass
{
[...]
};
std::vector<double> get_euclidian_distances_to_reference(std::vector<std::vector<double>> unlabeled, std::vector<double> reference)
{
EuclidianClass runner(unlabeled, reference);
return runner.get_euclidian_result();
}
The other cpp file:
#include [...]
#include "fast_qs_module.h"
class CosineClass
{
[...]
};
std::vector<double> get_dwds_distances(std::vector<std::vector<double>> unlabeled, std::vector<std::vector<double>> labeled, double alpha)
{
CosineClass runner(unlabeled, labeled, alpha);
return runner.get_dwds_result();
}
When I pack it all in one cpp it works, but why doesn't it work with two cpp files? The header is include guarded...
The error I am getting:
compiler_compat/ld: build/temp.linux-x86_64-cpython-38/src/euclidian.o: in function `PyInit_fast_cosine':
euclidian.cpp:(.text+0x810): multiple definition of `PyInit_fast_cosine'; build/temp.linux-x86_64-cpython-38/src/cdist_cosine.o:cdist_cosine.cpp:(.text+0xfc0): first defined here
collect2: error: ld returned 1 exit status
As per https://pybind11.readthedocs.io/en/stable/faq.html#how-can-i-reduce-the-build-time I split it like this:
Header:
void init_dwds(py::module_ &);
void init_euclidian(py::module_ &);
PYBIND11_MODULE(fast_cosine, mod) {
init_dwds(mod);
init_euclidian(mod);
}
Source files:
std::vector<double> get_dwds_distances(std::vector<std::vector<double>> unlabeled, std::vector<std::vector<double>> labeled, double alpha)
{
CosineClass runner(unlabeled, labeled, alpha);
return runner.get_dwds_result();
}
void init_dwds(py::module_ &mod)
{
mod.def("get_dwds_distances", &get_dwds_distances, "Multithreaded DWDS calculations to get the values for each unlabeled sample.");
}
Source 2:
std::vector<double> get_euclidian_distances_to_reference(std::vector<std::vector<double>> unlabeled, std::vector<double> reference)
{
EuclidianClass runner(unlabeled, reference);
return runner.get_euclidian_result();
}
void init_euclidian(py::module_ &mod)
{
mod.def("get_euclidian_distances", &get_euclidian_distances_to_reference, "Multithreaded Euclidian distance calculations to get the values for each unlabeled sample.");
}
but I still get
euclidian.cpp:(.text+0x810): multiple definition of `PyInit_fast_cosine'; build/temp.linux-x86_64-cpython-38/src/cdist_cosine.o:cdist_cosine.cpp:(.text+0xfc0): first defined here
collect2: error: ld returned 1 exit status
|
Include guard only protects a header to be included more than once in a single translation unit. It does not help if a header contains something that needs not be placed in the header.
In your case, it looks like PYBIND11_MODULE expands to something like a definition rather than a declaration, which should not be in a header. Placing it in a cpp should solve.
|
74,023,308
| 74,062,004
|
Debugging (breakpoints / etc) in VSCode with different makefiles for parts of the codebase
|
I'm working on an ESP-IDF based project that runs on ESP32 microcontrollers.
The project has a bunch of different C++ libraries (ESP-IDF calls them components) I've written. Normally I compile the whole project and it gets installed on the ESP32, and everything works great.
I've been writing tests, and how I make the tests work is a little different than the standard build process. For each set of tests, I am testing just one of my C++ components. (for instance "Wireless" or "UserInputs", etc) I mock out the rest of my components and the ESP-IDF code that my code uses, and this lets me just test "Wireless", for instance.
To do this, I'm using CppUTest and a series of makefiles. The makefile structure is based on the structure here: https://github.com/memfault/interrupt/tree/master/example/unit-testing/minimal
And here's the article I followed that is describing that makefile/testing setup.
https://interrupt.memfault.com/blog/unit-testing-basics#setting-up-cpputest
So, there's a main makefile, and it finds all the per-component makefiles. Those per-component makefiles specify which .cpp files to compile, what folders to find your imports in, where your tests are, etc. And all that works great.
The situation I'm in is that I want to be able to run the debugger in VSCode to set breakpoints, pause execution, and inspect my variables at a given point in my code.
Just doing this in the tests is enough. I don't need debugger in my main ESP-IDF build process.
But I'm having the most challenging time working with this kind of setup. Because there's not just ONE make file.
Here's the core of what I want to do. I want to be able to set a breakpoint, and then do something to tell my code to compile with a given list of .cpp files, and header import locations. Just like in those per-component test make files. And I want my code to execute to that breakpoint and then give me the sauce in VSCode.
Any suggestions on how I can work in this direction would be very helpful.
|
I was able to work this out. Here's what I did...
Firstly, I ran my tests. Now when I look in unit_tests/build/ I see sub
folders for each make file. And in those subfolders there are executables. For instance, unit_tests/build/data/data_tests
I made a .vscode/launch.json file in my repo. It's looks like this...
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch for Dispatch Component",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/unit_tests/build/dispatch/dispatch_tests",
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
]
},
{
"name": "(gdb) Launch for Wireless Component",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/unit_tests/build/wireless/wireless_tests",
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
]
},
{
"name": "(gdb) Launch for Data Component",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/unit_tests/build/data/data_tests",
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
]
},
]
}
Notice that in that launch.json file there are multiple configurations. One for each component/make file. The name of each configuration says what component it's for, and the program field points to the executable that the tests built.
If I'm in the Data component and want to drop into a breakpoint, here's
what I do.
ensure that there's a test called by the Makefile_data.mk that hits my
breakpoint.
click the Run and Debug button on the left in VSCode. (the bug with the play button)
click the dropdown at the top of Run and Debug and select Launch for Data Component
Hit play.
Now my tests run and when they get to the breakpoint in the code in my Data
component they will pause. Pretty slick!
|
74,023,865
| 74,023,934
|
Run-time vs link-time linking of dynamic libraries
|
tl;dr
When the main application makes use of a dynamic library via dlopen and dlsym, does it need to be linked against it in any way?
Say I have a library like this,
header
#pragma once
void foo();
implementation
#include "MyLib.hpp"
#include <iostream>
void foo() {
std::cout << "Hello world, dynamic library speaking" << std::endl;
}
that I compile via
g++ -fPIC -shared MyLib.cpp -o libMyLib.so
If the main application simply uses a symbol exported by that library, e.g.
#include "MyLib.hpp"
#include <iostream>
int main() {
int x;
std::cin >> x;
std::cout << "before calling foo" << std::endl;
foo();
}
that means I have to link it against the library, i.e.
g++ -c main.cpp -o main.o
g++ -L. -lMyLib main.o -o main
There are two things that puzzle me:
The first one is: why do I need to link main.o against libMyLib.so? I mean, the header MyLib.hpp already provides main.cpp with the signature of foo. What is the role of linking in this case?
And what about the case that the main application uses dlopen to load the library and dlsym to load symbols from within it?
My understanding is that it still needs to #include "MyLib.hpp", for the simple fact that it needs to know how to interpret the output of dlsym, but does main.o need to be in anyway linked against the shared object?
|
If you use dlopen and dlsym you don't need the header file or the foo function prototype. You don't need it because the name in the library will not be plain foo.
The C++ compiler uses name mangling to be able to handle things like function overloads, and it's the mangled name you need to pass to dlsym to get a pointer to the function. The mangled names are very implementation-specific, and you need to examine the library to find out the actual mangled name.
As a workaround for the name mangling problem, you can declare the function in the library as extern "C". This will, among other things, inhibit name mangling and you can pass the name foo to dlsym.
Also, if you use dlopen and dlsym you should not link with the library. That kind of defeats the purpose of your application doing the dynamic linking.
|
74,023,996
| 74,038,567
|
OpenMP atomic on return values
|
I have some trouble understanding the definition of scalar expression in OpenMP.
In particular, I thought that calling a function and using its return value in an atomic expression is not allowed.
Looking at Compiler Explorer asm code, it seems to me as it is atomic, though.
Maybe someone can clarify this.
#include <cmath>
int f() { return sin(2); }
int main()
{
int i=5;
#pragma omp atomic
i += f();
return i;
}
|
@paleonix comment is a good answer, so I'm expanding it a little here.
The important point is that the atomicity is an issue only for the read/modify/write operation expressed by the += operator.
How you generate the value to be added is irrelevant, and what happens during generating that value is unaffected by the atomic pragma, so can still contain races (should you want them :-)).
Of course, this is unlike the use of a critical section, where the whole scope of the critical region is protected.
|
74,024,032
| 74,029,906
|
emscripten -O3 optimization gives "Import #0 module="a" error" when instantiated
|
When I am using -O2 or -O1 optimization with em++ I have no problems, but when I am using -O3 as follows:
em++ -s WASM=1 -O3 .\testFunct.c++
I got the following error when I use "instantiateStreaming" in the Javascript.
App.js:95 Uncaught (in promise) TypeError: WebAssembly.instantiate():
Import #0 module="a" error: module is not an object or function
I tried to add the following in the import:
env: {
a: () => {},
...
...
}
wasi_snapshot_preview1: {
a: () => {},
...
...
}
But I still get the same error.
|
The module is looking for an module called "a".. so in your example "a" would live alongside "env" and not within it. However, the problem here is that emscripten is performing minifcation of the strings at -O3 which makes writing the loading code by hand tricky.
Are you using the emscripten-generated JS code for loading the wasm module? Emscripten should have generated the JS file alongside the wasm file.
If you don't want to use the emscripten-generated JS (this is highly recommended since the ABI between the wasm module and the JS code can change over time), then you can build with target that when with .wasm (e.g. -o out.wasm or use the explicit --oformat=wasm flag. When you do this it should suppress the minification of the import/export names.
|
74,024,368
| 74,024,419
|
GCC compiles use of noexcept operator but clang and msvc rejects it
|
While writing code involving noexcept I made a typo and was surprised to see that the program compiled in gcc but not in clang and msvc. Demo
struct C
{
void func() noexcept
{
}
void f() noexcept(noexcept(C::func)) //gcc compiles this but clang and msvc rejects this
{
}
};
So my question is which compiler is right here(if any)?
|
The program is ill-formed and gcc is wrong in accepting the code because we cannot name a non-static member function in an unevaluated-context like decltype or sizeof or noexcept operator.
This can be seen from expr.prim.id:
An id-expression that denotes a non-static data member or `non-static member function of a class can only be used:
as part of a class member access in which the object expression refers to the member's class or a class derived from that class, or
to form a pointer to member ([expr.unary.op]), or
if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
[ Example:
struct S {
int m;
};
int i = sizeof(S::m); // OK
int j = sizeof(S::m + 42); // OK
— end example
]
And since the id-expression C::func denotes the non-static member function but does not fall under any of the three listed categories, the program is ill-formed.
Here is the gcc bug:
GCC compiles invalid use of non static member function in noexcept operator
Note also that if C::func denoted a non-static data member(instead of member function) then the program would've been well-formed because of the third bullet in the above list. Demo
Similarly, if you were to write &C::func that would also have worked(well-formed) because of the 2nd bullet in the above quoted list.
|
74,024,532
| 74,024,826
|
Is it possible to deduce the value type of a range from the range argument?
|
If you look at standard algorithms like std::ranges::fill and std::ranges::generate, they both seem to use additional parameters to deduce the range value type for their output ranges. E.g. ranges::fill(v, 10) is able to deduce the value type T because of its second argument.
However, when you try to define a similar function but take the second argument away, C++ is no longer able to deduce the value type. For instance, consider the following function:
template<typename T, std::output_range<const T&> R>
void ones(R && r)
{
for (T & value : r) {
value = 1;
}
}
The code will not compile if you try to call it without explicitly specifying the value type:
std::array<int, 3> a;
// ones(a); // does not compile
ones<int>(a); // redundant!
When I try to compile the commented-out code, I get the following error:
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp: In function ‘int main()’:
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:19:9: error: no matching function for call to ‘ones(std::array<int, 3>&)’
19 | ones(a);
| ~~~~^~~
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:9:6: note: candidate: ‘template<class T, class R> requires output_range<R, T> void ones(R&&)’
9 | void ones(R && r)
| ^~~~
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:9:6: note: template argument deduction/substitution failed:
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:19:9: note: couldn’t deduce template parameter ‘T’
19 | ones(a);
| ~~~~^~~
Is there some way to deduce the range value type that I'm missing, or is it just not possible?
|
It sounds like you want:
template <typename T> requires std::output_range<T, std::ranges::range_value_t<T>>
Or, perhaps:
template <typename T> requires std::output_range<T, const std::ranges::range_value_t<T> &>
The former expects the element to be moved, and latter expects it to be copied. If you want to support both, you can use both constraints.
|
74,025,489
| 74,025,536
|
Template Argument Deduction with different typename
|
I have defined a generic function like this:
template <typename T1, typename T2>
T2 Calculation(T1 arg_one, T1 arg_two)
{
return arg_one + arg_two * 3.14;
}
When I try to use this generic function as follow:
auto sum = Calculation(2, 3.2);
Compiler told me: no matching overloaded function found. However, when I try to use this generic function like Calculation<double, double>, it works fine.
Why compiler couldn't deduce the type of the argument and return value in first sample? I have to explicitly define types?
|
The problem is that T2 cannot be deduced from any of the function parameters and T2 also doesn't have any default argument, and template parameters can't be deduced from return type.
To solve this either you can either explicitly specify the template argument for T2 when calling the function or change T1 arg_two to T2 arg_two so that T2 can also be deduced just like T1 as shown below:
template <typename T1, typename T2>
//-------------------------vv---------->changed T1 to T2 so that T2 can be deduced from passed second argument
T2 Calculation(T1 arg_one, T2 arg_two)
{
return arg_one + arg_two * 3.14;
}
auto sum = Calculation(2, 3.2); //works now
|
74,025,596
| 74,055,490
|
Boost.Locale translation - Preventing user modifications to dictionaries / embed dictionaries in executable
|
I use Boost.Locale with ICU backend (internally using GNU gettext) to do the translations. This translation uses dictionaries stored on disk. Search paths are provided through boost's generator class like so:
boost::locale:generator gen;
gen.add_messages_path("path");
By inspecting the boost's source code, this internally later passes the paths to localzation backend through localization_backend::set_option. In case of ICU localization backend implementation that I use, this finally makes the paths to be set in gnu_gettext::messages_info (paths field).
Now as for my question - my requirement is to make sure that the user will not change the texts e.g. by modifying the .mo dictionary file on disk. The reason I use Boost.Locale is its codepage translations support, multiple languages support etc. and I want to keep that, but I don't want the ability for the user to freely define the texts later used in the application. My initial thought was to use the dictionaries "in memory" in some way, e.g. by storing .mo file contents inside executable and pass already read data into the localization_backend somehow. However, after checking how it works internally (described above) it seems that the only supported option is to have the dictionaries read in "real time" as I do the translations, which may include any changes to those files done by the user. It's either that or maybe I'm missing something?
What are my options?
|
You can use the callback field on gnu_gettext::messages_info to provide a function that will be called instead of loading messages files from disk. From Custom Filesystem Support:
namespace blg = boost::locale::gnu_gettext;
blg::messages_info info;
info.language = "he";
info.country = "IL";
info.encoding="UTF-8";
info.paths.push_back(""); // You need some even empty path
info.domains.push_back(blg::messages_info::domain("my_app"));
info.callback = some_file_loader; // Provide a callback
The callback signature is std::vector<char>(std::string const &file_name, std::string const &encoding). There's an example in the tests; this actually loads from disk, but you can adapt it to return hard-coded data instead.
|
74,025,986
| 74,026,072
|
pybind11: convert py::list to std::vector<std::string>
|
I have the following sample code which obtains a py::list as the output of evaluating some python code.
I would like to convert it to a std::vector<std::string>, but am getting an error:
conversion from 'pybind11::list' to non-scalar type
'std::vector<std::__cxx11::basic_string<char> >' requested
Per the documentation:
When including the additional header file pybind11/stl.h, conversions
between
std::vector<>/std::deque<>/std::list<>/std::array<>/std::valarray<>,
std::set<>/std::unordered_set<>, and std::map<>/std::unordered_map<>
and the Python list, set and dict data structures are automatically
enabled.
As you can see from the below code example, I have included stl.h, but automatic conversion doesn't work.
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/eval.h>
namespace py = pybind11;
py::list func()
{
py::object scope = py::module_::import("__main__").attr("__dict__");
return py::eval("[ 'foo', 'bar', 'baz' ]", scope);
}
int main()
{
Py_Initialize();
// call the function and iterate over the returned list of strings
py::list list = func();
for (auto it : list)
std::cout << py::str(it) << '\n';
// error
// conversion from 'pybind11::list' to non-scalar type 'std::vector<std::__cxx11::basic_string<char> >' requested
std::vector<std::string> vec = list;
for (auto str : vec)
std::cout << str << '\n';
return 0;
}
I can iterate over the py::list manually and call vector::push_back with each element
// populating the vector manually myself works
std::vector<std::string> vec;
vec.reserve(list.size());
for (auto it : list)
vec.push_back(py::str(it));
So I guess the linked documentation above only refers to c++ -> python conversions, and not the other way?
What is the recommended way to convert from py::list to std::vector?
|
You need to call .cast<>:
auto vec = list.cast<std::vector<std::string>>();
<pybind11/stl.h> simply brings specializations of the conversion templates that allow such cast, and that also allow implicit conversion when you bind function with vector arguments or returning vectors (or other standard containers).
|
74,026,045
| 74,026,218
|
std::ostringstream::str() outputs a string with '\0'
|
Here's a code snippet from CppRestSDK How to POST multipart data
std::stringstream bodyContent;
std::ostringstream imgContent;
bodyContent << ... << imgContent.str();
imgContent is the binary file content in which there's inevitably a '\0'.
I checked std::ostringstream::str() first,
std::ostringstream oss;
oss << "abc\0""123";
std::string s = oss.str();
cout << s.length();//3
Yes, the string would be sliced by '\0'. So I guessed the file eventually uploaded would be sliced by the '\0'. And I also checked the file, there are a lot of '\0's.
But unexpectedly, the uploaded file was intact. I got into deep confustion.
Below is the code to copy file content into the stream.
std::ifstream inputFile;
inputFile.open(imagePath, std::ios::binary | std::ios::in);
std::ostringstream imgContent;
std::copy(std::istreambuf_iterator<char>(inputFile),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(imgContent));
Edit:
Thanks @user17732522's help, I made this code to force a '\0' into the stream.
using namespace std::string_literals;
void test()
{
std::ostringstream oss;
oss << "abc\0""123"s;
std::string s = oss.str();
cout << s.length() << endl; //7
cout << (&s[0])[4] << endl;
cout << (&s[0])[5] << endl;
cout << (&s[0])[6] << endl;
}
Conclusion: str() can return a string with '\0's.
|
oss << "abc\0""123";
There will be slicing up to the \0 here, because the overload of operator<< for std::ostream which will be chosen here expects a const char* pointer to a null-terminated character string and will interpret it as such. There is no overload of operator<< for std::ostream taking a reference to a const char array. If there was, the function would be able to tell the full size of the literal and print it including the embedded null character.
bodyContent << ... << imgContent.str();
Here however str() returns a std::string which stores an explicit size and can hold null characters as part of its contents. There is an overload of operator<< for std::ostream which expects a std::string and will write its full contents, not interpreting the string contents as a null-terminated string.
A string literal can be forced into a std::string even if null characters are embedded e.g. with the help of the user-defined literal operator operator""s which produces a std::string:
using namespace std::string_literals;
oss << "abc\0123"s;
|
74,026,051
| 74,029,071
|
Drake-Ros2: Multibody Plant returns wrong values or node dies in subscriber
|
I am trying to use Drake in Ros2. The problem is that after defining my robot plant in my class constructor, some weird behavior occurs in the subscriber callback and I can't call any plant functions without the node dying. Here's what I have
class Foo : public rclcpp::Node{
public:
Foo() : Node("foo_node") {
auto [plant_, scene_graph_] = drake::multibody::AddMultibodyPlantSceneGraph(&builder, 0.0);
plant = &plant_;
scene_graph = &scene_graph_;
auto parser = drake::multibody::Parser(plant, scene_graph);
parser.package_map().AddPackageXml(pkg_xml_dir);
auto model_ = parser.AddModelFromFile(model_path);
model = &model_;
plant->WeldFrames(plant->world_frame(), plant->GetFrameByName("base"));
plant->Finalize();
std::unique_ptr<drake::systems::Diagram<double>> diagram = builder.Build();
context = diagram->CreateDefaultContext();
plant_context = &plant->GetMyMutableContextFromRoot(context.get());
// first print
std::cout << "--------------" << std::endl;
std::cout << plant->is_finalized() << std::endl;
std::cout << plant->HasFrameNamed("link_3") << std::endl; // prints 1
std::cout << plant->HasFrameNamed("link_3", *model) << std::endl; // prints 1
std::cout << plant->HasFrameNamed("base", *model) << std::endl; // prints 1
std::cout << plant->num_frames() << std::endl; // prints N
std::cout << "--------------" << std::endl;
// Subscriber to update current state
state_current_sub = this->create_subscription<sensor_msgs::msg::JointState>("/joint_states", 10, std::bind(&Foo::update_current_state, this, _1));
private:
rclcpp::Subscription<sensor_msgs::msg::JointState>::SharedPtr state_current_sub;
drake::systems::DiagramBuilder<double> builder;
drake::multibody::MultibodyPlant<double>* plant;
drake::geometry::SceneGraph<double>* scene_graph;
std::string pkg_xml_dir = "/path/to/package.xml";
std::string model_path = "/path/to/robot.urdf";
drake::systems::Context<double>* plant_context;
std::unique_ptr<drake::systems::Context<double>> context;
drake::TypeSafeIndex<drake::multibody::ModelInstanceTag>* model;
void update_current_state(const sensor_msgs::msg::JointState::SharedPtr msg){
// Second print
std::cout << "--------------" << std::endl;
std::cout << plant->is_finalized() << std::endl; // prints 1
std::cout << plant->HasFrameNamed("link_3") << std::endl; // prints 0
std::cout << plant->HasFrameNamed("link_3", *model) << std::endl; // Dies with 'there is no model instance id 0/2/(random number) in the model.'
std::cout << plant->HasFrameNamed("base", *model) << std::endl; //
std::cout << plant->num_frames() << std::endl; // prints N
std::cout << "--------------" << std::endl;
auto & ee_frame = plant->GetFrameByName("link_3"); // Can't find frame with that name
auto G = plant->CalcGravityGeneralizedForces(*plant_context); // Dies with exit code -11
}
}
In the second print everything goes wrong. Calling the same functions as before, for example to check if a frame exists, won't work, even though it does the first time. My node either prints something wrong (that the frame doesn't exists), or dies with exit code -11 or with there is no model instance id 0/2/(random number) in the model., depending on which functions I use.
My guess is that there is some problem with the plant definition and usage. Any ideas on what should I change ?
|
First off, have you been able to briefly peruse drake-ros?
https://github.com/RobotLocomotion/drake-ros/tree/develop
It's still under development, but may have useful tidbits / utilities. It is mentioned at the bottom of Drake's website: https://drake.mit.edu/
Second off, I believe your plant is going out of scope.
Please note that diagram is actually the new owner of plant, scene_graph once builder.Build() is called. You must store that as a member variable.
If you do that, then plant should stay in scope, and it should resolve this issue.
For more info, see: https://drake.mit.edu/doxygen_cxx/classdrake_1_1systems_1_1_diagram_builder.html
Specifically:
It is single use: after calling Build or BuildInto, DiagramBuilder gives up ownership of the constituent systems, and should therefore be discarded
|
74,026,068
| 74,027,779
|
ld.exe: cannot find src: Permission denied
|
Basically im trying to build a game engine with OpenGl and SDL. Im using a makefile to compile it but I get an error. The error started appearing after I reorganized my folder structure and I included the src folder to the include path so i can access them with the absolute path. For example Renderer/Camera.h instead of ../Renderer/Camera.h.
When I try to compile my project I get this error:
C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find src: Permission denied
collect2.exe: error: ld returned 1 exit status
mingw32-make: *** [Makefile:57: build] Error 1
This is my makefile
RELEASE_MACRO:=-D RELEASE
DEBUG_MACRO:=-D DEBUG
OS_MACRO:=-D
BIN := bin
SRC := src
INCLUDE := -Isrc -Iinclude
LIB := lib
#Check the OS
ifeq ($(OS),Windows_NT)
# the compiler: gcc for C program, define as g++ for C++
CC := g++
# The windows command for delete
DEL := del
# The windows slash for directory
SLASH := \
# Indicating that we dont need wine, unlike in linux
WINE :=
OS_MACRO +=__WINDOWS__
SOURCES := $(wildcard $(SRC)/***/*.cpp) $(wildcard $(INCLUDE)/***/*.cpp) $(wildcard $(SRC))
else
# CURRENTLY NOT WORKING
# Linux compiler for windows executables (64 bits)
CC := x86_64-w64-mingw32-g++
# Linux command for delete (rm -f)
DEL := $(RM)
# Linux slash for directory
SLASH := '/'
# Wine, program for executing windows apps .exe
WINE := wine
OS_MACRO +=__LINUX__
SOURCES := $(shell dir . -r *.cpp)
endif
# compiler flags:
# -g adds debugging information to the executable file
# -Wall turns on most, but not all, compiler warnings
CFLAGS:= -g -Wall
# libraries to link to the project
LIBRARIES := -lmingw32 -lSDL2main -lSDL2 -lSDL2_net -lSDL2_mixer -lmingw32 -lopengl32 -lglew32 -lglu32 -lSDL2main -lSDL2 -lSDL2_image
# the build target executable
EXECUTABLE := game
all: build
showfiles:
@echo $(SOURCES)
# Builds the executable game
build:
echo "Building..."
$(CC) $(CFLAGS) $(INCLUDE) -L $(LIB) $(OS_MACRO) $(DEBUG_MACRO) -o $(BIN)/$(EXECUTABLE) $(SOURCES) $(LIBRARIES)
# Run the game
run:
@echo "Executing..."
$(WINE) $(BIN)/$(EXECUTABLE)
# Build then run the game
build-and-run: clean build run
# Remove the executable
clean:
@echo "Clearing..."
$(DEL) bin$(SLASH)$(EXECUTABLE).exe
This is my project folder structure
|
This is not valid:
SOURCES := $(wildcard $(SRC)/***/*.cpp) $(wildcard $(INCLUDE)/***/*.cpp) $(wildcard $(SRC))
I don't know where you got that wildcard syntax from but it doesn't do what you think it does. *** is identical to * in standard glob syntax which is what GNU make uses. Also do you really expect to find .cpp files in your $(INCLUDE) directory? That would be very strange.
The problem, as ssbssa points to, is that $(wildcard $(SRC)) will expand to $(wildcard src) which is just src, so you're trying to add a directory to your link line which is illegal and the linker complains.
|
74,026,860
| 74,027,027
|
What is a disadvantage of initializing a smart pointer data member in a member initializer list?
|
Let's say there is a class B which has a smart pointer member for a pointer to object of class A. Then, what is a disadvantage of initializing the smart pointer member in a member initializer list? I know that initializing is faster than assignment (would be resetting here), but I have no idea about disadvantages. What is a disadvantage of initializing a smart pointer in a member initializer list?
#include <chrono>
#include <iostream>
#include <memory>
struct A {
};
struct B1 {
B1(): a(new A) {}
std::unique_ptr<A> a;
};
struct B2 {
B2() {
a.reset(new A);
}
std::unique_ptr<A> a;
};
int main() {
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
for(auto i=0; i < 100000; ++i) {
B1 b;
// B2 b;
}
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << (end - begin).count() << std::endl;
}
B1: 8054043, B2: 8894576
|
There is no disadvantage and you should initialize it in the member initializer list. However I doubt it will make any performance difference at all. (Your test doesn't work. It is either done without optimizations enabled or measuring random noise.)
However usually it is recommended to not use new directly, but std::make_unique instead.
Also, if the value that is going to be initialized doesn't depend on the arguments to the constructor using a default initializer might be a better approach:
struct B1 {
std::unique_ptr<A> a = std::make_unique<A>();
};
|
74,026,892
| 74,027,412
|
cmake - add .so library with it's .h headers
|
I have a project with structure like this:
project/
├─ src/
│ ├─ main.cpp
│ ├─ CMakeLists.txt
├─ lib/
│ ├─ libapi.so
├─ CMakeLists.txt
├─ dep/
│ ├─ api/
│ │ ├─ api_types.h
In the main CMakeLists I have:
add_subdirectory(dep)
add_executable("my_${PROJECT_NAME}")
add_subdirectory(src)
And in CMakeLists inside src folder:
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
add_library(api SHARED IMPORTED)
set_property(TARGET api PROPERTY IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libapi.so")
target_sources("my_${PROJECT_NAME}" PRIVATE main.cpp)
In main.cpp I do #include <api_types.h> but I get this error during compile:
api_types.h: No such file or directory
How can I fix it?
|
First - add_subdirectory in fact just looks for CMakeLists.txt in
the specified directory to apply the sub-set of the rules to the
parent project. If the specified folder doesn't contain any
CMakeLists.txt this command does nothing (i.e. the command
add_subdirectory(dep)).
Second - target_include_directories expects a target object to link against (not the project name). Assuming ${PROJECT_NAME} is not a name of any of your targets (and the code given in the question reveals only two targets my_${PROJECT_NAME} and api) the command target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) does nothing sensible.
Last - you don't specify path to your actual headers anywhere. CMAKE_CURRENT_SOURCE_DIR refers to the current folder CMakeLists.txt is located in. You should specify path to the folder the headers are located in.
Putting all the said info together, the desired content for the top-level CMakeLists.txt should be something like that:
cmake_minimum_required(VERSION 3.20)
set(PROJECT_NAME Hello)
project(${PROJECT_NAME})
add_executable(my_${PROJECT_NAME})
add_subdirectory(src)
And for src's file it's apparently something like that:
target_include_directories(my_${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/dep/api)
target_sources(my_${PROJECT_NAME} PRIVATE main.cpp)
This solution, however, doesn't resolve another mistake in your code - the CMake files you provided don't link the library itself to the executable target. However this is not the question asked, and with respect to the members of the community, I suggest referring to answers to another related question here.
|
74,027,016
| 74,027,110
|
std::filesystem::weakly_canonical() does not seem to work with drive letters
|
The following code:
#include <iostream>
#include <filesystem>
int main()
{
std::filesystem::path path("C:");
std::filesystem::path canonicalPath = std::filesystem::weakly_canonical(path);
std::cout << canonicalPath.string() << std::endl;
}
produces the output:
C:\Users\andy\source\repos\ConsoleApplication8\ConsoleApplication8
using Visual Studio 2019 X64.
On x86-64 gcc it produces what I expect: C: according to godbolt.org.
|
Windows and Linux have different rules when it comes to paths.
For example, on Windows using the drive-letter and colon only means the current directory on the specified drive. This behavior is inherited from DOS.
When you build using GCC on the compiler explorer, it uses a virtual Linux environment, and Linux doesn't have drive letters. Which means that C: isn't a path in Linux, but rather a file-name.
|
74,027,618
| 74,027,999
|
Is there a way to pass a &CustomType or *CustomType into the "Stream Insertion" Operator?
|
Spoiler-Alert: I forgot the * in the header file, it compiled but ignored my operator overload, and just printed the adress.
Leading to this confused mess of a question, i'm so sorry! Thank you all!
I've included a simple example of what i want to do.
I have a pointer to a class, and i need to output it using <<,
WITHOUT copying the value first.
I implemented an operator<< function that takes a reference as an argument. This has been suggested in several answers on StackOverflow as well -
However, i can't get the compiler to actually pick my overloaded operator function.
When i run the example below, it simply returns 0x6af59ffac0
(because the standard << implementation for pointers is used)
Granted, you could always dereference the pointer and write a pass-by-value operator<< function.
But in my case this is not alllowed, as no other instance of the class should be created on the stack. (Basically trying to achive this without copying the class)
So, at this point i am probably going to simply avoid the << operator in that specific case, and write my own function. (see the workaround at the bottom)
But i can't help being frustrated at this. Surely, there should be a way to hint to the compiler which version of the operator to use?
(Similar to rust's Turbofish Operator ::<>)
Or is this legitimately impossible?
Example::
#include <iostream>
using namespace std;
class TEST {
public:
string name;
int id;
TEST(string nname, int iid) : name(nname), id(iid) {}
};
std::ostream& operator<<(std::ostream& out, TEST &m) {
return out << "Test Output, class has values: ID" << m.id << "; NAME: " << m.name;
}
int main() {
TEST var("tester", 22);
cout << &var; // Just prints the memory location
cout << (TEST*) &var; // Still just prints the memory location
return 0;
}
What i would do to avoid the language limitation (in case noone has an answer):
(this works for me since a method doesn't have a copy of its class in its stack frame, just a pointer)
#include <iostream>
using namespace std;
class TEST {
public:
string name;
int id;
TEST(string nname, int iid) : name(nname), id(iid) {}
std::ostream& display(std::ostream& out) {
return out << "Test Output, class has values: ID" << this->id << "; NAME: " << this->name;
}
};
std::ostream& operator<<(std::ostream& out, TEST m) {
return m.display(out);
}
int main() {
TEST var("tester", 22);
var.display(cout);
return 0;
}
|
I have a pointer to a class, and i need to output it using <<, WITHOUT copying the value first.
You wrote
std::ostream& operator<<(std::ostream& out, TEST &m)
which takes a reference to a TEST object and doesn't copy anything. Why did you think it would copy something?
Anyway, that stream insertion operation probably should be
std::ostream& operator<<(std::ostream& out, TEST const &m)
(since it shouldn't be changing the object it prints).
However, i can't get the compiler to actually pick my overloaded operator function.
Well, you wrote an overload that takes a reference argument. You have to pass a reference, because that's the type you wrote. To get one that takes a pointer ... just write one that takes a pointer argument instead
std::ostream& operator<<(std::ostream& out, TEST const *m)
{
return out << "TEST* : ID" << m->id << "; NAME: " << m->name;
}
Note that the default ostream& operator<<(ostream&, void*) is always a worse match than any specific non-void pointer overload. It just fell back on that because it was the only match available.
Just to clarify again
Granted, you could always dereference the pointer and write a pass-by-value operator<< function
nobody has suggested a pass-by-value operator<<, and that isn't what you originally wrote. You did add a pass-by-value version in your second code block but, since the first version was pass-by-reference, I don't know why. If you don't know how to read basic syntax like &, * and ->, this would be an excellent time to read a good book.
|
74,027,730
| 74,029,807
|
cin checking input only numbers in range from 0 to 255
|
cin >> red_rgb;
How to check the red_rgb, green_rgb, blue_rgb variable when entering it, so that only values in the range from 0 to 255 are allowed, while only integers {0,1,2...254,255} are counted, otherwise, you will need to enter the correct value.
int red_rgb = 0;
int green_rgb = 0;
int blue_rgb = 0;
std::cout << "Enter R: ";
while (!(cin >> red_rgb) || !(red_rgb >= 0 && red_rgb <= 255))
{
cout << "Error";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
std::cout << "Enter G: ";
while (!(cin >> green_rgb) || !(green_rgb >= 0 && green_rgb <= 255))
{
cout << "Error";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
std::cout << "Enter B: ";
while (!(cin >> blue_rgb) || !(blue_rgb >= 0 && blue_rgb <= 255))
{
cout << "Error";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
This method tests for a range, but skips semicolons. And if you enter letters instead of numbers, the more letters there are, the more times the cycle will start.
if you enter a float, the cycle for entering the next value is skipped
enter image description here
|
Try something like that:
int inprgb(const string& hint){
int a=-1;
while (true){
cout << hint;
cin>>a;
if (cin.fail() || cin.peek()!=10 ||!(a >= 0 && a <= 255) ) {
cin.clear();
cout << "Error\n";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
break;
}
return a;
};
and
red_rgb = inprgb("Enter R: ");
|
74,028,163
| 74,031,170
|
What will std::sort do if the comparison is inconsistent? (A<B, B<C, C<A)
|
I need to sort a file list by date. There's this answer how to do it. It worries me though: it operates on a live filesystem that can change during operation.
The comparison function uses:
struct FileNameModificationDateComparator{
//Returns true if and only if lhs < rhs
bool operator() (const std::string& lhs, const std::string& rhs){
struct stat attribLhs;
struct stat attribRhs; //File attribute structs
stat( lhs.c_str(), &attribLhs);
stat( rhs.c_str(), &attribRhs); //Get file stats
return attribLhs.st_mtime < attribRhs.st_mtime; //Compare last modification dates
}
};
From what I understand, this function can, and will be called multiple times against the same file, comparing it against different files. The file can be modified by external processes while sort is running; one of older files can become the newest in between two comparisons and turn up older than a rather old file, and later newer than one of newest files...
What will std::sort() do? I'm fine with some scarce ordering errors in the result. I'm not fine with a crash or a freeze (infinite loop) or other such unpleasantries. Am I safe?
|
As other answers have already said, handing std::sort a comparator that doesn't satisfy the weak strict ordering requirement and is preserved when called multiple times with the same value will cause undefined behavior.
That doesn't only mean that the range may end up not correctly sorted, it may actually cause more serious problems, not only in theory, but also in practice. A common one is as you already said infinite loops in the algorithm, but it can also introduce crashes or vulnerabilities.
For example (I haven't checked whether other implementations behave similarly) I looked at libstdc++'s std::sort implementation, which as part of introsort uses insertion sort. The insertion sort calls a function __unguarded_linear_insert, see github mirror. This function performs a linear search on a range via the comparator without guarding for the end of the range, because the caller is supposed to have already verified that the searched item will fall into the range. If the result of the comparison changes between the guard comparison in the caller and the unguarded linear search, the iterator will be incremented out-of-bounds, which could produce a heap overrun or null dereference or anything else depending on the iterator type.
Demonstration see https://godbolt.org/z/8qajYEad7.
|
74,028,371
| 74,028,530
|
C++: Is there a simple way of using a namespace as template?
|
Is there a way to use a namespace as a template?
I need to call the same function but from a different namespaces.
Something like that:
There are two namespaces here myNamespace1, myNamespace2 that contain a function with the same name - func()
#include <iostream>
using namespace std;
namespace myNamespace1 {
void func()
{
std::cout<<"myNamespace1" << std::endl;
}
}
namespace myNamespace2 {
void func()
{
std::cout<<"myNamespace2" << std::endl;
}
}
template<auto T>
class A {
public:
void func()
{
T::func();
}
};
}
int main() {
using namespace myNamespace1;
using namespace myNamespace2;
A<myNamespace1> a1;
a1.func(); // output: myNamespace1
A<myNamespace2> a2;
a2.func(); // output: myNamespace2
return 0;
}
|
A namespace may not be used as a template parameter. But you can use for example a non-type template parameter that denotes a function like for example
#include <iostream>
namespace myNamespace1 {
void func()
{
std::cout << "myNamespace1" << std::endl;
}
}
namespace myNamespace2 {
void func()
{
std::cout << "myNamespace2" << std::endl;
}
}
template<void ( &Func )()>
class A {
public:
void func()
{
Func();
}
};
int main()
{
A<myNamespace1::func> a1;
a1.func();
A<myNamespace2::func> a2;
a2.func();
}
The program output is
myNamespace1
myNamespace2
|
74,028,481
| 74,029,541
|
Mult-output files with Makefile
|
I am a cuda programmer and new in vscode and Makefile environment.
For a better programming, I use multiple .cu files for my functions. Thus, for the pull_model and build_meshgrid functions, the makefile becomes:
# Target rules
all: build
build: kernel
check.deps:
ifeq ($(SAMPLE_ENABLED),0)
@echo "Launch file will be waived due to the above missing dependencies"
else
@echo "Launch file is ready - all dependencies have been met"
endif
kernel: kernel.o Engine/Engine.o Engine/pull_model.o Engine/build_meshgrid.o
$(EXEC) $(NVCC) $(ALL_LDFLAGS) $(GENCODE_FLAGS) -o $@ $+ $(LIBRARIES)
$(EXEC) mkdir -p bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
$(EXEC) cp $@ bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
%.o: %.cu
$(EXEC) $(NVCC) $(INCLUDES) $(ALL_CCFLAGS) $(GENCODE_FLAGS) -o $@ -c $<
run: build
$(EXEC) ./kernel
testrun: build
clean:
rm -f kernel *.o Engine/*.o
rm -rf bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)/kernel
clobber: clean
I need to reduce the kernel somehow, like this:
kernel: kernel.o Engine/*.o
$(EXEC) $(NVCC) $(ALL_LDFLAGS) $(GENCODE_FLAGS) -o $@ $+ $(LIBRARIES)
$(EXEC) mkdir -p bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
$(EXEC) cp $@ bin/$(TARGET_ARCH)/$(TARGET_OS)/$(BUILD_TYPE)
So, all .cu files under Engine folder are targed.
Best Regards!
|
Well, you can't use Engine/*.o because when you run your makefile, no object files exist and so this wildcard will expand to nothing, then nothing will be built (except kernel.o).
It's a catch-22 because you can't just tell make "build all the object files that you would build if you knew which objects to build!"
If what you want is to build object files for all source files in the Engine directory, you can tell make to do that:
SRCS := $(wildcard Engine/*.c)
OBJS := $(SRCS:%.c=%.o)
kernel: kernel.o $(OBJS)
....
|
74,029,014
| 74,029,278
|
Using an atomic enum class in C++11 switch statement
|
Not sure this is possible, but if so, how do you use an atomic enum class for a switch statement in C++11? For example,
#include <atomic>
#include <iostream>
enum class A {RED, FRUIT, APPLE};
int main(){
std::atomic<A> myAtomicEnum;
myAtomicEnum = A::RED;
switch (myAtomicEnum){
case A::RED:
std::cout << "A::RED \n";
break;
default:
break;
}
return 0;
}
gives a compiler error
error: multiple conversions from switch condition type
'std::atomic<A>' to an integral or enumeration type
switch (myAtomicEnum){
A different question using an enum class (not atomic) forced a conversion to arithmetic type using a unary +, but you can't pass an std::atomic<A> to the unary +. I don't receive any errors using a non-atomic enum class and not using a unary +, e.g.
#include <iostream>
enum class A {RED, FRUIT, APPLE};
int main(){
A myEnum = A::RED;
switch (myEnum){
case A::RED:
std::cout << "A::RED \n";
break;
default:
break;
}
return 0;
}
which outputs A::RED as expected.
The context of the problem is that I have a class with a member that may be read/written to by multiple threads and a switch statement using that member. I have a workaround using mutex-es so that I have well-defined behavior but would like to use atomic if possible.
|
In C++ 11, you may explicitly cast atomic type variable to enum type, this will call std::atomic<T>::operator T() casting operator of the object:
switch ((A)myAtomicEnum){
case A::RED:
...
Btw, starting from C++ 14 this explicit cast is not needed, and cast to switch type will be done implicitly (cppreference.com, Implicit conversions page)
|
74,029,772
| 74,032,137
|
Is there any point in using __attribute__((noinline)) in a source file (not header file)?
|
Some programmers at my company have started sprinkling __attribute__((noinline)) in methods all over our code, in both header and source files. We do not use whole-program optimization. And in the vast majority of the cases I'm seeing, these methods are not calling other methods in the same source file ("translation unit"); the only callers of these "noinline" methods are (in most cases) methods in other source files.
I want to make a point that these __attribute__((noinline)) attribute markers are not doing anything and only clutter our code, but before I do that I just want to verify that I'm right:
Is there any benefit to marking a method "noinline" if its definition (code body) is...
in a source (.c or .cpp) file
not called by any other methods in that source file
and whole program optimization is not being used
...?
I.e., in the absence of whole-program optimization, could a compiler+linker even inline a method defined as such (above bullet points) anyway?
|
Is there any benefit to marking a method "noinline" if its definition
(code body) is...
in a source (.c or .cpp) file
not called by any other methods in that source file
and whole program optimization is not being used
...?
The position of the attribute on the function / method definition instead of on a non-definition declaration is not necessarily relevant in the particular case of a noinline attribute, because in order for inlining to be performed, some form of the function's definition (which bears the attribute) must be available.
Certainly the function won't be inlined into any other functions in the same translation unit if no other functions in that unit call it in the first place, directly or indirectly.
The "whole program optimization is not being used" seems to be an attempt to stipulate that the function in question cannot be inlined into any other functions, either. In that case, the noinline attribute is, by assumption, unnecessary to prevent inlining of that function.
I.e., in the absence of whole-program optimization, could a
compiler+linker even inline a method defined as such (above bullet
points) anyway?
This seems to be a question of semantics. I would categorize any optimization that crosses translation-unit boundaries as a "whole-program optimization". In that sense, then, no, a build process that does not perform any whole-program optimization will not perform the specific whole-program optimization of inlining a function from one TU into a function from a different TU.
Since you have not specified any details of your compilation procedure, we cannot speak to whether it is really true in your particular case that whole program optimzation is not being used, in the sense described above.
However, whether the attribute is necessary to prevent inlining of functions in your current code base is not the only consideration relevant to the "Is there any benefit?" question. Consider:
Whether the attribute is necessary to prevent inlining or not, it is effective at communicating the intent that the function should not be inlined.
In the event that your analysis of the code is wrong, or the code changes so that it no longer applies, the noinline attributes will provide for the desired inlining-suppression behavior.
Both of these are reminiscent of the nature and (proper) usage of assertions. If an assertion in my program ever triggers then that means a situation has arisen that I believed could not happen and assumed would not happen. Are assertions then just wasteful code? No, certainly not. They serve a documentary purpose (often supplemented with explanatory code comments), an error detection purpose, and often a failsafe purpose. Similar can be said of use of noinline under the circumstances you describe.
|
74,030,006
| 74,030,608
|
Where to put member variables in my interface?
|
The c++ guidelines say not to put any data in the base class and also not to use trivial getter and setter methods, but rather just member variables, but where do I put the member variables in my data base access implementation? If I put it in one of the derived classes, I get the compiler error that my class db_interface does not have such a member.
#include <boost/core/noncopyable.hpp>
#include <postgresql/libpq-fe.h>
#include <sqlite3.h>
#include <iostream>
#include <string>
class db_interface : boost::noncopyable{
public:
void connect() const {connect_to_DB();}
virtual ~db_interface(){};
private:
virtual void connect_to_DB() const = 0;
};
class postgreSQL : public db_interface{
private:
void connect_to_DB() const { std::cout << "THIS IS POSTGRESQL"<< std::endl; }
};
class liteSQL : public db_interface{
public:
std::string dbName;
private:
void connect_to_DB() const { std::cout << "THIS IS LIGHTSQL"<< std::endl; }
};
class DBFactory {
public:
virtual db_interface *createDB(std::string) = 0;
};
class Factory: public DBFactory {
public:
db_interface *createDB(std::string type) {
if(type == "LiteSQL") {
return new liteSQL;
}
else if(type == "PostgreSQL") {
return new postgreSQL;
}
return nullptr;
}
};
|
It's worth pointing out the guidelines are just that. Some of them even contradict each other. It's up to you to be the engineer and decide what guidelines make sense for you and your project.
However, these guidelines do not really contradict each other.
The first one you linked to is: C.133: Avoid protected data
The other guideline linked in that one is: C.121: If a base class is used as an interface, make it a pure abstract class
The other guideline linked is the one you seem to be skipping and subsequently tripping yourself over: C.9: Minimize exposure of members
C.133 links to last one with the text Prefer private data.
The ideas being presented do not conflict, but they do take the separation of concerns to a level that is less common in C++ land.
Mainly, your interface should just be an interface. In that regard, putting data in your interface makes no sense.
You can then derive from that interface to create your 'base' class. When here, don't make your data protected. Make it private. Your base class is then the only class responsible for that data. Protected functions like getters and setters do make sense here for your derived classes to make changes which your base class alone is responsible for handling/validating.
On top of that, I actually don't like the idea of the interface being all public pure virtual functions and instead I prefer NVI or Non-Virtual Interfaces. Here's a short example:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// Interface
class PetInterface {
public:
virtual ~PetInterface() = default;
std::string speak() const { return speak_v(); }
std::string name() const { return name_v(); }
private:
virtual std::string speak_v() const = 0;
virtual std::string name_v() const = 0;
};
// Base class
class Pet : public PetInterface {
public:
Pet() = default;
Pet(std::string name, std::string vocal) : m_name(name), m_vocal(vocal) {}
virtual ~Pet() = default;
private:
std::string m_name;
std::string m_vocal;
protected:
std::string name() const { return m_name; }
std::string vocal() const { return m_vocal; }
};
class Dog final : public Pet {
public:
Dog() = default;
Dog(std::string name) : Pet(name, "Woof") {}
private:
std::string speak_v() const override { return vocal(); }
std::string name_v() const override { return name(); }
};
class Cat final : public Pet {
public:
Cat() = default;
Cat(std::string name) : Pet(name, "Meow") {}
private:
std::string speak_v() const override { return vocal(); }
std::string name_v() const override { return name(); }
};
int main() {
std::vector<std::unique_ptr<PetInterface>> pets;
pets.emplace_back(new Dog("Fido"));
pets.emplace_back(new Cat("Dame Whiskers"));
for (const auto& i : pets) {
std::cout << i->name() << " says \"" << i->speak() << "\"\n";
}
}
Output:
❯ ./a.out
Fido says "Woof"
Dame Whiskers says "Meow"
Pet is still an abstract class, as only 'leaf' classes should be concrete.
One final note is that you don't need boost to make a thing non-copyable. Just = delete the copy constructor and copy assignment operator.
|
74,031,183
| 74,034,022
|
Cleanest way to handle both quoted and unquoted strings in Spirit.X3
|
Buon giorno,
I have to parse something such as:
foo: 123
"bar": 456
The quotes should be removed if they are here. I tried:
((+x3::alnum) | ('"' >> (+x3::alnum) >> '"'))
But the parser actions for this are of type variant<string, string> ; is there a way to make it so that the parser understands that those two are equivalent, and for my action to only get a single std::string as argument in its call?
edit: minimal repro (live on godbolt: https://gcc.godbolt.org/z/GcE8Pj4r5) :
#include <boost/spirit/home/x3.hpp>
using namespace boost::spirit;
// action handlers
struct handlers {
void create_member(const std::string& str) { }
};
// rules
static const x3::rule<struct id_obj_mem> obj_mem = "obj_mem";
#define EVENT(e) ([](auto& ctx) { x3::get<handlers>(ctx).e(x3::_attr(ctx)); })
static const auto obj_mem_def = ((
((+x3::alnum) | ('"' >> (+x3::alnum) >> '"'))
>> ':' >> x3::lit("123"))[EVENT(create_member)] % ',');
BOOST_SPIRIT_DEFINE(obj_mem)
// execution
int main()
{
handlers r;
std::string str = "foo: 123";
auto first = str.begin();
auto last = str.end();
bool res = phrase_parse(
first,
last,
boost::spirit::x3::with<handlers>(r)[obj_mem_def],
boost::spirit::x3::ascii::space);
}
|
I too consider this a kind of defect. X3 is definitely less "friendly" in terms of the synthesized attribute types. I guess it's just a tacit side-effect of being more core-language oriented, where attribute assignment is effectively done via default "visitor" actions.
Although I understand the value of keeping the magic to a minimum, and staying close to "pure C++", I vastly prefer the Qi way of synthesizing attributes here. I believe it has proven a hard problem to fix, as this problem has been coming/going in some iterations of X3.
I've long decided to basically fix it myself with variations of this idiom:
template <typename T> struct as_type {
auto operator()(auto p) const { return x3::rule<struct Tag, T>{} = p; }
};
static constexpr as_type<std::string> as_string{};
Now I'd write that as:
auto quoted = '"' >> +x3::alnum >> '"';
auto name = as_string(+x3::alnum | quoted);
auto prop = (name >> ':' >> "123")[EVENT(create_member)] % ',';
That will compile no problem:
Live On Coliru
#include <boost/spirit/home/x3.hpp>
#include <iomanip>
#include <iostream>
namespace x3 = boost::spirit::x3;
struct handlers {
void create_member(std::string const& str) {
std::cerr << __FUNCTION__ << " " << std::quoted(str) << "\n";
}
};
namespace Parser {
#define EVENT(e) ([](auto& ctx) { get<handlers>(ctx).e(_attr(ctx)); })
template <typename T> struct as_type {
auto operator()(auto p) const { return x3::rule<struct Tag, T>{} = p; }
};
static constexpr as_type<std::string> as_string{};
auto quoted = '"' >> +x3::alnum >> '"';
auto name = as_string(+x3::alnum | quoted);
auto prop = (name >> ':' >> "123")[EVENT(create_member)] % ',';
auto grammar = x3::skip(x3::space)[prop];
} // namespace Parser
int main() {
handlers r;
std::string const str = "foo: 123";
auto first = str.begin(), last = str.end();
bool res = parse(first, last, x3::with<handlers>(r)[Parser::grammar]);
return res ? 1 : 0;
}
Prints
create_member "foo"
Interesting Links
Spirit X3, How to get attribute type to match rule type?
Combining rules at runtime and returning rules
spirit x3 cannot propagate attributes of type optional<vector>
etc.
|
74,031,210
| 74,032,845
|
c++ - deterministic alternative to std::uniform_XXX_distribution with mt19937?
|
I need a way to get deterministic sequences of ints and doubles.
template <class U>
constexpr auto get_random_value (std::mt19937 &gen, U min_value, U max_value)->U
{
if constexpr ( std::is_same_v <U, double> or std::is_same_v <U, float> ){
std::uniform_real_distribution <U> distrib( min_value, max_value );
return distrib( gen );
}
else if constexpr ( std::is_same_v <U, u32> or std::is_same_v <U, i32> ){
std::uniform_int_distribution distrib( min_value, max_value );
return distrib( gen );
}
else {
throw std::runtime_error( "error value type" );
}
}
My issue is that one day to another, the same seeded value will lead to different results.
The distribution is to blame because it goes a long way to avoid the pitfall of the modulo.
But I need a precise way to always be certain that a sequence will always be the same starting from a given seed. And I need an unbiased partition (so % and rand() are out).
What kind of implementation will guarantee this?
|
The distributions in the C++ standard are not portable ("seed-stable"), in the sense that the result can change between different implementations (e.g. Microsoft STL vs gcc libstdc++ vs clang libc++) or even different versions (e.g. Microsoft changed their implementation before). The standard simply does not prescribe a specific algorithm, with the intention to allow implementations to select the one with the best performance for each platform.
So far, there is only a proposal (D2059R0) to do something about this.
Note, however, that the generators are actually portable.
I have yet to see a library that guarantees portability.
However, in practice boost.random is known to produce reproducible result across platforms (see e.g. here or here or here). Also, Google's abseil library explicitly states that they do not provide a stability guarantee, but seems to produce the same result on different platforms nevertheless.
Here is a live example on godbolt where you can see that to some extent (well, at least Linux vs Windows for a tiny selection of parameters).
The major point is not to update the libraries without checking for a breaking change. Also compare e.g. this blog post.
Or you could also implement a specific algorithm yourself (see e.g. here) or simply copy the code from one the libraries to your code base and thereby effectively freezing its version.
For distributions involving floating point arithmetic, you also have the problem that the arithmetic itself is, generally speaking, far from stable across platforms since stuff like automatic vectorization (SSE2 vs AVX etc) or FPU settings might change behavior. See this blog post for more information. How far distributions, including the above mentioned libraries, are affected by this, I unfortunately do not know. The small example on godbolt mentioned above does at least not show any problem with -ffast-math, which is a good sign.
Whatever you do, I highly recommend to back up your choice by appropriate automatic tests (unit tests etc.) that catch any potential deviations in behavior.
|
74,031,454
| 74,031,652
|
Subset algorithm behaves differently in Python than C++
|
The algorithm follows recursive approach, dividing the array in two parts:
In first recursion the first part is neglected
In second part the first part is added
Code for C++ (Works Fine)
class Solution {
public:
vector<vector<int>> result;
void get_set(vector<int>& nums, vector<int> res, int index=0)
{
if(index == nums.size())
{
result.push_back(res);
return;
}
int top = nums[index++];
get_set(nums, res, index);
res.push_back(top);
get_set(nums, res, index);
}
vector<vector<int>> subsets(vector<int>& nums)
{
vector<int> res;
get_set(nums, res);
return result;
}
};
Code for Python
class Solution:
def __init__(self):
self.result = [[]]
def get_subsets(self, arr, temp=[], index=0):
if(index==len(arr)):
self.result.append(temp)
return
top = arr[index]
index+=1
self.get_subsets(arr, temp, index)
temp.append(top)
self.get_subsets(arr, temp, index)
def subsets(self, nums: List[int]) -> List[List[int]]:
self.get_subsets(nums)
return self.result
|
In the C++ version, res is a by-value parameter, so a copy of the vector is made in each call. Python passes references to the list, so you keep modifying the same temp list throughout the algorithm. Pass a copy when you make the recursive calls.
There's also no need for an empty nested list in the initial value of self.result. The C++ version starts with an empty vector.
class Solution:
def __init__(self):
self.result = []
def get_subsets(self, arr, temp=None, index=0):
if temp is None:
temp = []
if(index==len(arr)):
self.result.append(temp)
return
top = arr[index]
index+=1
self.get_subsets(arr, temp.copy(), index)
temp.append(top)
self.get_subsets(arr, temp.copy(), index)
def subsets(self, nums: List[int]) -> List[List[int]]:
self.get_subsets(nums)
return self.result
|
74,031,476
| 74,031,581
|
how to initializes a collection (list) by copying the parameters from a constructor?
|
I've a class PokemonCollection which has a private list which accepts a pair.
Now what I've to do is, when I make an object"collection" of that class PokemonCollection in main() function, I pass some pairs to the constructor, and in the constructor I've to initialize the private list of the class.
PokemonCollection collection({pair<string, size_t>("Pikachu", 25),
pair<string, size_t> ("Raticate", 20), pair<string, size_t>("Raticate", 20),
pair<string, size_t>("Bulbasaur", 1), pair<string, size_t>("Pikachu", 25),
pair<string, size_t>("Diglett", 50)});
this confuses me alot, can someone kindly help me as I'm a beginner,
also I've to print that private list too.
collection.print();
where print is public function of my class.
class definition:
class PokemonCollection{
public:
void print();
private:
list<pair<string, size_t>> pokemons_;
};
where "size_t" is an identifier for the pokemon name.
I have this hint in my assignment for the constructor:
/* constructor
* initializes the collection to by copying the parameter
*/
PokemonCollection(const std::list<std::pair<std::string, size_t>>& pokemons){}
enter image description here
|
how to initializes a collection (list) by copying the parameters from a constructor?
Just like you would initialize any other data member in the member initializer list:
class PokemonCollection{
public:
void print();
PokemonCollection(const std::list<std::pair<std::string,
//---------------------------------------------------VVVVVVVVVVVVVVV--->use member initializer list
size_t>>& pokemons): myList(pokemons)
{
}
private:
list<pair<string, size_t>> myList;
};
Demo
Note that in your given example, you had not given any name to the list data member, so in my example I've named it myList. Then myList is initialized with the function parameter named pokemons using the member initializer list.
|
74,031,918
| 74,035,458
|
C++ Single linked list problem deleting node
|
I have written this code for deleting all nodes which are divisible
by 9.
But when I try to input two consecutive numbers that are
divisible by 9 only of them is deleted.
void deletebydivisable(){
Node *currentNode = head;
while (currentNode!=NULL){
if(currentNode->nextNodeAddress->data % 9 == 0){
Node *todelted = currentNode->nextNodeAddress;
currentNode->nextNodeAddress = todelted->nextNodeAddress;
delete(todelted);
}
currentNode = currentNode->nextNodeAddress;
}
}
|
Your logic is wrong, for several reasons:
you not taking into account that the currentNode->nextNodeAddress field will be NULL when currentNode is pointing at the last node in the list. You should be deleting the currentNode, not its nextNodeAddress.
you are not taking into account the possibility that the 1st node in the list may be divisible by 9, in which case you would have to update the head pointer to point at the 2nd node in the list.
when deleting a node, you are not updating the nextNodeAddress field of the previous node to no longer point at the deleted node but to now point at the next node in the list.
Try this instead:
void deletebydivisable(){
Node *currentNode = head;
Node *previousNode = NULL;
while (currentNode != NULL) {
Node *nextNode = currentNode->nextNodeAddress;
if ((currentNode->data % 9) == 0) {
if (head == currentNode) {
head = nextNode;
}
else {
previousNode->nextNodeAddress = nextNode;
}
delete currentNode;
}
else {
previousNode = currentNode;
}
currentNode = nextNode;
}
}
Which can be simplified slightly by using a pointer-to-pointer to eliminate the innermost if-else block, eg:
void deletebydivisable(){
Node *currentNode = head;
Node **previousNode = &head;
while (currentNode != NULL) {
if ((currentNode->data % 9) == 0) {
*previousNode = currentNode->nextNodeAddress;
delete currentNode;
}
else {
previousNode = &(currentNode->nextNodeAddress);
}
currentNode = *previousNode;
}
}
|
74,032,725
| 74,045,827
|
Yocto SDK Missing Files
|
I have a Yocto project that requires boost. I have added boost and I can confirm that the boost libraries are placed into my SDK.
To create my SDK I run the command
DISTRO=fsl-imx-fb MACHINE=imx6ull14x14evk bitbake mainapplication-dev -c populate_sdk
This builds my image without my main application installed, the main application is run using eclipse.
In my image bitbake file I have the lines
IMAGE_INSTALL_append += " boost"
TOOLCHAIN_TARGET_TASK_append = " boost-staticdev"
I was looking around and found that the second line above should solve my issue. It does not. My application is complaining that:
fatal error: boost/interprocess/managed_shared_memory.hpp: No such file or directory
And it is correct, this file does not exist in my Yocto SDK. I have searched in all files/folders in /opt/fsl-imx-fb/5.10-hardknott/sysroots.
What do I need to add to my bitbake file to get ALL of the required boost header files?
Edit: I changed TOOLCHAIN_TARGET_TASK_append = " boost-staticdev" to TOOLCHAIN_HOST_TASK += "nativesdk-boost-dev". This changes nothing.
Edit: I have attempted to use TOOLCHAIN_HOST_TASK_append = " boost-staticdev", this just gives me an error Couldn't find anything to satisfy 'boost-staticdev'.
Edit: Looking into my main application recipe-sysroot folder I see that managed_shared_memory.hpp exists. This is in the sysroot of my recipe but not in my SDK and I am unsure as to why.
Edit: I am building my dev version of the application. The bitbake file I was adding the DEPENDS += " boost" was not included in the build. I have since moved this to another recipe. The issue remains.
|
I made a mistake in my testing. I would export the new SDK but never installed it. The steps to solve this issue for me are
Add TOOLCHAIN_TARGET_TASK_append = " boost-staticdev" to my recipe bitbake file
Run DISTRO=fsl-imx-fb MACHINE=imx6ull14x14evk bitbake mainapplication-dev -c populate_sdk
cd tmp/deploy/sdk/
./fsl-imx-fb-glibc-x86_64-mainapplication-dev-cortexa7t2hf-neon-imx6ull14x14evk-toolchain-5.10-hardknott.sh
source /opt/fsl-imx-fb/5.10-hardknott/environment-setup-cortexa7t2hf-neon-poky-linux-gnueabi
Run eclipse and build
|
74,033,251
| 74,033,361
|
How to deal with "non-const reference cannot bind to bit-field" error?
|
I encounter this error while using emplace_back to construct a bit field structure in a vector:
struct Foo
{
Foo(uint32_t foo1): foo1(foo1) {}
uint32_t foo1 : 4;
};
int main()
{
vector<Foo> fooVector;
Foo foo = Foo(10);
fooVector.emplace_back(foo.foo1); // Error: non-const reference cannot bind to bit-field
}
I have found that I can avoid this error by either using push_back (but I prefer emplace_back for performance reasons), or by modifying the concerned line like so:
fooVector.emplace_back(uint32_t(foo.foo1)); // Don't raise error
Is it the proper way to deal with it?
Why does this solution work?
|
This is the definition of std::vector::emplace_back:
template< class... Args >
reference emplace_back( Args&&... args );
Args&& in this case gets deduced to uint32_t&, and, as the error says, a bit-field (Foo::foo1) cannot be bound to this type since it is a non-const reference.
In general, you cannot have a reference or a pointer to a bit-field because it has no address. A const reference works because it creates a temporary that is copy initialized with the value of the bit-field, and binds to that temporary instead.
You can indeed do an intermediate cast, like in your example or more explicitly like this:
fooVector.emplace_back(static_cast<uint32_t>(foo.foo1));
However, I am questioning why you want a 8-bit bitfield of a uint32_t instead of just using a uint8_t.
|
74,033,533
| 74,033,671
|
C++ List of member callback functions
|
I am going from C development to C++ on the STM32 platform and simply cant find a suitable solution for my problem.
Please have a look at the simplified example code attached to this post.
#include <iostream>
#include <functional>
#include <list>
using namespace std;
class Pipeline {
public:
std::list<std::function<void(Pipeline*)>> handlers;
//add handler to list --> works fine
void addHandler(std::function<void(Pipeline*)> handler) {
this->handlers.push_front(handler);
}
void ethernetCallback(void) {
//handle received data and notify all callback subscriptions --> still works fine
// this callback function is normally sitting in a child class of Pipeline
int len = handlers.size();
for (auto const &handler : this->handlers) {
handler(this);
}
}
void removeHandler(std::function<void(Pipeline*)> handler) {
// Here starts the problem. I can not use handlers.remove(handler) here to
// unregister the callback function. I understood why I can't do that,
// but I don't know another way of coding the given situation.
}
};
class Engine {
public:
void callback(Pipeline *p) {
// Gets called when new data arrives
cout<<"I've been called.";
}
void assignPipelineToEngine(Pipeline *p) {
p->addHandler(std::bind(&Engine::callback, this, std::placeholders::_1));
}
};
int main()
{
Engine *e = new Engine();
Pipeline *p = new Pipeline();
e->assignPipelineToEngine(p);
// the ethernet callback function would be called by LWIP if new udp data is available
// calling from here for demo purposes only
p->ethernetCallback();
return 0;
}
The idea is that when the class "Pipeline" receives new data over ethernet, it informs all registered callback functions by calling a method. The callback functions are stored in a std::list. Everything works fine till here, but the problem with this approach is that I can't remove the callback functions from the list, which is required for the project.
I know why I can't simply remove the callback function pointers from the list, but I don't know another approach at the moment.
Probably anybody could give me a hint where I could have a look for solving this problem. All resources I've researched don't really show my specific case.
Thank you all in advance for your support! :)
|
Perhaps you could attach an ID to each handler. Very crude variant would just use this address as an ID if you have at most one callback per instance.
#include <functional>
#include <iostream>
#include <list>
using namespace std;
class Pipeline {
public:
using ID_t = void *; // Or use integer-based one...
struct Handler {
std::function<void(Pipeline *)> callback;
ID_t id;
// Not necessary for emplace_front since C++20 due to agreggate ctor
// being considered.
Handler(std::function<void(Pipeline *)> callback, ID_t id)
: callback(std::move(callback)), id(id) {}
};
std::list<Handler> handlers;
// add handler to list --> works fine
void addHandler(std::function<void(Pipeline *)> handler, ID_t id) {
this->handlers.emplace_front(std::move(handler), id);
}
void ethernetCallback(void) {
// handle received data and notify all callback subscriptions --> still
// works fine
// this callback function is normally sitting in a child class of
// Pipeline
int len = handlers.size();
for (auto const &handler : this->handlers) {
handler.callback(this);
}
}
void removeHandler(ID_t id) {
handlers.remove_if([id = id](const Handler &h) { return h.id == id; });
}
};
class Engine {
public:
void callback(Pipeline *p) {
// Gets called when new data arrives
cout << "I've been called.";
}
void assignPipelineToEngine(Pipeline *p) {
//p->addHandler(std::bind(&Engine::callback, this, std::placeholders::_1), this);
//Or with a lambda
p->addHandler([this](Pipeline*p){this->callback(p);},this);
}
void removePipelineFromEngine(Pipeline *p) { p->removeHandler(this); }
};
int main() {
Engine *e = new Engine();
Pipeline *p = new Pipeline();
e->assignPipelineToEngine(p);
// the ethernet callback function would be called by LWIP if new udp data is
// available calling from here for demo purposes only
p->ethernetCallback();
return 0;
}
You might also consider std::map<ID_t,std::function<...>> instead of list, not sure how memory/performance constrained you are.
Obligatory: do not use new, use std::unique_ptr, or better use automatic storage whenever you can. Although in this case a pointer is appropriate for e as you need stable address due to this capture/bind/ID.
std::functions are not comparable as there isn't a good generic way how to define this comparison.
|
74,033,685
| 74,033,793
|
How does this default template struct assignment work?
|
I have been digging into some embedded C++ firmware used by DaveJone's (eevblog) uSupply project
https://gitlab.com/eevblog/usupply-firmware.
There is common pattern of code that I just can't quite wrap my head around what is happening.
For example:
In the file "RegistersRCC.hpp" there is a template struct:
template <std::size_t A>
struct CR : public General::u32_reg<A>
{
using base_t = General::u32_reg<A>;
using base_t::base_t;
//PLL register bits
auto PLLRDY () { return base_t::template Actual<RCC_CR_PLLRDY>(); }
auto PLLON () { return base_t::template Actual<RCC_CR_PLLON>(); }
//PLL Management functions
void EnablePLL() noexcept
{
if ( not PLLON().Get() )
{
PLLON() = true;
while ( not PLLRDY().Get() );
}
}
void DisablePLL() noexcept
{
if ( PLLON().Get() )
{
PLLON() = false;
while ( PLLRDY().Get() );
}
}
//Enable clock security
auto CSSON () { return base_t::template Actual<RCC_CR_CSSON>(); }
//High speed external oscillator bits
auto HSEBYP () { return base_t::template Actual<RCC_CR_HSEBYP>(); }
auto HSERDY () { return base_t::template Actual<RCC_CR_HSERDY>(); }
auto HSEON () { return base_t::template Actual<RCC_CR_HSEON>(); }
//HSE Management functions
void EnableHSE()
{
if ( not HSEON().Get() )
{
HSEON() = true; //Enable the clock
while( not HSERDY().Get() ); //Wait for it to stable
}
}
void DisableHSE()
{
if ( HSEON().Get() )
{
HSEON() = false; //Disable the clock
while( HSERDY().Get() ); //Wait for it to disable
}
}
void ConnectHSE()
{
HSEBYP() = false; //Connect it to system
}
void BypassHSE()
{
HSEBYP() = true; //Disconnect it to system
}
//High speed internal oscillator bits
auto HSICAL () { return base_t::template Actual<RCC_CR_HSICAL>(); }
auto HSITRIM() { return base_t::template Actual<RCC_CR_HSITRIM>(); }
auto HSIRDY () { return base_t::template Actual<RCC_CR_HSIRDY>(); }
auto HSION () { return base_t::template Actual<RCC_CR_HSION>(); }
//HSI Management functions, No calibration provided
// these chips are factory calibrated
void EnableHSI()
{
if (not HSION().Get())
{
HSION() = true;
while (!HSIRDY());
}
}
void DisableHSI()
{
if ( HSION().Get() )
{
HSION() = false;
while (HSIRDY());
}
}
};
This struct exists in the namespace:
namespace Peripherals::RCCGeneral
{
}
Within the same namespace/header file there is this "Default"
CR() -> CR<RCC_BASE + offsetof(RCC_TypeDef, CR)>;
I think this is where my gap in understanding lies. What is happening here? Specifically with the lvalue and arrow operator, and why this is located within the header.
Within the files that utilize the RCCRegisters you see usages like:
CR{}.DisablePLL();
|
This is called class template argument deduction(CTAD) which allows writing deduction guides to the compiler about how to deduce the template arguments from constructor calls.
It is a handy C++17 addition that saves on typing:
std::vector x{1.,2.,3.} //deduces std::vector<double>
C++14 and older requires to explicitly write std::vector<double> which gets tedious and too verbose for some more complex examples.
In this case, the guide
CR() -> CR<RCC_BASE + offsetof(RCC_TypeDef, CR)>;
specifies that the default constructor should deduce A template parameter to RCC_BASE + offsetof(RCC_TypeDef, CR).
The same could have been achieved by simply using a default template argument:
template <std::size_t A = default_value>
struct CR : public General::u32_reg<A>{ ... };
But here comes the catch, offsetof(RCC_TypeDef, CR) is not valid here because at this line, CR doesn't exist yet.
So my assumption is this a fix around this limitation to allow making the default value depend on the class definition itself, quite clever I think.
|
74,033,813
| 74,102,466
|
Refactoring switch statement with template function using the type
|
I am trying to refactor several switch-case statements littered across the code base that have the following structure:
enum Model {
a = 1, b = 2, c = 3, d = 4, e = 5
};
function computeVal(Model m, int param1, int param2, int param3){
Eigen::MatrixXd val, val2;
swtich(m) {
case Model::a:
val = someFunc<classA>(param1, param2, param3);
val2 = someFunc2<classA>(param1, param2, param3);
// some more common logic
case Model::b:
val = someFunc<classB>(param1, param2, param3);
val2 = someFunc2<classB>(param1, param2, param3);
// some more common logic
case Model::c:
val = someFunc<classC>(param1, param2, param3);
val2 = someFunc2<classC>(param1, param2, param3);
// some more common logic
case Model::d:
val = someFunc<classD>(param1, param2, param3);
val2 = someFunc2<classD>(param1, param2, param3);
// some more common logic
default:
val = someFunc<classE>(param1, param2, param3);
val2 = someFunc2<classE>(param1, param2, param3);
// some more common logic
}
}
classA, classB, classC, classD, and classE all inherit from a base class (classBase).
someFunc and someFunc2 initialize the class in the template and use it.
What is a potential way to refactor this? Or should I even be refactoring this?
I was looking at a hashmap / unordered map which would map the Model enum type to the class but I am running into errors.
e.g.:
function computeVal(Model m, int param1, int param2, int param3) {
std::unordered_map<int, classBase*> modelMap = {
{Model::a, classA},
{Model::b, classB},
{Model::c, classC},
...
};
val = someFunc<modelMap[m]>(param1, param2, param3);
val2 = someFunc2<modelMap[m]>(param1, param2, param3);
// some common logic
}
I get the following error: expected primary-expression before '}' token. Which makes sense since it expects a reference to an initialized class when initializing the map. Thats not what I want here though.
Any ideas on how to clean this up?
|
After talking with a co-worker and doing some more research - the consensus was:
The switch statement itself isn't refactorable
The logic inside each case can be refactored into a function as it is exactly the same
e.g.
template<class LL>
function commonLogic(int param1, int param2, int param3){
LL someClass();
val = someFunc<someClass>(&someClass, param1, param2, param3);
val2 = someFunc2<someClass>(&someClass, param1, param2, param3);
// some more common logic
}
function computeVal(Model m, int param1, int param2, int param3){
Eigen::MatrixXd val, val2;
swtich(m) {
case Model::a:
computeVal<classA>(param1, param2, param3);
case Model::b:
computeVal<classB>(param1, param2, param3);
case Model::c:
computeVal<classC>(param1, param2, param3);
case Model::d:
computeVal<classD>(param1, param2, param3);
default:
computeVal<classE>(param1, param2, param3);
}
}
This follows the DRY principle but I can see why this would just be pre-mature refactoring.
|
74,034,601
| 74,035,364
|
What is wrong with the default installation of Qt6 on Ubuntu 22.04
|
I am trying to install Qt (this time 6.4), the online version, on Ubuntu 22.04.
The installation was apparently smooth; I used the default options.
However, when attempting to create a desktop project, I receive the message
/opt/Qt/Tools/CMake/share/cmake-3.23/Modules/CMakeFindDependencyMacro.cmake:47: warning: Found package configuration file: /opt/Qt/6.4.0/gcc_64/lib/cmake/Qt6Gui/Qt6GuiConfig.cmake but it set Qt6Gui_FOUND to FALSE so package "Qt6Gui" is considered to be NOT FOUND. Reason given by package: Qt6Gui could not be found because dependency WrapOpenGL could not be found.
Did I wrong something? How can I continue?
|
Install the OpenGL development packages like the following.
$ sudo apt install libglx-dev
|
74,034,964
| 74,035,008
|
C++ can't return nth element of string only nth element onwards
|
I am trying to get the nth element of a string, which I know generally works with a method such as
char current_letter = input_string[j];
However when using the code below I get an output of
0 current_letter: ABC
1 current_letter: BC
2 current_letter: C
ABC BC 9ekNc5GlorW1PkaBQlYCuXMBljdSQClygl00XwKxoVzYsf8FrCs3qUZV85gHJHsl
where the 4th line is just the coded_string variable being printed. This indicates that the std::string current_letter = &input_string[j]; way of trying to get the nth element of the string is not actually returning the nth element but rather everything in the string from the specified index onward.
When I use char instead of std::string to define the current_letter variable (and correspondingly change it from std::string to char in the previous lines defining the std::map and the .insert() method to match, I get an red error line under the .find() method, saying:
no instance of overloaded function "std::map<_Key, _Tp, _Compare, _Alloc>::find [with _Key=std::string, _Tp=std::string, _Compare=std::less<std::string>, _Alloc=std::allocator<std::pair<const std::string, std::string>>]" matches the argument list
I would also like to generally be able to use std::string for both the key and value in the std::map for future purposes, so how would I retrieve the nth letter of the string without any other element in the string being returned?
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
void set_seed_n_shuffle(std::vector<std::string> &array, unsigned seed){
std::srand(seed);
random_shuffle(std::begin(array), std::end(array));
}
std::string en_to_ch(std::vector<std::string> list, std::string input_string){
// list = ch_list, input_string = string to be converted
std::vector<std::string> en_list = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
std::map<std::string, std::string> en_ch_dict;
for (int i=0; i<en_list.size(); i++){
en_ch_dict.insert(std::pair<std::string, std::string>(en_list[i], list[i]));
//en_ch_dict.emplace(en_list[i], list[i]);
}
std::string coded_string;
for (int j=0; j<input_string.size(); j++){
std::string current_letter = &input_string[j];
std::cout << j << " current_letter: " << current_letter << "\n";
if (en_ch_dict.find(current_letter) == en_ch_dict.end()) {
coded_string += current_letter + " "; // not found
} else {
coded_string += en_ch_dict.find(current_letter)->second + " "; // found
}
}
return coded_string;
}
int main(){
std::vector<std::string> ch_list = {"randomcharacters1", "randomcharacters2","randomcharacters3","randomcharacters4","randomcharacters5",}
set_seed_n_shuffle(ch_list, 156);
std::string string_input = "ABC";
std::string new_string = en_to_ch(ch_list, string_input);
std::cout << new_string << "\n";
}
|
std::string current_letter = &input_string[j];
input_string[j] is a single character, not a null-terminated string. If you construct a std::string with a char* pointer to a character, it will read from that character onward until it encounters a null terminator '\0', which doesn't exist in this case, so the result is undefined behavior.
|
74,035,009
| 74,035,103
|
Why is cin apparently skipping input in this C++ code?
|
I have a simple C++ test code. The way it should work is for a user to enter a sequence of integers through cin, followed by some character to terminate the cin input, then the code should output the integers. Next, the user should enter an integer other than zero to input another sequence. If that's what the user does, the process begins again, otherwise the code exits.
For example, I am expecting input
1 2 3 4 5 a
to result in output
1, 2, 3, 4, 5
followed by an opportunity to input the signal for another sequence. What happens instead is that this output gets repeated ad infinitum (or until ctrl-c):
1, 2, 3, 4, 5
1, 2, 3, 4, 5
1, 2, 3, 4, 5
etc.
What is going on with cin? I know about getline(), and could probably solve the problem with it. But, regardless, I think there is something simple and fundamental that I need to understand about cin. Here's the code:
#include <iostream>
#include <vector>
int main(int argc, char **argv) {
std::vector<int> data;
int goahead = 1;
int nextval;
while (goahead) {
while (std::cin >> nextval) {
data.push_back(nextval);
}
for (int i=0; i<data.size(); i++) {
if (i>0) std::cout <<", ";
std::cout << data[i];
}
std::cout << std::endl;
std::cin >> goahead;
}
}
|
Using cin.clear() and cin.ignore() can help:
#include <iostream>
#include <vector>
#include <limits>
int main(int argc, char **argv) {
std::vector<int> data;
int goahead = 1;
int nextval;
while (goahead) {
data.clear();
while (std::cin >> nextval) {
data.push_back(nextval);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (int i=0; i<data.size(); i++) {
if (i>0) std::cout <<", ";
std::cout << data[i];
}
std::cout << std::endl;
std::cin >> goahead;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
Best regards.
|
74,035,109
| 74,035,143
|
Can you Iterate through member variables using a for loop, if a vector is of a class
|
for (std::string& request : recData.getReqest()) //recData is a vector
{
}
recData is a vector which stores objects of an X type, X class has a member variable which is "std::string request;" and as I iterate through the for loop I want all objects within recData to have their request member variable processed. Is this possible?
|
It's certainly possible, by changing the for loop and using one extra statement:
for (auto &r: recData)
{
std::string &request = r.request;
// Here's your request, for your loop.
}
|
74,035,291
| 74,063,401
|
CMake Errors including IXWebSocket in Ubuntu 22 (works on MacOS 12.6)
|
Context:
I have a cpp program built on MacOS 12.6 with the following CMakeLists.txt file.
cmake_minimum_required(VERSION 3.19.0)
project(cpp-test VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
add_executable(cpp-test main.cpp)
add_library(test-helpers main.cpp ${PROJECT_SOURCE_DIR}/helpers.hpp)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
# this is super important in order for cmake to include the vcpkg search/lib paths!
set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" CACHE STRING "")
# find library and its headers
find_path(IXWEBSOCKET_INCLUDE_DIR ixwebsocket/IXWebSocket.h)
find_library(IXWEBSOCKET_LIBRARY ixwebsocket)
find_package(OpenSSL REQUIRED)
find_package(CURL REQUIRED)
# include headers
include_directories(${IXWEBSOCKET_INCLUDE_DIR} ${CURL_INCLUDE_DIR})
# Cmake will automatically fail the generation if the lib was not found, i.e is set to NOTFOUND
target_link_libraries(
${PROJECT_NAME} PRIVATE
${IXWEBSOCKET_LIBRARY}
OpenSSL::SSL
OpenSSL::Crypto
${CURL_LIBRARIES}
"-framework Foundation"
"-framework Security"
"-lz"
)
This compiles just fine. However, when I try to pull it into my Ubuntu VM and try to build it /build> cmake .., I get the following errors
CMake Error in CMakeLists.txt:
Found relative path while evaluating include directories of "cpp-test":
"IXWEBSOCKET_INCLUDE_DIR-NOTFOUND"
CMake Error in CMakeLists.txt:
Found relative path while evaluating include directories of
"test-helpers":
"IXWEBSOCKET_INCLUDE_DIR-NOTFOUND"
-- Generating done
What I have tried...
I have installed vcpkg and created my symlink ln -s /path/to/vcpkg /usr/local/bin/vcpkg.
I have installed ixwebsocket via vcpkg install ixwebsocket, but it seems that the CMAKE_TOOLCHAIN_FILE is not being parsed correctly.
I'm a bit lost, any help would be appreciated
|
This is not a great answer to the issue, but I ended up resolving it by building ixwebsocket via CMake instead.
It seems that vcpkg was not compatible with the linux distro in my VM.
|
74,036,132
| 74,036,442
|
Problem converting member function pointer to std::function with CRTP
|
I am trying to pass a bound member function as an std::function while hiding the std::bind_front invocation in a base class. Minimal example:
#include <functional>
static void runIt(std::function<void()> f) { f(); }
template<typename T>
struct Base {
using PFn = void (T::*)();
void run(PFn fun) { runIt(std::bind_front(fun, this)); }
};
struct Derived : Base<Derived> {
void main() { run(&Derived::func); }
void func() {}
};
Unfortunately, the compiler does not like it:
static void runIt(std::function<void()> f)
No matching function for call to 'runIt' clang(ovl_no_viable_function_in_call)
test.cpp(12, 19): In instantiation of member function 'Base<Derived>::run' requested here
test.cpp(3, 13): Candidate function not viable: no known conversion from 'std::__perfect_forward_impl<std::__bind_front_op, std::__tuple_types<void (Derived::*)(), Base<Derived> *>, std::__tuple_indices<0, 1>>' to 'std::function<void ()>' for 1st argument
What am I missing?
|
You can't std::invoke(fun, this) since this is of type Base<Derived>* and the function pointer is of type void (Derived::*)() (And Derived is not a base of Base<Derived>, but the other way around).
Either upcast the pointer to member function or the pointer to the object. Preferably the object pointer:
runIt(std::bind_front(fun, static_cast<T*>(this)));
|
74,036,695
| 74,038,011
|
What is the working mechanism under the hood for ReadDirectoryChangesW()?
|
I understand ReadDirectoryChangesW can be implemented synchronously or asynchronously. The general consideration being asynchronous is good for slow I/O operations, vice-versa.
Currently, I am trying to do monitoring and get the paths of all new files created on the drive. This would involve watching many subdirectories and I am unsure what exactly are the operations carried out in this function and if asynchronous is good for this use case.
It would be good if there's somewhere to read about its working mechanism. I have read the documentation but it only states how to use it.
Thanks.
|
ReadDirectoryChanges is implemented by issuing IRP_MJ_DIRECTORY_CONTROL to the appropriate file system driver, with a minor function code of IRP_MN_NOTIFY_CHANGE_DIRECTORY.
At the file system level the implementation will likely always be asynchronous unless change data is already available to return. The general synchronous case is likely instead handled by ReadDirectoryChangesW, waiting for the dispatched I/O request packet to complete on behalf of the user.
Whether you choose to call ReadDirectoryChangesW synchronously or asynchronously should depend on whether you have any useful work you could be doing while waiting for a response. If no then there is no point to dealing with the trouble asynchronous I/O presents. If yes (even if just updating UI) then the asynchronous route will very likely be preferable. It might also be useful to instead spawn a worker thread and have that thread issue the call, very often mixing asynchronous I/O code with UI becomes a tangled mess. A separate worker thread can allow each to deal with just one or the other.
|
74,036,969
| 74,037,410
|
Lazy type constraint (implement Rust `Default` trait in c++)
|
In Rust you can implement traits for structs and each implementation has own type constraint. (for who may does not familiar with rust, you can consider a "trait" as a "base class" and "implementation" as "inheritance").
look at this example:
// our struct has an item of type mutable T pointer
struct Box<T> {
inner: mut* T
}
// implementing `Default` trait for
// box. in this implementation, type
// constraint is: `T: Default`.
// it means the inner type also must
// implements Default.
impl <T: Default> for Box<T> {
fn default() -> Self {
return Box::new(T::default());
}
}
the note in this example is there is no need T: Default to be applied until you use Box::default() in your code.
well it is possible to do like this in cpp? I'm familiar with how we can constraint types in cpp and this is not my problem. I want to know is there some way to lazy type constrain (maybe a better description) in cpp when I define a class?
I know it is possible with if constexpr or static_assert. but this way is not beautiful.
I want a template or concept solution ( I mean what applies to function signature in fact) if possible.
thank you for any guidance.
|
I am not sure I follow exactly what you want (I don't really know Rust), but you can constrain member functions individually:
template<typename T>
concept Default = requires {
{ T::default_() } -> std::same_as<T>;
};
template<typename T>
struct Box {
static Box default_()
requires Default<T> {
//...
}
//...
};
Now Box itself has no requirements on T, but to use Box::default() will require T to satisfy the Default concept.
However, it would basically work without the constraint as well. If Box<T>::default calls T::default() and the latter is not well-formed the code will fail to compile if and only if Box<T>::default is actually used in a way that requires it to be defined (i.e. called or pointer/reference to it taken). But without the requires clause e.g. Default<Box<T>> would always report true.
And of course in C++ we would use the default constructor instead of a static member function called default to construct the object. The same approach applies to constructors though and there is already the concept std::default_initializable for that in the standard library.
As far as I understand, Rust traits do not really overlap fully with either C++ (abstract) base classes nor concepts though. The approach above will not allow for runtime polymorphism on types satisfying Default. For that an abstract base class with the interface functions as non-static pure virtual member functions should be used instead.
However, the trait Default only imposes a requirement on a static member function, so that it shouldn't be relevant to runtime polymorphism, but only compile-time properties of the type, which is what concepts are for, although in contrast to Rust you don't declare a type to implement a trait. Instead the concept describes requirements which a type needs to satisfy to satisfy the concept.
|
74,037,170
| 74,037,254
|
Empty characters in C/ C++
|
Are there any empty characters available in C or C++? And by empty character I mean, no white-space, no null character, just to skip that place of the particular character. I don't want to replace that character with the above mentioned ones, but to just disappear that character and it's place.
For example, I have a string s = "thisIsAma@zing$"
and I want to skip those '@' and '$' without creating another string or utilising more space, so is there any way to do that? If so, then please tell.
Thank You
|
The actual charset in use is not defined by the C++ standard itself, but by the particular implementation. That being said, I'm not aware of anything like that in common text encodings, and ultimately it's not clear how would that work: say that × was such a character: thisIsAma×zing$ and thisIsAmazing$ would still be two different character sequences, even if onscreen rendering would be the same, meaning that they would not really be the same.
Anyhow, in an std::string you don't have to create a new one to remove unwanted characters: std::string is modifiable, and algorithms such as std::remove_if works inplace and without reallocing.
|
74,037,422
| 74,038,021
|
C++ class instances which reference to each other
|
It is possible to make circular references from class A to class B and vica-versa using forward declarations
class class_a;
class class_b;
class class_a {
class_a(class_b& arg) : ref_to_b(arg){}; // constructor
class_b& ref_to_b;
};
class class_b {
class_b(class_a& arg) : ref_to_a(arg){}; // constructor
class_a& ref_to_a;
};
How to create instances of such classes?
|
At global scope you can declare the classes before initializing them to obtain references:
extern class_a a;
extern class_b b;
class_a a{b};
class_b b{a};
And now that we have those we can use placement new to create more such pairs:
auto a2 = new class_a(a);
auto b2 = new class_b{a2};
a2 = new(a2) class_a{b2};
Now a2 and b2 point to another pair of such class objects.
However, I doubt that this is useful in practice.
|
74,037,589
| 74,037,677
|
Wrong result when using double data type
|
The following code gets wrong result when using double data type for the result y, why is this? How do I get the correct one when using double?
You can run this code using https://godbolt.org/z/hYvxjW8xT
#include <cstdio>
#include <iostream>
int main()
{
double MYR = 153.6;
double MIYR = -153.6;
double po_size = 0.1;
printf("MYR: %.4f\n", MYR);
printf("MIYR: %.4f\n", MIYR);
printf("po_size: %.4f\n", po_size);
double y =(MYR - MIYR) / po_size; // should be 3072
printf("double res: %d\n", int(y)); // 3071 wrong
float x = (MYR - MIYR) / po_size; // should be 3072
printf("float res: %d\n", int(x)); // correct
}
|
Floating point math is an approximation. So you get a number that is close to 3072 (3071.999 for example) and then you truncate it and get 3071. Instead, round the number:
printf("double res: %.0f\n", std::round(y));
And you don't even need the explicit std::round call, since %.0f format specifier implies the rounding:
printf("double res: %.0f\n", y);
This also avoids possible overflow bugs due to the conversion.
|
74,038,003
| 74,039,702
|
Convert unsigned char* to std::shared_ptr<std::vector<unsigned char>>
|
I'm trying to change a variable of type unsigned char* to std::shared_ptr<std::vector<unsigned char>> for memory management. The thing is, this code was written by a coworker who left several years ago, and I'm not so sure how to manage the change in some methods since I'm not familiar with them. Currently, I'm stuck with this function to get the buffer of an image from the class BaseImage.
const unsigned char* BaseImage::getConstBuffer() const
{
if(m_bufferSize == 0) return 0;
else return m_bufferData + m_headerSize;
}
With:
unsigned int m_bufferSize;
unsigned short m_headerSize;
unsigned char* m_bufferData = new unsigned char[(unsigned) m_headerSize + m_bufferSize];
I'm not sure to understand why we are adding m_bufferData to m_headerSize, and what would be the proper way to change it after the conversion. Does anyone have an idea?
|
If you really need the callers of this function to share ownership of the return value, then you can use std::shared_ptr<unsigned char[]>. Much more likely, callers only get to observe the pointed to data, and don't need to own it. In that case, you can use std::vector<unsigned char> as the data member, and return a span type (std::span is C++20, gsl::span requires C++14 but could be adapted to C++11)
class BaseImage
{
unsigned short m_headerSize;
std::vector<unsigned char> m_bufferData;
public:
BaseImage(size_t bufferSize, unsigned short headerSize) : m_headerSize(headerSize), m_bufferData(bufferSize + headerSize) {}
span<const unsigned char> BaseImage::getConstBuffer() const
{
return { m_bufferData.data() + m_headerSize, m_bufferData.size() - m_headerSize };
}
};
|
74,038,077
| 74,038,125
|
Accessing structure array attributes without using pointers
|
Is it possible to make a structure array variable and access structure attributes without using pointers? I tried doing it without a pointer and it is giving me an error.
#include<iostream>
#include<string>
using namespace std;
struct Student
{
string name;
string rollNo;
float GPA;
string department;
char section;
};
int main()
{
Student s1[10];
for (int i = 0; i < 10; i++)
{
cout << i + 1 << "Enter your name: ";
cin >> s1.name;
cout << "Enter roll num: ";
cin >> s1.rollNo;
}
return 0;
}
I am accessing attributes by placing a dot s1.rollNo gives an error.
|
s1 is an array of structs and needs to be accessed with an index: s1[i].name etc.
|
74,038,118
| 74,038,267
|
Unable to call my operator<T t>() if it doesn't receives arguments
|
I'm trying to create a State class that will be used like an enum.
template <class ApplicationType>
class State
{
public:
template<class T>
requires requires(){ std::is_base_of<ApplicationType, T>::value; }
unsigned int operator()() //broken operator
{
static unsigned int localCounter = counter++;
return localCounter;
}
template<class T>
requires requires(){ std::is_base_of<ApplicationType, T>::value; }
unsigned int operator()(T t) //working operator
{
static unsigned int localCounter = counter++;
return localCounter;
}
private:
unsigned int counter = 0;
};
My problem is that when I call the first operator State::operator()() the code doesn't compile, but when I call the second one State::operator()(T t) everything works fine.
class Base{};
class Derived: Base{};
int main()
{
State<Base> myState;
Derived d;
myState<Derived>(); // Error
myState(d); // OK
return 0;
}
Error message:
expected primary-expression before '>' token
expected primary-expression before ')' token
PS: I'm using G++ with -std=c++20
|
Just use the explicit notation for the call:
myState.operator()<Derived>();
|
74,038,168
| 74,038,227
|
How to draw 1 isosceles triangle with vertex facing left side of screen using C++
|
I am a student and am looking for a way to solve a problem online with content like the image below
Please solve it for me with C++ code
|
If you want to solve such a problem, then you need split the big problem in to smaller problems. Then the solution is easier.
So, let's first strip of the '*'. They are always starting a row and ending it. This is not needed in the beginning.
Next. You see some sequences, like
1
121
12321
1234321
123454321
1234321
12321
121
1
You see that the digits will be incremented by one until we hit the maximum value for this row and then decremented again until they are 1.
The decreasing numbers are also not important at the moment, because, it is simple to decrement them from the maximum number.
Stripping of the decremented numbers, we will get:
1
12
123
1234
12345
1234
123
12
1
And this looks like a triangle and can be generated mathematically by a typical triangular function.
We want to calculate the maximum number in a row from the row value istelf. Applying the algorithm from the triangular function, will always result in a formular with the "abs"-function. So taking the absolute value.
We will then get something like the below:
Row 5-abs(Row-5)
0 0
1 1
2 2
3 3
4 4
5 5
6 4
7 3
8 2
9 1
10 0
We see also that the number of output lines is double the input value.
We can then do a simple increment/decrement loop, to show the digits according to the before shown values.
Then we add a little bit the output of the "". Please note, that the "closing" star "" at the end of the line is not needed in the first and last row.
Having explained all the above, we can now start writing the code. There are really many many potential solutions, and I just show you one of them as an example.
Please have a look and implement your own solution.
#include <iostream>
#include <cmath>
int main() {
// Tell user what to do
std::cout << "\nPlease add number for the triangle: ";
// Get the maximum extent from the user. Limit values
int maxN{};
if ((std::cin >> maxN) and (maxN >= 0) and (maxN < 10)) {
// Now we want to print row by row
for (int row=0; row <= (maxN * 2); ++row) {
// Calculate the maximum value that should be shown in this row
int maxValueForRow = maxN - std::abs(row-maxN);
// You may uncomment the following line for getting more info
//std::cout << maxValueForRow << '\t';
// Always print at least on beginning star
std::cout << '*';
// Now we want to print the digits. Start counting with 0
int i = 0;
// Print and increment digits
for (i = 0; i < maxValueForRow; ++i) std::cout << i+1;
// And now decrement the digits and print them
for (i=i-2; i >= 0; --i) std::cout << i+1;
// Show closing star only, if we are not in first or last row
if (maxValueForRow > 0) std::cout << '*';
// Start a new line
std::cout << '\n';
}
}
else std::cerr << "\n\nError: Invalid input\n";
}
|
74,038,339
| 74,038,588
|
(C++) How to imagine working of nested loops?
|
I have no idea what's going on how to imagine that, one more thing like in 3rd for loop there's a condition that k<j but its upper loop j is set to 0 and i is also 0 then as I think k=0 if this is right than 0<0 how's that can be valid????
void printing_subarrays(int *arr,int n){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
for(int k=i; k<j; k++){
cout<<arr[k]<<", ";
}cout<<endl;
}cout<<endl;
}
}
|
I don't think it makes much sense for us to explain what's happening, you need to see it for yourself.
Therefore I've added some output lines, which will show you how the values of the variables i, j and k evolve through the loops:
for(int i=0; i<n; i++){
cout<<"i=["<<i<<"]"<<endl;
for(int j=0; j<n; j++){
cout<<"i=["<<i<<"], j=["<<j<<"]"<<endl;
for(int k=i; k<j; k++){
cout<<"i=["<<i<<"], j=["<<j<<"], k=["<<k<<"]"<<endl;
cout<<arr[k]<<", ";
}
cout<<endl;
}
cout<<endl;
}
|
74,039,493
| 74,039,768
|
Truncate on first non-printable character
|
I am trying to use std::regex to truncate on the first non-printable character.
I tried
std::string ExtractPrintableString(const std::string& message) {
std::regex trim_nonprintable_regex("([[:print:]]+).*")
std::smatch matched_message;
std::regex_search(message, matched_message, trim_nonprintable_regex);
return matched_message[1].str()
}
But I am not getting the expected result.
Ex:
If I pass "\r\t\r\t\r\t\ruessw7cr9jhmdiy" it should return empty string.
If I pass "asd\r\tdfvdfv" then it should return asd only.
|
You need to 1) match at the start of string by adding a ^ at the start and 2) by replacing the ([[:print:]]+).* pattern with just [[:print:]]*:
std::string ExtractPrintableString(const std::string& message) {
std::regex trim_nonprintable_regex("^[[:print:]]*");
std::smatch matched_message;
std::regex_search(message, matched_message, trim_nonprintable_regex);
return matched_message[0].str();
}
Note that in this case, there is no capturing group, so you need to return matched_message[0].str().
See the online C++ demo.
Pattern details:
^ - start of string
[[:print:]]* - zero or more printable chars (that are only matched at the start of string due to ^).
|
74,039,907
| 74,040,149
|
What are the differences between char** and char*& in CPP
|
For an assignment I came across this question.
What is the result of the statement following the definitions given below?
char c='a';
char *pc=&c;
char *&rc=pc ;
(*rc)++;
after printing all the different variables it shows that now variable c stores 'b'.
I didn't understand why.
Can anyone please explain?
|
Both char** (pointer-to-pointer) and char*& (reference-to-pointer) are second level abstractions of a value. (There's no pointer-to-reference type btw.)
The differences are really the same as they are for regular pointers vs. references: nullable vs. non-nullable etc. See here for more: https://www.geeksforgeeks.org/pointers-vs-references-cpp/
In your example, incrementing *rc does the same as would with using *pc.
Note that you don't need a symbol for accessing a references value as you would with * when using a pointer.
Just for fun: Try char** ppc = &pc. Can you tell what this does ?
|
74,040,122
| 74,045,096
|
remove a pair from a list of pairs c++
|
I'm doing this all in classes, I've a simple question, I've a private list of pairs:
std::list<std::pair<std::string, size_t>> pokemons_;
to which I've passed certain values as:
{("Pikachu", 25),
("Raticate", 20),
("Raticate", 20),
("Bulbasaur", 1),
("Pikachu", 25),
("Diglett", 50)};
Now I want to remove a pair by calling a public remove function of my class.
bool PokemonCollection::Remove(const std::string& name, size_t id){};
what I don't understand is how to compare the string and id value while calling the remove function:
collection.remove("Raticate", 20);
"collection Is an object of my class"
what I've implemented till now by the help of other forums and reading internet and cpp reference is:
bool PokemonCollection::Remove(const std::string& name, size_t id){
bool found;
string x;
size_t y;
for (auto currentPair : pokemons_){
pair<string, size_t> currentpair = currentPair;
x=currentpair.first;
y=currentpair.second;
pokemons_.erase(pokemons_.begin()+i)
for (int i=0; i<pokemons_.size(); i++){
if (pokemons_[i].first == x && pokemons_[i].second == y){
// pokemons_.erase(pokemons_.begin() +i);
cout<<"FOUND!!!!!!!!!!!!!!!";
found = true;
return true;
}else{
found = false;
}
}
}
return found;
}
but this remove function of mine gives some errors I don't really understand.
also it gives so much errors on the commented line where I used erase function. I just need some help to compare the string and id and remove that pair from original private list of my class.
MY FUNCTION
```bool PokemonCollection::Remove(const std::string& name, size_t id){
bool found;
//string x;
//size_t y;
pokemons_.remove_if([&](std::pair<std::string, size_t>& p){return found = true and p.first==name and p.second==id;});
if(found==true){
return true;
}else{
found = false;
}
return found;
}```
|
It can be done even simpler than Armin Montigny's solution. std::pair<> comes with comparison operators, so you don't need a custom function to check if an element of the list is equal to a given pair:
void remove(const std::string& s, size_t i) {
poke.remove({s, i});
}
Since C++20, std::list's remove() and remove_if() return a count of the number of elements removed. If you need to be compatible with earlier versions, you could always check the result of poke.size() before and after the call to remove() to see if the size of the list has changed.
|
74,040,167
| 74,040,426
|
How can I set up debugging C++ programs with command-line arguments in VS Code?
|
I am having a problem setting up my debugger in VSCode for C++. I wrote some code, then ran into some errors while running it so I decided to debug. I think thats when VSCode created the task.json file. Then I realized I wanted to use command line arguments and google/stackoverflow said to create a launch.json file which I did. It was empty so I pressed the add configuration button and got this.
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "enter program name, for example ${workspaceFolder}/a.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "/path/to/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
]
}
]
}
Now I tried to fill the placeholders but I can't do them without getting tons of errors after errors. Could someone please post an example of a working launch.json and how the file paths are supposed to work?
My main goal is to debug my code while using command line arguments.
|
Here is a sample from a project I currently use:
{
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch Test",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/build_amd64/bin/tester_config",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}/build_amd64",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": []
}
]
}
If you post your launch.json with the filled in values then I might be able to tell you exactly what's wrong, because assuming you filled out everything correctly, you should be working.
|
74,040,516
| 74,044,374
|
QDialogButtonBox::accepted() is protected
|
I want to write my custom input dialog. I wrote following lines to handle click on OK/Cancel:
connect(buttonBox, &QDialogButtonBox::accepted,this, &MyCustomDialog::accept);
I got this error on compile:
/usr/include/qt4/QtGui/qdialogbuttonbox.h:147:10: error: 'void QDialogButtonBox::accepted()' is protected
void accepted();
There isn't any public signal in QDialogButtonBox.
|
This is not about QDialogButtonBox. It is about your Qt version. You are using Qt5 syntax for singal-slot while you have Qt4. Use this:
connect(buttonBox, SIGNAL(accepted()),this, SLOT(accept()));
accepted is a Q_SIGNALS which is protected in Qt4, so you can't use that syntax.
|
74,040,896
| 74,048,203
|
Opening file only once before writing to it in an async loop using boost::asio
|
Based on one of the previous questions I posted, I have implemented a separate async thread that dumps the contents of a container every 10 seconds using the steady_timer from the boost::asio library. It looks as follows:
m_outfile.open("numbers.bin", std::ios::out | std::ios::trunc | std::ios::binary);
for (auto val : number_container) {
m_outfile.write(reinterpret_cast<const char*>(&val), sizeof(int));
if (m_outfile.bad()) {
throw std::runtime_error("Error in writing to numbers.bin");
}
}
m_timer.expires_at(m_timer.expiry() + boost::asio::chrono::seconds(NUM_SECONDS_DUMP));
m_timer.async_wait(boost::bind(&Data_dump::dump, this));
This is just part of the code but you can see that I open a file, loop through a container and write the contents into the file.
The problem here is with the very first line - it should only be used once or else the code crashes after 10 seconds when I enter this code again. I have put a while loop around the first line that only runs once like so:
while (testing == 0) {
m_outfile.open("numbers.bin", std::ios::out | std::ios::trunc | std::ios::binary);
testing++;
}
This works fine as testing is a global variable, but I am not sure about declaring a global variable and having to check this while loop all the time even though it will never enter it. Just looking for a better solution to this issue!
|
What you're looking for is a class member. It's not global, each object instance will have its own copy.
Because it's also not local to the function, it will stay around across member function calls on the same object.
I'd argue that you don't need a flag, because you can ask the stream whether it was already open:
if (!m_outfile.is_open())
m_outfile.open(filename, std::ios::binary);
Since you want exceptions on error, consider enabling them on the file stream:
m_outfile.exceptions(std::ios::failbit | std::ios::badbit);
Consider using the actual size of val, instead of duplicating the assumed type (int).
for (auto val : number_container) {
m_outfile.write(reinterpret_cast<const char*>(&val),
sizeof(val));
}
(aside: If number_container is contiguous, you can more efficiently write that as:
auto span = as_bytes(std::span(number_container));
m_outfile.write(reinterpret_cast<char const*>(span.data()), span.size());
/aside)
Here's a live demo On Coliru
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <fstream>
#include <iostream>
#include <span>
using namespace std::chrono_literals;
static constexpr auto DUMP_INTERVAL = 1s;
struct Data_dump {
Data_dump() { //
m_outfile.exceptions(std::ios::failbit | std::ios::badbit);
}
void foo() {
try {
if (!m_outfile.is_open())
m_outfile.open(m_filename, std::ios::binary);
//for (auto val : number_container) {
//m_outfile.write(reinterpret_cast<const char*>(&val),
//sizeof(val));
//}
auto span = as_bytes(std::span(number_container));
m_outfile.write(reinterpret_cast<char const*>(span.data()), span.size());
m_outfile.flush();
m_timer.expires_at(m_timer.expiry() + DUMP_INTERVAL);
m_timer.async_wait(boost::bind(&Data_dump::dump, this, boost::placeholders::_1));
std::cerr << "Expiry: " << (m_timer.expiry() - std::chrono::steady_clock::now())/1ms << "ms\n";
} catch (std::exception const& e) {
throw std::runtime_error("Error in writing to " + m_filename);
}
}
void run() {
ioc.run_for(10s); // for COLIRU
}
private:
void dump(boost::system::error_code ec) {
// don't use rand in production code!
std::cerr << "Dump (" << ec.message() << ")" << std::endl;
generate(begin(number_container), end(number_container), std::rand);
foo();
}
std::string const m_filename = "numbers.bin";
boost::asio::io_context ioc;
boost::asio::steady_timer m_timer{ioc, 1s};
std::ofstream m_outfile;
std::vector<int> number_container{1, 2, 3};
};
int main() {
boost::asio::io_context ioc;
Data_dump dd;
dd.foo();
dd.run();
}
Showing the timings:
BONUS
In your case, it looks like you might not actually need async IO (you're not using it in the code shown), so maybe just write it like:
void foo(std::string const& filename) {
std::ofstream ofs;
ofs.exceptions(std::ios::failbit | std::ios::badbit);
ofs.open(filename, std::ios::binary);
auto start = std::chrono::steady_clock::now();
for (auto now = start; now <= start + 10s; now += DUMP_INTERVAL) {
/*
*for (auto val : data)
* ofs.write(reinterpret_cast<const char*>(&val), sizeof(val));
*/
auto span = as_bytes(std::span(data));
ofs.write(reinterpret_cast<char const*>(span.data()), span.size());
ofs.flush();
std::this_thread::sleep_until(now + 1s);
}
}
Now, perhaps add a thread to update the number container (be sure to add synchronization e.g. using a lock, or atomic exchange etc.)
|
74,041,078
| 74,041,179
|
Function pointers initialized by lambda and their scope
|
I have written the following code, which shall do element-wise transformation on arrays of the type x=a op b. T is numeric type (float, double, int, uint8_t, uint32_t, ...)
template <typename T>
void processFrame(Args ARG, T* a_array, T* b_array, T* x_array, uint32_t elmcount)
{
if(ARG.multiply)
{
std::transform(A_array, A_array + elmcount, B_array, x_array, std::multiplies());
} else if(ARG.divide)
{
std::transform(A_array, A_array + elmcount, B_array, x_array, std::divides());
} else if(ARG.min)
{
std::transform(A_array, A_array + elmcount, B_array, x_array, [](T i, T j) {return std::min(i, j);});
}
}
The problem with this code is that I need to repeat the std::transform line multiple times but only transform type really changes. After googling I ended up with using pointer to function populated by lambda.
template <typename T>
using Operator = T (*)(const T&, const T&);
template <typename T>
void processFrame(Args ARG, T* A_array, T* B_array, T* x_array, uint32_t elmcount)
{
Operator<T> op = nullptr;
if(ARG.multiply)
{
op = [](const T &i, const T &j) { return T(i * j); };
} else if(ARG.divide)
{
op = [](const T &i, const T &j) { return T(i / j); };
} else if(ARG.inverseDivide)
{
op = [](const T &i, const T &j) { return T(j / i); };
} else if(ARG.add)
{
op = [](const T &i, const T &j) { return T(i + j); };
} else if(ARG.subtract)
{
op = [](const T &i, const T &j) { return T(i - j); };
} else if(ARG.max)
{
op = [](const T &i, const T &j) { return std::max(i, j); };
} else if(ARG.min)
{
op = [](const T &i, const T &j) { return std::min(i, j); };
}
std::transform(A_array, A_array + elmcount, B_array, x_array, op);
}
Now it is working but I am not sure if I don't use unallocated memory. As op is formally pointer and I initialize it by lambda , shall not that lambda go out of scope at the end of each if block? Is my std::transfrom not using pointer to non existing object?
|
The code is safe.
Function pointers are valid throughout the length of the program (with exception of dlopen stuff...).
Lambdas without capture are implicitly convertible to function pointers through magic. Each lambda expression creates a distinct type and returns a new object of that type.
Yes, the object goes out of scope, but the type of course doesn't, neither does its static methods which will be the function stored inside the pointer.
|
74,041,539
| 74,093,441
|
Disabling USB storage device in windows during transferring data to PC
|
I had used the following code to disable the USB drive in Windows but it does not work while transferring the data from USB to PC. I am requesting suggestion from you for any other alternative to disable the device during this scenario.
if (SetupDiSetClassInstallParams(m_hDevInfo, &spdd, (SP_CLASSINSTALL_HEADER*)&spPropChangeParams, sizeof(SP_PROPCHANGE_PARAMS)) == FALSE)
{
printf("Not able to manage the status of the device.SetupDiSetClassInstallParams Failed at ErrorCode - %ld\n", GetLastError());
writeLog("err", "Not able to manage the status of the device.SetupDiSetClassInstallParams Failed");
}
else if (!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, m_hDevInfo, &spdd))
{
DWORD error = GetLastError();
printf("Not able to manage the status of the device.SetupDiCallClassInstaller API Failed at Errorcode - %ld\n", error);
writeLog("err", "Not able to manage the status of the device.SetupDiCallClassInstaller API Failed", error);
{
if (error == 13)
{
for (int i = 0; i < 100; i++)
{
writeLog("war", "Retrying");
if (SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, m_hDevInfo, &spdd))
{
printf("retry succeeded for disabling device\n");
writeLog("suc", "Retry succeeded for disabling device", GetLastError());
break;
}
printf("retry failed for disabling device\n");
writeLog("err", "Retry failed for disabling device");
Sleep(20);
}
}
}
}
|
Just try to enable Edit group policy in Administrative Template/System/Removable Storage Access/Removable Disks: Deny read Access manually.
Or you can use Group API using program (https://learn.microsoft.com/en-us/windows/win32/api/_policy/).
you can refer the below code for disabling the read access.
int denyRead(DWORD val)
{
HKEY key;
HKEY pol;
//DWORD val = 1;
DWORD disp = 0;
GUID ext = REGISTRY_EXTENSION_GUID;
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
CComPtr<IGroupPolicyObject> lgp;
HRESULT hr = CoCreateInstance(CLSID_GroupPolicyObject, NULL, CLSCTX_INPROC_SERVER, IID_IGroupPolicyObject, (LPVOID*)&lgp);
if (SUCCEEDED(lgp->OpenLocalMachineGPO(GPO_OPEN_LOAD_REGISTRY)))
{
if (SUCCEEDED(lgp->GetRegistryKey(GPO_SECTION_MACHINE, &key)))
{
//All Removable Storage classes: Deny All access
RegCreateKeyExW(key, L"SOFTWARE\\Policies\\Microsoft\\Windows\\RemovableStorageDevices", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_QUERY_VALUE, NULL, &pol, &disp);
RegSetValueEx(pol, L"Deny_All", 0, REG_DWORD, (BYTE*)&val, sizeof(val));
RegCreateKeyExW(key, L"SOFTWARE\\Policies\\Microsoft\\Windows\\RemovableStorageDevices\\{53f5630d-b6bf-11d0-94f2-00a0c91efb8b}", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_QUERY_VALUE, NULL, &pol, &disp);
//Removable Disks: Deny write access
RegSetValueEx(pol, L"Deny_Write", 0, REG_DWORD, (BYTE*)&val, sizeof(val));
//Removable Disks: Deny read access
RegSetValueEx(pol, L"Deny_Read", 0, REG_DWORD, (BYTE*)&val, sizeof(val));
//Removable Disks: Deny execute access
RegSetValueEx(pol, L"Deny_Execute", 0, REG_DWORD, (BYTE*)&val, sizeof(val));
RegCloseKey(key);
hr = lgp->Save(TRUE, TRUE, &ext, const_cast<GUID*>(&CLSID_GPESnapIn));
_com_error err(hr);
wprintf(L"%s", err.ErrorMessage());
}
}
lgp.Release();
CoUninitialize();
Sleep(1000);
return 0;
}
|
74,041,553
| 74,041,679
|
Passing Arrays as Parameters and Returning Them in C++
|
// createArray_1 returns the array as a return value
double* createArray_1( ) {
return new double [ 10 ];
}
// createArray_2 returns the array from the parameter list
// (using a reference parameter)
void createArray_2( double*& arr ) {
arr = new double [ 10 ];
}
// createArray_3 returns the array from the parameter list
// (without using a reference parameter but simulating
// pass-by-reference using a pointer)
void createArray_3( double** arr ) {
*arr = new double [ 10 ];
}
// What is wrong with the following two functions?
// void incorrectCreateArray_1( double* arr ) {
// arr = new double [ 10 ];
//}
// double* incorrectCreateArray_2( ) {
// double arr[ 10 ];
// return arr;
// }
And we have the main function:
int main() {
double* D;
D = createArray_1();
delete [] D;
createArray_2( D );
delete [] D;
createArray_3( &D );
delete [] D;
return 0;
}
Can you help me understand why create_array2 and create_array3 are correct whereas incorrectCreateArray_1 and incorrectCreateArray_2 are wrong?
To me, incorrectCreateArray_1 should be fine because we are passing a pointer, and then assign a double array of size 10 to it, which seems correct.
On the other hand, incorrectArray_2 returns a double pointer, which should be fine because arr points to a double array, which also seems correct.
|
void incorrectCreateArray_1( double* arr )
{
arr = new double [ 10 ];
}
is incorrect because you receive a pointer (uninitialized) and you make it point somewhere else. But only the arr pointer, local to this function, gets changed. The calling code still keeps its (uninitialized) pointer.
double* incorrectCreateArray_2( )
{
double arr[ 10 ];
return arr;
}
is incorrect because you return a pointer to a local object (arr) which will not be valid to access after the function returns.
|
74,041,830
| 74,041,873
|
C++ overload std::abs for custom (template) class?
|
Wrote my own numeric class. Overloaded std::numeric_limit::max() fine. However, I'm trying to overload std::abs() but the compiler doesn't like my attempt. I've tried this:
namespace std
{
template<uint8_t T>
MyType<T> abs(const MyType<T>& mt)
{
MyType<T> copy = mt;
copy.val = std::abs(md.val);
return copy;
}
}
However, the compiler isn't finding the overload:
error: no matching function for call to ‘abs(const MyType<10>&)’
/usr/include/c++/11/bits/std_abs.h:56:3: note: candidate: ‘long int std::abs(long int)’
56 | abs(long __i) { return __builtin_labs(__i); }
| ^~~
/usr/include/c++/11/bits/std_abs.h:56:12: note: no known conversion for argument 1 from ‘const MyType<10>’ to ‘long int’
56 | abs(long __i) { return __builtin_labs(__i); }
| ~~~~~^~~
/usr/include/c++/11/bits/std_abs.h:61:3: note: candidate: ‘long long int std::abs(long long int)’
61 | abs(long long __x) { return __builtin_llabs (__x); }
| ^~~
/usr/include/c++/11/bits/std_abs.h:61:17: note: no known conversion for argument 1 from ‘const MyType<10>’ to ‘long long int’
61 | abs(long long __x) { return __builtin_llabs (__x); }
| ~~~~~~~~~~^~~
/usr/include/c++/11/bits/std_abs.h:71:3: note: candidate: ‘constexpr double std::abs(double)’
71 | abs(double __x)
| ^~~
/usr/include/c++/11/bits/std_abs.h:71:14: note: no known conversion for argument 1 from ‘const MyType<10>’ to ‘double’
71 | abs(double __x)
| ~~~~~~~^~~
/usr/include/c++/11/bits/std_abs.h:75:3: note: candidate: ‘constexpr float std::abs(float)’
75 | abs(float __x)
| ^~~
/usr/include/c++/11/bits/std_abs.h:75:13: note: no known conversion for argument 1 from ‘const MyType<10>’ to ‘float’
75 | abs(float __x)
| ~~~~~~^~~
/usr/include/c++/11/bits/std_abs.h:79:3: note: candidate: ‘constexpr long double std::abs(long double)’
79 | abs(long double __x)
| ^~~
/usr/include/c++/11/bits/std_abs.h:79:19: note: no known conversion for argument 1 from ‘const MyType<10>’ to ‘long double’
79 | abs(long double __x)
Code calling it:
MyType<10> mt;
MyType<10> abs = std::abs(mt);
|
Adding function or function template declarations into the std namespace is not allowed.
You should put the overloads into the namespace where your custom type is declared and then call the function with an unqualified name, so that argument-dependent lookup can find your overload.
If you are not sure at the call site whether std::abs or your overload should be called, then do using std::abs; in the calling scope before the call.
Customizing abs like that is however not intended like it is for e.g. swap and you cannot assume that a library user will call it in the above form.
|
74,042,287
| 74,043,148
|
Does calling GetDC directly create memory leaks?
|
I am listening to the ON_WM_ERASEBKGND() msg, inside the fired function relative to that event called OnEraseBackground(CDC* pDC). I am changing a background color like the following:
if (pDC)
{
pDC->SetBkColor(BlackColor);
}
else if (GetDC())
{
GetDC()->SetBkColor(BlackColor);
}
My question is, should I call ReleaseDC() after GetDC()?
|
A device context returned from GetDC or CWnd::GetDC should always be released by passing it either to ReleaseDC or CWnd::ReleaseDC (doesn't matter which one). The documentation is a fair bit lenient towards situations where this isn't strictly necessary, though establishing those preconditions is complex in itself.
If you call either of the ReleaseDC functions on a device context that doesn't strictly need to be released, the operation has no adverse effect.
The consequences of not releasing device contexts (a GDI resource) is far worse than a memory leak. GDI resources are severely limited, and shared across all processes running in the same user session. One program's GDI resource leak can easily cause any other program to malfunction.
Note that you are calling GetDC twice in your code so you will want to release it twice as well. Alternatively, only call it once, e.g.
if (pDC)
{
pDC->SetBkColor(BlackColor);
}
else
{
auto myDC = GetDC();
myDC->SetBkColor(BlackColor);
ReleaseDC(myDC);
}
or, using an if statement with initializer (introduced in C++17):
if (pDC)
{
pDC->SetBkColor(BlackColor);
}
else if (auto myDC = GetDC())
{
myDC->SetBkColor(BlackColor);
ReleaseDC(myDC);
}
Though, really, I would probably just scrap the entire else-arm. If your WM_ERASEBKGND message handler doesn't receive a device context, then there's no reason to go hunting for one yourself.
|
74,042,325
| 74,043,027
|
listing all intermediate recurrence results
|
I have a function
int f(int);
I want to get
[0, f(0), f(f(0)), f(f(f(0))), ...]
until f return -1.
I was wondering if there is a name for this in functional programming. It looks like recursion.
|
The closest thing in range-v3 to do this views::partial_sum1. This takes a binary function, applying it to the result of the previous element in the destination range and the next element in the source range.
But here, we can simply ignore the next element in the source range, since we don't care about it - just the previous element:
auto recurrence =
rv::iota(0)
| rv::partial_sum([](int prev, int){
return f(prev);
})
| rv::take_while([](int i){
return i != -1;
})
iota(0) gives you the range [0, 1, 2, ...]. It doesn't actually matter what the contents are after the 0, just that they're infinite. rv::repeat(0) also works, that's just the range [0, 0, 0, ...]
The partial_sum then gives you the range [0, f(0), f(f(0)), f(f(f(0))), ...]
And then take_while stops when we reach -1. Note that -1 is not included in the result - if you want to include that, the construction is... trickier.
In general though, this kind of thing is much easier to do with a generator:
auto recurrence() -> generator<int> {
int i = 0;
while (i != -1) {
co_yield i;
i = f(i);
}
}
Which is also easier to restructure if you want to include the -1:
auto recurrence() -> generator<int> {
int i = 0;
while (true) {
co_yield i;
if (i == -1) {
break;
}
i = f(i);
}
}
1 range-v3 has views::generate, but that takes a nullary function - it gives you the range [f(), f(), f(), ...], but allowing for f() to return a different value every time. I suppose we could use that to do:
views::generate([cur=0, next=0]() mutable {
cur = next;
next = f(next);
return cur;
})
Which we could built up a:
auto generate_unary = [](auto init, auto f){
return views::generate([cur=init, next=init, f]() mutable {
cur = next;
next = f(next);
return cur;
});
};
And then we can generate_unary(0, f)
|
74,042,810
| 74,043,589
|
How to reduce recursive variadic inheritance code bloat?
|
Let's say I want to create a variadic interface with different overloads for the structs A,B,C:
struct A{};
struct B{};
struct C{};
template <typename ... Ts>
class Base;
template <typename T>
class Base<T>{
public:
virtual void visit(const T& t) const
{
// default implementation
}
};
template<typename T, typename ... Ts>
class Base<T, Ts...>: Base<T>, Base<Ts...>{
public:
using Base<T>::visit;
using Base<Ts...>::visit;
};
int main()
{
A a;
B b;
auto base = Base<A,B,C>{};
auto base2 = Base<A,C,B>{};
base.visit(a);
base2.visit(b);
}
Now funtionally Base<A,B,C> is identical to Base<A,C,B> but the compiler still generates the different combinations. Of course with more template parameters it gets worse.
I assume there is some meta programming magic which can cut this code bloat down.
One solution might be to define template<typename T, typename U> Base<T,U> in a way that it checks if Base<U,T> already exists. This could reduce at least some combinations and can probably be done by hand for triplets as well. But I am missing some meta programming magic and hoping for a more general approach.
Edit:
I would like to have the variadic Interface for a (simplified) use case like that:
class Implementation:public Base<A,B,C>
{
public:
void visit(const A& a) const
{
std::cout <<"Special implementation for type A";
}
void visit(const B& a) const
{
std::cout <<"Special implementation for type B";
}
// Fall back to all other types.
};
using BaseInterface = Base<A,B,C>;
void do_visit(const BaseInterface& v)
{
v.visit(A{});
v.visit(B{});
v.visit(C{});
}
int main()
{
std::unique_ptr<BaseInterface> v= std::make_unique<Implementation>();
do_visit(*v);
}
The reason why I want to do this is that there could be potentially a lot of types A,B,C,... and I want to avoid code duplication to define the overload for each type.
|
Base<A, B, C> instantiates Base<A>, Base<B, C>, Base<B>, Base<C>
and
Base<A, C, B> instantiates Base<A>, Base<C, B>, Base<B>, Base<C>
Whereas final nodes are needed, intermediate nodes increase the bloat.
You can mitigate that issue with:
template <typename T>
class BaseLeaf
{
public:
virtual ~BaseLeaf() = default;
virtual void visit(const T& t) const
{
// default implementation
}
};
template <typename... Ts>
class Base : public BaseLeaf<Ts>...
{
public:
using BaseLeaf<Ts>::visit...;
};
Demo
Base<A,B,C> and Base<A,C,B> are still different types.
To be able to have same type, they should alias to the same type, and for that, ordering Ts... should be done in a way or another.
|
74,043,619
| 74,044,000
|
What is the default probability of [[likely]]? Is it possible to change it?
|
What is the default probability of [[likely]]? Is it possible to change it?
Backgound: GCC has the following built-in functions:
long __builtin_expect(long exp, long c): the probability that a __builtin_expect expression is true is controlled by GCC's builtin-expect-probability parameter, which defaults to 90%.
long __builtin_expect_with_probability(long exp, long c, double probability): the last argument, probability, is a floating-point value in the range 0.0 to 1.0, inclusive.
What is the C++ definition of the term "likely"? 51%? 90%? What does the term "arbitrarily (un)likely" mean?
|
There is no "probability" for these things. They tell the compiler to rearrange code and tests around branches to optimize for the case where one path is more often taken than another. But that's all.
These are not everyday tools you should be tossing into every loop and if statement. These are micro-optimization tools that are best used when one has a clear performance target in mind and one sees that the compiler is generating sub-optimal machine code in a performance-critical section of code. Only then do you employ these tools. And even then, you need to check the generated code to see if they fixed the problem you're trying to solve.
These are compiler tweaks for cases where the compiler's usual methods of code generation around a branch does not produce optimal code. It's not about probability; it's about micro-optimization.
Here is a quote from the paper adding this feature to the standard:
Objection #1: Can this feature easily result in code pessimization?
Yes, as shown by the conditional move example misusing a branch hint can definitely result in worse code with a much longer run time. This feature is primarily meant to be used after a hotspot has been found in existing code. The proposed attributes are not meant to be added to code without measuring the impact to ensure they do not end up degrading performance.
Emphasis added. So please do not just throw these anywhere.
One of the biggest dangers in adding these attributes by default is that the information is, conceptually, redundant. Something, somewhere decides what the likelihood of the branch actually is, and you're specifying that likelihood more directly.
Redundantly-specified information can easily get out-of-sync. Non-local changes to code can change the likelihood of branches, which gets the two out-of-sync. And once that happens, the attribute becomes very bad for performance.
So it's best to apply this in specific cases, with profilers handy, and with relatively mature code where the likelihood is unlikely to change.
|
74,043,623
| 74,044,848
|
How can I get the logging directory of a RollingFileAppender from log4cxx?
|
I'm using XML to configure log4cxx. The appender is a RollingFileAppender that outputs to a folder like yyyy/MM/dd/HHmm, and I need to know what that folder is at the end of the program.
I can't get the current yyyy/MM/dd/HHmm at runtime because that value will likely be different than it was when the log directory was created. After scanning log4cxx's documentation, I found only one function that was relevant:
log4cxx::FileAppender::getFile()
which returns the file that an appender is logging to.
The problem with that is that calls to log4cxx::Logger::getAppender() yield only AppenderPtrs- I could dynamic_cast this into a FileAppender if I know that's the ultimate type, but this introduces uncertainty into the program. Is there really no way to get the current log directory from log4cxx?
Thanks!
|
There is currently no(easy) way to get the name of the file that the RollingFileAppender is using.
Using Logger::getAppender() is the best way to get the correct appender that you are looking for. Since the appenders should all have unique names, there shouldn't be any issue with casting to the correct type. If you want to be safe about casting, use log4cxx::cast<FileAppender>( AppenderPtr ) which will return an invalid pointer if the object is unable to be casted to the correct type.
|
74,043,745
| 74,046,260
|
Using macros to define forward declarations
|
I am writing a pretty huge program with lots of templated functions. Naturally, the program has a long compile-time, which is why I wanted to use forward declaration. Now there are a lot of functions and I do not want to write the forward declaration for each single one of them. Even more so, I want to be able to add some functions without having to add the forward declarations manually.
A quick example:
#define max_dim 3
template bool match_any<1>();
template bool match_any<2>();
template bool match_any<3>();
If I set max_dim to another value, I do not want to manually add the additional forward declarations.
Until now I have used a python-script, to just generate a file with all the forward declarations for me.
My goal now is to avoid the python-script and to do this using the cpp-preprocessor only (if this is possible). More concretly, I want to be able to just change the max_dim and all neccessary forward-declarations are generated.
I now that loops etc. are possible just with the preprocessor; what I do not know is how to actually make the preprocessor generate the declarations.
|
I'm not the right one to ask if what you want to do is possible in a better way, but this is definitely solvable using the preprocessor.
I'll use file iteration, although other methods are also possible:
// slot.h
#ifndef A_0
# include "a.h"
#else
# include "b.h"
#endif
// a.h
#if (SLOT) & 1
# define A_0 1
#else
# define A_0 0
#endif
#if (SLOT) & 2
# define A_1 2
#else
# define A_1 0
#endif
#if (SLOT) & 4
# define A_2 4
#else
# define A_2 0
#endif
#if (SLOT) & 8
# define A_3 8
#else
# define A_3 0
#endif
#undef VAL
#define VAL (A_3|A_2|A_1|A_0)
#undef B_0
#undef B_1
#undef B_2
#undef B_3
// b.h
#if (SLOT) & 1
# define B_0 1
#else
# define B_0 0
#endif
#if (SLOT) & 2
# define B_1 2
#else
# define B_1 0
#endif
#if (SLOT) & 4
# define B_2 4
#else
# define B_2 0
#endif
#if (SLOT) & 8
# define B_3 8
#else
# define B_3 0
#endif
#undef VAL
#define VAL (B_3|B_2|B_1|B_0)
#undef A_0
#undef A_1
#undef A_2
#undef A_3
// impl.cpp
#ifndef VAL
#define VAL 12
#endif
template bool match_any<VAL>();
#define SLOT (VAL-1)
#include "slot.h"
#if VAL != 0
#include __FILE__
#endif
(https://godbolt.org/z/csehns44j)
If you need more than 4 bits to represent the value of max_dim, then you'd need to add a few lines to a.c and b.c.
This uses self recursive includes, which only works for a few hundred iterations (without special compiler flags).
To circumvent this, you can use the following structure:
// iter1.h
#if CONTINUE
#include "iter2.h"
#if CONTINUE
#include "iter2.h"
#if CONTINUE
#include "iter2.h"
#if CONTINUE
#include "iter2.h"
#if CONTINUE
#include "iter2.h"
// ...
#endif
#endif
#endif
#endif
#endif
// iter2.h
#if CONTINUE
#include "iter3.h"
#if CONTINUE
#include "iter3.h"
#if CONTINUE
#include "iter3.h"
#if CONTINUE
#include "iter3.h"
#if CONTINUE
#include "iter3.h"
// ...
#endif
#endif
#endif
#endif
#endif
// iter3.c
#if CONTINUE
#include FILE
#if CONTINUE
#include FILE
#if CONTINUE
#include FILE
#if CONTINUE
#include FILE
#if CONTINUE
#include FILE
// ...
#endif
#endif
#endif
#endif
#endif
// impl.cpp
#ifndef VAL
#define VAL 100
#define FILE "impl.cpp"
#endif
template bool match_any<VAL>();
#define SLOT (VAL-1)
#define CONTINUE VAL != 0
#include "slot.h"
#ifndef ONCE
#define ONCE
#include "iter1.h"
#endif
(https://godbolt.org/z/h74jPb11c)
With 3 iter.h files, of which each has 5 includes that results in 5^3 iterations. Expanding this should be trivial.
|
74,043,973
| 74,044,142
|
How can I delete specific parts of the console in c++ ? ( not a file )
|
I'm already familiar with system ("cls") but it deletes all of the text above it and I just need to delete some of the text not all.
|
[Based on the reference to cls, I'm assuming this is code running under Windows.]
It depends on whether you need portability.
If you want (reasonably) portable code, you can use curses, an old text-mode Windowing library, originally written for terminals under Unix, but now implemented on most other systems (Linux, Windows, MacOS, etc.)
If you don't care about portability, Windows provides FillConsoleOutputCharacter, which will let you fill parts of a console with arbitrary characters. To "delete" text, you normally fill that area with spaces.
|
74,044,010
| 74,046,228
|
Detecting from within a process whether it is running as an HTCondor job
|
Could you please let me know if there is a way to detect from within a process whether it is running as an HTCondor job?
I am especially interested in how to do it from python code but a C++ way to do it would be also very helpful.
Example of what I hope to do in python:
if current_process_is_running_as_an_HTCondor_job():
do_action_1()
else:
do_action_2()
How can one implement current_process_is_running_as_an_HTCondor_job() ?
Thank you very much for your help!
|
HTCondor sets a number of environment variables: https://htcondor.readthedocs.io/en/latest/users-manual/services-for-jobs.html
_CONDOR_SCRATCH_DIR
_CONDOR_SLOT
_CONDOR_JOB_AD
_CONDOR_MACHINE_AD
_CONDOR_JOB_IWD
_CONDOR_WRAPPER_ERROR_FILE
The existence of any of them would be a good indicator that you are running under Condor.
|
74,044,260
| 74,045,438
|
trying to figure out std::count_if
|
So I've been stuck with yet another issue and can't figure it out. I'm tryin to write a programm that will count vowels in a txt file. And I'm using different methods to do that. Now I'm stuck with a std::count_if method. Here is the code:
std::string vowels = "aeiouyAEIOUY";
bool findVowel()
{
for (size_t i = 0; i < vowels.size(); i++)
{
if (vowels.find(i) != std::string::npos)
{
return true;
}
}
}
void CountIf(std::ifstream& x)
{
std::string ww;
Timer t("count_if/find");
size_t c = 0;
while (x >> ww)
{
size_t count = std::count_if(ww.begin(), ww.end(), findVowel());
c = count;
}
t.print();
std::cout << c;
}
and i get the Error: C2064 term doesn't evaluate to a function taking 1 arguments. Maybe I should have used lambda in this case, though I don't think it would have solved the problem.
Hope for some help! Thank you!)
|
Start by checking the documentation of std::count_if.
As you can see in (3), it requires a UnaryPredicate, which is some function (or function object) that takes a single parameter and returns true or false. The count_if function goes over each char in the input and uses your predicate to check if it counts. Therefore your predicate could look like this:
bool isVowel(char c)
{
static const std::string vowels = "aeiouyAEIOUY";
return vowels.find(c) != std::string::npos;
}
Notice that the function takes a char now. When count_if calls your predicate, it passes the current character as an argument. The for loop was unnecessary, because find(c) iterates over the vowels and returns an index or npos. Since the string of vowels is constant and used only in this function, we could make it a static const.
When passing your predicate to count_if, think of the function as a value.
const size_t count = std::count_if(word.begin(), word.end(), isVowel);
Notice that there is no () after isVowel, because we are not calling it, just passing.
|
74,044,278
| 74,044,393
|
static variables in a template class c++
|
So, I'm pretty new in the generic programmation and I started the following :
template<class T>
class A
{
public:
static int m;
}
template<class T>
int A<T>::m;
int main()
{
A::m = 3; //Cannot compile of course !!
return 1
}
The idea being to have a member variable that could be shared by all the instances of A, no matter what T we have.
Would there be any way of doing this or do I have to use a global variable instead ?
|
Members of class templates are never shared between specializations of the class template. You should consider a class template to be just that: A template to create classes of similar structure based on different types. For each type T the specialization A<T> is an independent class. The resulting classes are not otherwise related in any way.
If you want to have multiple classes share a static data member, you can put the member in a base class:
struct ABase
{
static int m;
};
template<class T>
struct A : ABase
{
};
int ABase::m;
int main()
{
A<int>::m = 3;
return A<double>::m; // will return 3
}
You still need to specify a type for the template argument though when accessing the member through A, because A itself is not a class that has members at all, it is just a template of which specializations may or may not have the m member inherited from a base. In particular you could add partial specializations or explicit (full) specializations of A which override the definition of A<T> for some types of T, so that A<T>::m is not ABase::m any longer.
Also make sure that this really logically makes sense for your use case. Again, specializations of a class template are as such unrelated types.
|
74,044,404
| 74,044,577
|
save result of for_each algorithm inside a vector
|
I have a functor and the overloaded operator() of it returns a double. In an easy way I can write:
int main(){
auto f=[](double t){return 1.0/(pow(7.0*t,2.0)+1.0);};
std::vector<double> nodes(n);
bestpolchevnod(f,nodes); //calculate nodes = f_i(cheby_point(i))
ChebyPoly c_p = ChebyPoly(nodes);//call the constructor with the calculated nodes
std::cout << c_p(0.6) << std::endl; //evaluate at c_p(0.6) as an approx of f(0.6)
};
Now it is possible to go through a set of values by using for_each() like:
std::vector<double> xpoints={0.4,0.5,0.6,0.7};
std::for_each(xpoints.begin(), xpoints.end(), ChebyPoly(nodes));
Is there a sharp/short way to save the calculated values of this algorithm directly for example in a vector? I know there are ways to do it otherwise. But I wonder if there is something similar like
std::vector<double> resvec(xpoints.size());
resvec.push_back(std::for_each(xpoints.begin(), xpoints.end(), ChebyPoly(nodes))); // wrong
|
std::for_each is the wrong algorithm, you want std::transform
std::vector<double> resvec(xpoints.size());
std::transform(xpoints.begin(), xpoints.end(), resvec.begin(), ChebyPoly(nodes));
Or without zero-initialising the elements of resvec
std::vector<double> resvec;
resvec.reserve(xpoints.size());
std::transform(xpoints.begin(), xpoints.end(), std::back_inserter(resvec), ChebyPoly(nodes));
Or without allocating a result, instead having a lazy view
auto result = xpoints | std::ranges::views::transform(ChebyPoly(nodes));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.