question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,161,504 | 72,163,631 | Does std::atomic<> gurantee that store() operation is propagated immediately (almost) to other threads with load()? | I have std::atomic<T> atomic_value; (for type T being bool, int32_t, int64_t and any other). If 1st thread does
atomic_value.store(value, std::memory_order_relaxed);
and in 2nd thread at some points of code I do
auto value = atomic_value.load(std::memory_order_relaxed);
How fast is this updated atomic value propagated from 1st thread to 2nd, between CPU cores? (for all CPU models)
Is it propagated almost-immediately? For example up-to speed of cache coherence propagation in Intel, meaning that 0-2 cycles or so. Maybe few more cycles for some other CPU models/manufacturers.
Or this value may stuck un-updated for many many cycles sometimes?
Does atomic guarantee that value is propagated between CPU cores as fast as possible for given CPU?
Maybe if instead on 1st thread I do
atomic_value.store(value, std::memory_order_release);
and on 2nd thread
auto value = atomic_value.load(std::memory_order_acquire);
then will it help to propagate value faster? (notice change of both memory orders) And now with speed guarantee? Or it will be same gurantee of speed as for relaxed order?
As a side question - does replacing relaxed order with release+acquire also synchronizes all modifications in other (non-atomic) variables?
Meaning that in 1st thread everything that was written to memory before store-with-release, is this whole memory guaranteed in 2nd thread to be exactly in final state (same as in 1st thread) at point of load-with-acquire, of course in a case if loaded value was new one (updated).
So this means that for ANY type of std::atomic<> (or std::atomic_flag) point of store-with-release in one thread synchronizes all memory writes before it with point in another thread that does load-with-acquire of same atomic, in a case of course if in other thread value of atomic got updated? (Sure if value in 2nd thread is not yet new then we expect that memory writes have not yet finished)
PS. Why question arose... Because according to name "atomic" it is obvious to conclude (probably miss-conclude) that by default (without extra constraints, i.e. with just relaxed memory order) std::atomic<> just makes any arithmetic operation atomical, and nothing else, no other guarantees about synchronization or speed of propagation. Meaning that write to memory location will be whole (e.g. all 4 bytes at once for int32_t), or exchange with atomic location will do both read-write atomically (actually in a locked fashion), or incrementing a value will do atomically three operations read-add-write.
| The C++ standard says only this [C++20 intro.progress p18]:
An implementation should ensure that the last value (in modification order) assigned by an atomic or
synchronization operation will become visible to all other threads in a finite period of time.
Technically this is only a "should", and "finite time" is not very specific. But the C++ standard is broad enough that you can't expect them to specify a particular number of cycles or nanoseconds or what have you.
In practice, you can expect that a call to any atomic store function, even with memory_order_relaxed, will cause an actual machine store instruction to be executed. The value will not just be left in a register. After that, it's out of the compiler's hands and up to the CPU.
(Technically, if you had two or more stores in succession to the same object, with a bounded amount of other work done in between, the compiler would be allowed to optimize out all but the last one, on the basis that you couldn't have been sure anyway that any given load would happen at the right instant to see one of the other values. In practice I don't believe that any compilers currently do so.)
A reasonable expectation for typical CPU architectures is that the store will become globally visible "without unnecessary delay". The store may go into the core's local store buffer. The core will process store buffer entries as quickly as it can; it does not just let them sit there to age like a fine wine. But they still could take a while. For instance, if the cache line is currently held exclusive by another core, you will have to wait until it is released before your store can be committed.
Using stronger memory ordering will not speed up the process; the machine is already making its best efforts to commit the store. Indeed, a stronger memory ordering may actually slow it down; if the store was made with release ordering, then it must wait for all earlier stores in the buffer to commit before it can itself be committed. On strongly-ordered architectures like x86, every store is automatically release, so the store buffer always remains in strict order; but on a weakly ordered machine, using relaxed ordering may allow your store to "jump the queue" and reach L1 cache sooner than would otherwise have been possible.
|
72,161,614 | 72,167,256 | identifier D3DReadFileToBlob is undefined? | #include<D3Dcompiler.h>
void Init()
{
D3DReadFileToBlob(L"", nullptr);
}
it gives D3DReadFileToBlob is undefined error, i don't think it is a linking error and i read this which i don't get what am i suppose to do (i think that might be the cause)
so what should i do to fix this?
| The problem was that i was using both Windows Kits and Directx SDK at the same time and that caused this error, Because i was watching old tutorials i didn't know that i really don't need Directx SDK and i could use Windows Kits which already has everything in it for development of directx 11.
|
72,161,866 | 72,162,062 | cannot be used as a member pointer, since it is of type 'void (*)()' | I'm trying to dereference a method pointer stored in a static array and call it from within a method, but I'm getting the following error:
error: 'chip8::Chip8::table[0]' cannot be used as a member pointer, since it is of type 'void (*)()'
(this->*table[0])();
^
Here is my class declaration (chip.hpp):
class Chip8{
private:
static void (*table[16])(); //function pointer table
//...
public:
void cycle();
//...
};
and here are the implementations of Chip8::cycle and Chip8::table (chip.cpp):
void (Chip8::*table[16])() = {
&Chip8::opcode0,
&Chip8::JP_1nnn,
&Chip8::CALL_2nnn,
&Chip8::SE_3xkk,
&Chip8::SNE_4xkk,
&Chip8::SE_5xy0,
&Chip8::LD_6xkk,
&Chip8::ADD_7xkk,
&Chip8::opcode8,
&Chip8::SNE_9xy0,
&Chip8::LD_Annn,
&Chip8::JP_Bnnn,
&Chip8::RND_Cxkk,
&Chip8::DRW_Dxyn,
&Chip8::opcodeE,
&Chip8::opcodeF
};
void Chip8::cycle(){
opcode = (memory[pc] << 8) | memory[pc+1];
pc+=2;
(this->*table[0])(); // error here
if(dt > 0){
dt--;
}
if(st > 0){
st--;
}
}
EDIT:
Here are the declarations of the functions assigned to the table:
//Function table extensions
void opcode0();
void opcode8();
void opcodeE();
void opcodeF();
//Instructions
void CLS_00E0(); // Clears screen
void RET_00EE(); // Pops new pc off the stack
void JP_1nnn(); // Jumps to nnn
void CALL_2nnn(); // Pushes current pc to stack and jumps to nnn
void SE_3xkk(); // Skip next instruction if Vx = kk
void SNE_4xkk(); // Skip next instruction if Vx != kk
void SE_5xy0(); // Skip next instruction if Vx == Vy
void LD_6xkk(); // Set Vx = kk
void ADD_7xkk(); // Vx += kk
void LD_8xy0(); // Vx = Vy
void OR_8xy1(); // Vx |= Vy
void AND_8xy2(); // Vx &= Vy
void XOR_8xy3(); // Vx ^= Vy
void ADD_8xy4(); // Vx += Vy, if the sum is greater than 255, then VF = 1
void SUB_8xy5(); // Vx -= Vy, if Vx > Vy, then VF = 1, otherwise VF = 0
void SHR_8xy6(); // Vx >>= 1, if least significant bit of Vx is 1, then VF is set to 1, otherwise 0
void SUBN_8xy7(); // Vx = Vy - Vx, if Vy > Vx, VF = 1, otherwise VF = 0
void SHL_8xyE(); // Vx <<= 1, if most significant bit of Vx is 1, then VF is set to 1, otherwise 0
void SNE_9xy0(); // Skip next instruction if Vx != Vy
void LD_Annn(); // I = nnn
void JP_Bnnn(); // Jumps to nnn + V0
void RND_Cxkk(); // Vx = random byte & kk
void DRW_Dxyn(); // Draws n-byte (n = height) sprite starting at Vx and Vy. If collision detected, VF = 1
void SKP_Ex9E(); // Skip next instruction if value of Vx is pressed
void SKNP_ExA1(); // Skip next instruction if value of Vx isn't pressed
void LD_Fx07(); // Set Vx = delay timer
void LD_Fx0A(); // Wait for key press and store value in Vx
void LD_Fx15(); // Set delay timer = Vx
void LD_Fx18(); // Set sound timer = Vx
void ADD_Fx1E(); // Set I += Vx
void LD_Fx29(); // Set I = memory location of digit sprite in Vx
void LD_Fx33(); // Store BCD representation of value of Vx in I, I+1, I+2
void LD_Fx55(); // Store registers V0 through Vx (including) starting at memory location I
void LD_Fx65(); // Read registers V0 through Vx (including) starting at memory location I
What is the problem and how can I fix it?
| The problem is that when you wrote:
static void (*table[16])();
you're declaring a static data member named table that is an array of size 16 whose elements are pointers to free function with no parameter and return type of int.
But what you actually want is a table that is an array of size 16 whose elements are pointers to the member functions of Chip8 which you can do as shown below:
class Chip8{
private:
//---------------vvvvvvvv------------>note the added Chip8::* indicating that a pointer to a member function instead of free function
static void (Chip8::*table[16])(); //function pointer table
public:
void cycle();
void opcode0();
};
//definition for the static data member `table`
void (Chip8::*Chip8::table[16])() = {
&Chip8::opcode0,
};
void Chip8::opcode0()
{
std::cout<<"opcode0 called"<<std::endl;
}
void Chip8::cycle(){
std::cout<<"cycle called"<<std::endl;
(this->*table[0])();
}
int main()
{
Chip8 chip;
chip.cycle();
return 0;
}
Working Demo.
Note that you can make the above code more readable using alias declaration as shown below:
class Chip8{
private:
using type = void (Chip8::*)();
static type table[16]; //function pointer table
public:
void cycle();
void opcode0();
};
Chip8::type Chip8::table[16] = {
&Chip8::opcode0,
};
void Chip8::opcode0()
{
std::cout<<"opcode0 called"<<std::endl;
}
void Chip8::cycle(){
std::cout<<"cycle called"<<std::endl;
(this->*table[0])();
}
int main()
{
Chip8 chip;
chip.cycle();
return 0;
}
Demo
|
72,162,158 | 72,162,205 | Why does not std::priority_queue constructor work? | Why is it that when I call the same constructor, it works in one case, but not in the other?
std::vector<ulli> v(n);
for(int i = 0; i < n; i++){
inf >> v[i];
}
std::priority_queue<ulli> q1(std::greater<ulli>(), v); // fails
std::priority_queue<ulli> q2(std::less<ulli>(), v); // works
| Because of the default template parameter, the Compare of std::priority_queue<ulli> is of type std::less, and in your first example, you use std::greater to initialize std::less, which is not correct.
With help of CTAD, just
std::priority_queue q1(std::greater<ulli>(), v);
|
72,162,197 | 72,162,263 | How to assign base class shared_ptr object to child class shared_ptr object | in below scenario, I need to invoke child class B function (fun1) from Base class A shared pointer
returned by setup function and for the same have used dynamic_cast_pointer so that derived
class shared_ptr object can be assigned to Base class shared_ptr but during compilation I am
not allowed to do so. Can anybody suggest how to achieve this behaviour
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
void fun() {cout<<"A"<<endl;}
};
class B : public A
{
public:
void fun1() {cout<<"B" <<endl;}
};
shared_ptr<A> setup(shared_ptr<A> ptr = nullptr )
{
if(!ptr)
{
ptr = make_shared<A> ();
}
ptr.get()->fun();
return ptr;
}
int main() {
auto ptr = std::dynamic_pointer_cast <B> (setup());
ptr->fun1(); // Doesn't compile
}
| I presume the question is cut down from the real problem.
Presuming you're not expecting this example to work at runtime (you are casting a pointer to A as a pointer to B when it's an instance of A - so you're in undefined behaviour territory), the issue is that you have no virtual methods. The compiler tells you this:
error: 'A' is not polymorphic
When you intend to use pointers to a base class, you need to have virtual destructors (personally I always use them as a matter of course).
See demo: https://godbolt.org/z/qe6jPrhsa
Here you can see a modified example demonstrating that you're in Undefined Behaviour territory...
https://godbolt.org/z/harzoP946
|
72,162,281 | 72,162,546 | C++ Vector subscript out of range when assigning values | I am making a simple algorithm that counts how many times each number is represented in a vector. However, on compile it gives me the following error in popup: Vector subscript out of range and it is referencing to:
File: C:\Program Files\Microsoft Visual
Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector
Line:
1463
Code:
//get if highest value is negative
if (mx < 0) {
//store number of invidiual values in array invert, mn value
std::vector<int> vl(mn * -1);
for (int x = 0; x < arr.size(); x++) {
vl[arr[x] * -1] += 1;
}
Here I am working with negative values so I am inverting them to positive. Mn is representing the lowest value in the vector, which is then inverted so it becomes the highest, according to is created another vector Vl which stores a number of each value, so its size is mn * -1.
Full function:
void topSort(std::vector<int> &arr) {
//stores highest value
int mx = arr[0];
//stores lowest value
int mn = arr[0];
//get highest value
for (int i = 1; i < arr.size(); i++) {
if (arr[i] > mx) {
mx = arr[i];
}
if (arr[i] < mn) {
mn = arr[i];
}
}
//get if highest value is negative
if (mx < 0) {
//store number of invidiual values in array invert mx value
std::vector<int> vl(mn * -1);
for (int x = 0; x < arr.size(); x++) {
vl[arr[x] * -1] += 1;
}
for (auto z : vl) {
std::cout << z << "\n";
}
} else {
//store number of invidiual values in array
std::vector<int> vl(mx);
}
}
| On the input [-3, -2, -1], your program will:
Set mx=-1.
Set mn=-3.
Create a vector vl of size 3, so with the positions vl[0], vl[1] and vl[2].
Try to set vl[3] += 1, which throws the error you are seeing, as vl[3] does not exist.
You should have std::vector<int> vl(mn * -1 + 1); to avoid out-of-range exceptions.
|
72,162,309 | 72,162,428 | How to call a templated function for each type in a tuple (acting as type list) with tuple b as argument | How to call a template function for each type in a typelist with arguments (e.g. another tuple)?
Given is a typelist std::tuple<T1, T2, T3, ...> and a std::tuple containing data.
template <typename T>
void doSomething (const auto& arg) {
std::cout << __PRETTY_FUNCTION__ << '\n';
}
template <typename T> struct w {T v; w(T _v) : v{_v} {}};
int main () {
using types = std::tuple<int, char, float, double, w<int>, w<float>>; // used as type list
constexpr auto data = std::make_tuple(1, 2, 3.0, 4.0f, w(5.0));
// call doSomething<T>(data) for each type in types
// like
// someFunctor<types>(doSomething, data);
}
My current idea is a functor like appreach that receives the typelist to extract nexted types and std::tuple<Ts> having an operator () to call doSomething<T>(args) for each of Ts.
template<template<typename...> typename TL, typename... Ts>
struct someFunctor {
template<typename... Args>
static constexpr void operator() (Args&&... args) {
(doSomething<Ts>(std::forward<Args>(args)...), ...);
}
};
Not sure if that's the smartest approach. Brain fog blocked me so far to get it work.
| Use template partial specialization to extract the type of typelist, then use fold-expression to invoke doSomething with different template parameters
template<typename Tuple>
struct someFunctor;
template<typename... Args>
struct someFunctor<std::tuple<Args...>> {
template<class T>
constexpr void operator()(T&& x) {
(doSomething<Args>(std::forward<T>(x)), ...);
}
};
Demo
using types = std::tuple<int, char, float, double, w<int>, w<float>>;
constexpr auto data = std::make_tuple(1, 2, 3.0, 4.0f, w(5.0f));
someFunctor<types>()(data);
|
72,162,366 | 72,162,519 | Change image range using linear interpolation | so I want to change an image from lets say width=500 to width=100, using linear interpolation. How can I do that?
| I'll try to help even though the question requires improvements:
You can use cv::resize to resize the image. The interpolation parameter can be set to cv::INTER_LINEAR for linear interpolation.
Code example:
cv::Mat bigImg(cv::Size(500, 500), CV_8UC1);
// Initialize bigImg in some way ...
cv::Mat smallImg;
cv::resize(bigImg, smallImg, cv::Size(100, 100), 0, 0, cv::INTER_LINEAR);
See the documentation for cv::resize, and interpolation options.
You can also see recommended interpolation method for various cases here: Which kind of interpolation best for resizing image?.
|
72,163,114 | 72,173,789 | Segmentation fault when trying to pass dynamic array to processes | I tried to pass dynamic array from 0 process to 1 and vice versa. Getting segmentation fault in process 1. All matrices printed as expected. What could be the problem in this situation?
int main(int argc, char **argv){
MPI_Init(&argc,&argv);
int n;
cin >> n;
int *matrix = new int[n*n];
int *matrix2 = new int[n*n];
int i,j,ProcNum,ProcRank;
MPI_Comm_size(MPI_COMM_WORLD, &ProcNum);
MPI_Comm_rank(MPI_COMM_WORLD, &ProcRank);
MPI_Status status;
if (ProcRank == 0){
/* Filling matrices here with i*n + j values*/
MPI_Send(&n, 1, MPI_INT, 1, 1, MPI_COMM_WORLD);
MPI_Send(&(matrix[0]), n*n, MPI_INT, 1, 2, MPI_COMM_WORLD);
MPI_Recv(&(matrix[0]), n*n, MPI_INT, 1, 2, MPI_COMM_WORLD, &status);
print_matrix(matrix,n);
}
if (ProcRank > 0) {
MPI_Recv(&n, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
MPI_Recv(&(matrix[0]), n*n, MPI_INT, 0, 2, MPI_COMM_WORLD, &status);
/*passing i-j values to matrix and printing them here*/
MPI_Send(&(matrix[0]), n*n, MPI_INT, 0, 2, MPI_COMM_WORLD);
}
MPI_Finalize();
delete matrix;
delete matrix2;
return EXIT_SUCCESS;
}
| Interactive input in parallel programs is always dangerous. Your MPI processes are often started through an ssh connection, and so they will probably not get the terminal input. Process zero most likely will, so I'd advocate reading n only on process zero and then broadcasting it.
|
72,163,357 | 72,164,530 | SDL mingw static lib linking errors | I'm trying to compile a simple SDL program using Mingw w64. Here is my code:
test.c
#include "SDL2/SDL.h"
#include <stdio.h>
int main( int argc, char* args[] )
{
SDL_Window *window;
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("SDL2 Window", 100, 100, 640, 480, 0);
if(window==NULL)
{
printf("Could not create window: %s\n", SDL_GetError());
return 1;
}
SDL_Delay(3000);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
and here is the command I'm using to compile the program:
g++ -o text.exe test.c -I./include -L./lib -lmingw32 -lSDL2main -lSDL2
but when I compile the program, I get hundreds of linking errors that look like this:
./lib/libSDL2.a(SDL_wasapi_win32.o): In function `WASAPI_PlatformInit':
/Users/valve/release/SDL/SDL2-2.0.22-source/foo-x64/../src/audio/wasapi/SDL_wasapi_win32.c:255: undefined reference to `__imp_CoCreateInstance'
I downloaded the library from the second link down in the windows development libraries section on the official SDL website, and took the libraries from the following directory:
SDL2-2.0.22\x86_64-w64-mingw32\lib
The contents of ./lib are:
libSDL2main.a
libSDL.a
What is the problem and how can I fix it?
| You have two options, depending on your intent:
If you want to link SDL2 dynamically (this should be your default course of action), you need to add libSDL2.dll.a to your library directory. Then libSDL2.a will be ignored and can be removed. It should just work, no other changes are needed.
If you want to statically link SDL2, you need more linker flags. The exact flags are listed in sdl2.pc in the Libs.private section.
As of SDL 2.0.22, those are: -Wl,--dynamicbase -Wl,--nxcompat -Wl,--high-entropy-va -lm -ldinput8 -ldxguid -ldxerr8 -luser32 -lgdi32 -lwinmm -limm32 -lole32 -loleaut32 -lshell32 -lsetupapi -lversion -luuid.
Those should be added to the right of -lmingw32 -lSDL2main -lSDL2.
You also might want to add -static to statically link everything, including the standard library. (What's the point of statically linking SDL2, when your program still needs the DLLs of the standard library to work?) It also makes the linker prefer libSDL2.a to libSDL2.dll.a if both are available, meaning you don't need to worry what's in your library directory.
|
72,163,466 | 72,168,683 | Using C++ libraries in VS Code (Winsock) | I'm coding on Visual Studio for a simple UDP socket application on windows, for which I need the ws2_32.lib library.
Now, in Visual Studio I'm using
#pragma comment (lib, "ws2_32.lib")
to link the needed library.
What about moving on VS Code? How can I use that library then? Aside from the C++ extension, do I need a particular compiler?
Since the complete IDE essentially does all by itself, I'm pretty new to the problem.
Thank you in advance
| You can add properties in tasks.json in VS Code. This is the test demo DLLProject.lib
{
"tasks": [
{
...
...
"args": [
......
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}",
"DLLProject.lib"
],
.CPP
#include"DLLProject.h"
|
72,163,822 | 72,163,939 | Q: remaining 0 printed after using "\r" in C++ code | I created a program that works like a countdown and I ran into an error:
Everything is printed fine until the seconds fall (counter.second) bellow 10, then it prints 90 instead of 9 ( or 09 ), 80 instead of 8 and so on.
If I remove "\r" the "Time remaining text" will be printed the "counter" amount of times besides one another, without this error, but that would fill my cmd which is worse.
Other than that, everything works as expected.
Any ideas on how to fix this?
#include <iostream>
#include <windows.h>
int main() {
std::pair<int, int> counter;
std::pair<int, int> aux;
std::cin >> counter.first;
std::cin >> counter.second;
while (1) {
aux.first = counter.first;
aux.second = counter.second;
while (aux.first >= 0 && aux.second >= 0)
{
std::cout << "\rTime remaining: " << aux.first << ":" << aux.second << std::flush;
Sleep(1000);
if (aux.second == 0) {
aux.first--;
aux.second = 60;
}
aux.second--;
}
PlaySound(TEXT("retro.wav"), NULL, SND_ASYNC);
}
return 0;
}
| Well, take a look:
If you write
I like cats.
And then cover it with
I like dogs.
Everything's fine.
But if you cover it with
I like.
Then cats. remain uncovered.
I like.cats.
This is what happens.
You try to cover 10 with 9. The 0 remains uncovered. You can fix it with a space after that for example.
|
72,164,120 | 72,164,181 | Why is returning a const from a function not being detected as a const? | I have a program which depends on the result of std::is_same_v <const value_t, decltype(value)>. However, I have found that when functions are passed to this expression the result is unexpected, causing me bugs.
I thought that functions returning const value_t were going to be treated as being the same as const value_t, but this seems not to be the case since std::is_same_v <value_t, decltype(func())> is what returns true.
I tried returning this values using std::as_const, using static_cast, returning it from a constexpr function, but none of them worked as expected.
A minimal, reproducible example:
#include <type_traits>
#include <iostream>
inline const int x = 1;
/// A constant integer variable.
inline const int y() {return x;}
/// A constant integer function returning <x>.
int main()
{
/// <x> successfully passes as being a constant.
std::cout << std::is_same_v <const int, decltype(x)> << " ";
/// But returning it from a function (<y>) does not.
std::cout << std::is_same_v <const int, decltype(y())> << std::endl;
}
Why is this the case? How can I ensure that std::is_same_v <const value_t, decltype(value)> and std::is_same_v <const value_t, decltype(func())> both return true?
| y() is a prvalue expression. The type of this expression is not const int, but int.
This is because the type of prvalue non-class non-array expressions have their cv-qualifiers stripped.
In other words, it will work if you use a class type, but not with non-class types.
This is just how the language works. There is no difference between a const int and a int prvalue and similar for other fundamental types. They are just values for which the qualifiers aren't useful.
In contrast the expression x is a lvalue, not a prvalue, and therefore the cv-qualifier is not stripped. There is a difference between referring to an object via const-qualified and non-const-qualified lvalue.
But even then decltype applied directly to an non-parenthesized name doesn't actually consider the type of the expression anyway, but instead considers the type of the declaration of the named entity. This is a special case. decltype((x)) would consider the expression type and yield const int&, adding the lvalue reference because x is a lvalue.
std::invoke_result is also specified to return the decltype of the INVOKE expression, so it will have the same issue.
You can obtain the const-qualified type from the return type of the function type. A typical approach to that is partial specialization based on the function type. Unfortunately doing this properly is quite cumbersome since a lot of specializations must be written out to cover all cases. It also won't work if y is overloaded or a generic lambda/functor.
My guess would be that e.g. boost::callable_traits::return_type is implemented that way and will yield the const-qualified int.
It produces the expected result (see https://godbolt.org/z/7fYn4q9vs):
#include <type_traits>
#include <iostream>
#include <boost/callable_traits/return_type.hpp>
inline const int x = 1;
/// A constant integer variable.
inline const int y() {return x;}
/// A constant integer function returning <x>.
int main()
{
/// <x> successfully passes as being a constant.
std::cout << std::is_same_v <const int, decltype(x)> << " ";
/// And returning it from a function (<y>) now does as well.
std::cout << std::is_same_v <const int, boost::callable_traits::return_type_t<decltype(y)>> << std::endl;
}
|
72,164,146 | 72,164,275 | Is there a way to use logical operations as templates in C++? | For example, I want to control the operator between A and B to something depending on the template I'm assigning it to (in main).
// Theoretical operation template function
template <OPERATION>
void Example(int A, int B) {
A OPERATION B;
}
int main(void) {
Example< += >(10, 20);
Example< -= >(10, 20);
Example< *= >(10, 20);
Example< |= >(10, 20);
}
I know this is not valid C++ syntax but I'm only doing this for the purpose of explanation. Is this possible? Thanks in advance.
| You could template Example on the operation, and pass the operation as a third parameter. An easy way to pass the operation is as a lambda or, as @Yksisarvinen commented above, as one of the function objects available in std::functional.
The example below works with arithmetic operators instead of logical operators (you seemed to want to use logical operators in your question's title, but arithmetic operators in your example).
[Demo]
#include <functional> // plus, minus, multiplies, divides
#include <iostream> // cout
template <typename Op>
void Example(int a, int b, Op&& op) {
std::cout << "result = " << op(a, b) << "\n";
}
int main(void) {
Example(10, 20, std::plus<int>{});
Example(10, 20, std::minus<int>{});
Example(10, 20, [](int a, int b) { return a * b; }); // or multiplies
Example(10, 20, [](int a, int b) { return a / b; }); // or divides
}
// Outputs:
//
// result = 30
// result = -10
// result = 200
// result = 0
|
72,164,254 | 72,164,520 | How to extract type list from tuple for struct/class | I want to use a static method in a class that gets a type list in the form std::tuple<T1, T2, T3,...>. Instead of working with std::tuple<...> I want to have <...>.
How to implement example struct x resulting in Ts == <T1, T2, T3,...>
template<template <typename...> typename TL, typename... Ts>
struct x {
static void test() {
// expecting Ts == <int, char, float, double> (without std::tuple<>)
std::cout << __PRETTY_FUNCTION__ << '\n';
}
};
using types = std::tuple<int, char, float, double>;
x<types>::test();
See example on godbolt
| It seems to me that you're looking for template specialization.
Something as
// declaration (not definition) for a template struct x
// receiving a single template parameter
template <typename>
struct x;
// definition for a x specialization when the template
// parameter is in the form TL<Ts...>
template<template<typename...> typename TL, typename... Ts>
struct x<TL<Ts...>> {
static constexpr void test() {
// you can use Ts... (and also TL, if you want) here
std::cout << __PRETTY_FUNCTION__ << ' ' << sizeof...(Ts) << '\n';
}
};
|
72,164,839 | 72,164,915 | Why is appending an int to a std::string undefined behavior with no compiler warning in C++? | In my code I use logging statements in order to better see what's going on. Sometimes I write code like the following:
int i = 1337;
// More stuff...
logger->info("i has the following value: " + i);
When compiled and executed in debug mode this does not print out i as expected (this is how it would work in Java/C# for example), it rather prints something garbled. In release mode however this might as well crash the entire application. What does the C++ standard say about appending ints to a std::string like I'm doing here?
Why does the compiler not warn me at all when I compile code invoking obvious undefined behavior like this? Am I missing something? I'm using Visual Studio 2022 (MSVC). The correct way to do the logging statement would be converting the int to a std::string explicitly:
logger->info("i has the following value: " + std::to_string(i));
However this bug easily slips through during development. My warning level is set to Level4 (/W4).
| The problem is that in
logger->info("i has the following value: " + i);
you are not working with std::string. You are adding an int to a string literal, ie a const char[] array. The const char[] decays into a const char* pointer in certain contexts. In this case, the int advances that pointer forward by 1337 characters, which is way beyond the end of the string literal, and therefore undefined behavior.
You should get a better compiler that warns you about this, ie:
foo.cc:7:42: warning: offset ‘1337’ outside bounds of constant string [-Warray-bounds]
7 | foo("i has the following value: " + i);
| ^
You can use a std::string literal like this:
#include <string>
using namespace std::literals;
void foo(std::string);
void bla() {
int i = 1337;
foo("i has the following value: "s + i);
}
and then you get a "nicer" error that "std::string + int" isn't a thing in C++:
foo.cc:8:40: error: no match for ‘operator+’ (operand types are ‘std::__cxx11::basic_string<char>’ and ‘int’)
8 | foo("i has the following value: "s + i);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^ ~
| | |
| std::__cxx11::basic_string<char> int
...
going on for 147 lines
After this, it should be obvious that what you want is this instead:
logger->info("i has the following value: "s + std::to_string(i));
Using std::string literals avoids mistakes like this, because it turns warnings (which your compiler doesn't even give) into hard errors, forcing you to write correct code. So I recommend using the s suffix for all strings.
|
72,164,964 | 72,165,021 | Vector as value in JSON (C++/nlohmann::json) | I want to have something like that:
{ "rooms": [ "room1", "room2", "room3", etc ] }
I have an std::vector<std::string> of the name of the rooms, and I would like to convert it so the key of the JSON will be 'rooms', and its value will be a list of all the rooms.
For conclusion,
How to convert a std::vector to JSON array as a value (not a key).
Thanks for the helpers! :)
| You can create a Json array directly from the std::vector<std::string> so something like this will work:
#include <nlohmann/json.hpp>
#include <iostream>
#include <string>
#include <vector>
using json = nlohmann::json;
int main() {
std::vector<std::string> rooms{
"room1",
"room2",
"room3",
};
json j;
// key `rooms` and create the json array from the vector:
j["rooms"] = rooms;
std::cout << j << '\n';
}
Output
{"rooms":["room1","room2","room3"]}
|
72,165,365 | 72,165,416 | All instances of a class share the same values | I've got a class called Data, whenever I declare a new instance of this class and change something in it, it changes all instances of that class. I'm not sure how to fix this, or why it is even happening.
(Note, I've stripped back a lot of what was in my data class, but this example still produces the error)
Data.h
#include <chrono>
volatile class Data{
public:
volatile struct Ts{
volatile int64_t unixTimestamp;
};
int ReturnTimestamp() volatile;
void SetTimestamp(int) volatile;
};
Data.cpp
#include "data.h"
#include <ctime>
volatile Data::Ts data;
int Data::ReturnTimestamp() volatile{
return data.unixTimestamp;
}
void Data::SetTimestamp(int timestamp) volatile{
data.unixTimestamp = timestamp;
}
In main I run
int main() {
Data d1;
Data d2;
Data d3;
d1.SetTimestamp(1);
d2.SetTimestamp(2);
d3.SetTimestamp(3);
printf("%i %i %i\n", d1.ReturnTimestamp(), d2.ReturnTimestamp(), d3.ReturnTimestamp());
return 0;
}
The output is
3 3 3
I want the output to be
1 2 3
Why is it not "1 2 3" ?
| data is not defined in the class, so you create a global variable. Create a member variable.
class Data{
public:
struct Ts{
volatile int64_t unixTimestamp;
} data;
int ReturnTimestamp() volatile;
void SetTimestamp(int) volatile;
};
instead of volatile Data::Ts data;
|
72,165,736 | 72,165,894 | How can I load an image in C++ using SFML library? | How can I load an image in C++ using SFML library?
I am making a game using C++, and for textures of bonuses I want to upload *.png from directory instead of creating them in *.cpp file. How can I do this using SFML library?
| Try something like:
sf::Texture texture;
if (!texture.loadFromFile("path/to/myTexture.png")) {
perror("Couldn't load texture \"myTexture\".");
return;
}
You can then put it on spirte:
sf::Sprite sprite;
sprite.setTexture(texture);
and finally display it:
sprite.setPosition(x,y);
window.draw(sprite);
|
72,165,914 | 72,166,047 | How do I create a program that replaces the CODE to VALUE? | I just wanted to help with my code
here's my questions
How can I input "computer" in any in any order and case insensitively and still get the correct output?
Here are the replacement
COMPUTERS.X
1234567890.X
If I input other letters that is not included in the COMPUTERS.X the program will terminate and ask again if i should input again.
example:
Input Code: Most.x
UNABLE TO CONVERT YOUR INPUT
INPUT AGAIN? Type YES to input again, type NO to end program:
Is there any way or method to replace the whole string array instead of
replace(CODES.begin(),CODES.end(),'C','1');
here's my code
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
string CODES;
char choice[5];
do
{
cout << "Input code: ";
cin >> CODES;
replace(CODES.begin(),CODES.end(),'C','1');
replace(CODES.begin(),CODES.end(),'O','2');
replace(CODES.begin(),CODES.end(),'M','3');
replace(CODES.begin(),CODES.end(),'P','4');
replace(CODES.begin(),CODES.end(),'U','5');
replace(CODES.begin(),CODES.end(),'T','6');
replace(CODES.begin(),CODES.end(),'E','7');
replace(CODES.begin(),CODES.end(),'R','8');
replace(CODES.begin(),CODES.end(),'S','9');
replace(CODES.begin(),CODES.end(),'X','0');
replace(CODES.begin(),CODES.end(),'c','1');
replace(CODES.begin(),CODES.end(),'o','2');
replace(CODES.begin(),CODES.end(),'m','3');
replace(CODES.begin(),CODES.end(),'p','4');
replace(CODES.begin(),CODES.end(),'u','5');
replace(CODES.begin(),CODES.end(),'t','6');
replace(CODES.begin(),CODES.end(),'e','7');
replace(CODES.begin(),CODES.end(),'r','8');
replace(CODES.begin(),CODES.end(),'s','9');
replace(CODES.begin(),CODES.end(),'x','0');
cout << "Value: " << CODES << endl;
cout << "Do you want to enter another code? (Y/N) ";
cin >> choice;
}
while(strcmpi(choice, 'yes') == 0 ||strcmpi(choice, 'y') == 0 );
{
if (strcmpi(choice, 'no') == 0 || strcpmi(choice, 'no' == 0);
{
cout << "Program terminate";
}
}
return 0;
}
any help will be appreciated, thank you very much
ps. i prefer classic c++
| Use a array to save convert rules. And both convert to upper to ignore case.
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
bool encode(string& old, const char* replace_rules[]) {
int i = 0;
int replaced = 0;
while (replace_rules[0][i] != '\0') {
for (int j = 0; j < old.size(); j++) {
// convert to upper case
if (old[j] >= 'a' && old[j] <= 'z') {
old[j] = old[j] - 'a' + 'A';
}
if (old[j] == replace_rules[0][i]) {
old[j] = replace_rules[1][i];
replaced++;
}
}
i++;
}
if (replaced != old.size()) {
cout << "UNABLE TO CONVERT YOUR INPUT" << endl;
return false;
}
return true;
}
int main() {
string codes;
string choice;
const char* replace_rules[2] = {"COMPUTERSX", "1234567890"};
do {
cout << "Input code: ";
cin >> codes;
if (encode(codes, replace_rules)) {
cout << "Value: " << codes << endl;
}
cout << "Do you want to enter another code? (Y/N) ";
cin >> choice;
} while (choice == "Y" || choice == "y");
cout << "Program terminate";
return 0;
}
Result:
Input code: comPutErSspxX
Value: 1234567899400
|
72,166,085 | 72,166,327 | Why does std::is_invocable_r reject functions returning non-moveable types? | I'm curious about the definition of std::is_invocable_r and how it interacts with non-moveable types. Its libc++ implementation under clang in C++20 mode seems to be wrong based on my understanding of the language rules it's supposed to emulate, so I'm wondering what's incorrect about my understanding.
Say we have a type that can't be move- or copy-constructed, and a function that returns it:
struct CantMove {
CantMove() = default;
CantMove(CantMove&&) = delete;
};
static_assert(!std::is_move_constructible_v<CantMove>);
static_assert(!std::is_copy_constructible_v<CantMove>);
CantMove MakeCantMove() { return CantMove(); }
Then it's possible to call that function to initialize a CantMove object (I believe due to the copy elision rules):
CantMove cant_move = MakeCantMove();
And the type traits agree that the function is invocable and returns CantMove:
using F = decltype(MakeCantMove);
static_assert(std::is_invocable_v<F>);
static_assert(std::is_same_v<CantMove, std::invoke_result_t<F>>);
But std::is_invocable_r says it's not possible to invoke it to yield something convertible to CantMove, at least in C++20 under clang:
static_assert(!std::is_invocable_r_v<CantMove, F>);
The definition of std::is_invocable_r is
The expression INVOKE<R>(declval<Fn>(), declval<ArgTypes>()...) is well-formed when treated as an unevaluated operand
with INVOKE<R> being defined as
Define INVOKE<R>(f, t1, t2, …, tN) as [...] INVOKE(f, t1, t2, …, tN) implicitly converted to R.
and INVOKE defined (in this case) as simply MakeCantMove(). But the definition of whether an implicit conversion is possible says:
An expression E can be implicitly converted to a type T if and only if the declaration T t=E; is well-formed, for some invented temporary variable t ([dcl.init]).
But we saw above that CantMove cant_move = MakeCantMove(); is accepted by the compiler. So is clang wrong about accepting this initialization, or is the implementation of std::is_invocable_r_v wrong? Or is my reading of the standard wrong?
For the record, the reason I care about this question is that types like std::move_only_function (I'm using an advanced port to C++20 of this) have their members' overload sets restricted by std::is_invocable_r_v, and I'm finding that it's not possible to usefully work with functions that return a no-move type like this. Is that by design, and if so why?
|
So is clang wrong about accepting this initialization, or is the
implementation of std::is_invocable_r_v wrong?
This is a bug of libc++. In the implementation of is_invocable_r, it uses is_convertible to determine whether the result can be implicitly converted to T, which is incorrect since is_convertible_v<T, T> is false for non-movable types, in which case std::declval adds an rvalue reference to T.
It is worth noting that both libstdc++ and MSVC-STL have bug reports about this issue, which have been fixed.
|
72,166,104 | 72,166,168 | I want to use cout more comfortably |
I want to use cout to print out this sentence: "You can build piramid which floor is only odd. not even", but I want to do it more comfortably. Just like the way below. But, when I use this way, an error occurs. So, is there any way to use it like this?
cout << "You can build piramid which floor is only odd.
not even" << '\n';
| Adjacent string literals will automatically be concatenated, even if they are on different lines. So you can write it this way instead:
std::cout << "You can only build pyramids whose floor is odd, "
"not even.\n";
|
72,166,189 | 72,166,247 | Issues with outputs for dynamic arrays | I'm working with a template class for dynamic arrays, and my code has compiled successfully, however my get function for a given element in the dynamic array does not seem to be working. Nothing seems to be outputted whenever I output the function, but this doesn't make sense, because my size function works fine, and shows that there is indeed something within the array, I just can't output it. Can anyone help?
#include <iostream>
using namespace std;
template <class T>
class Wrapper{
private:
T* array;
int size;
public:
Wrapper(){
array = NULL;
size = 0;
}
int returnSize(){
return size;
}
void addEntry(string input){
if(returnSize()==0){
array = new string[returnSize()+1];
array[returnSize()] = input;
size+=1;
}
else{
T* newArray = new T[returnSize()+1];
for(int i = 0; i<returnSize(); i++){
newArray[i] = array[i];
}
newArray[returnSize()] = input;
size+=1;
string *array = new string[returnSize()];
array = newArray;
}
}
bool deleteEntry(string input){
int mySize = returnSize();
string* testArray = new string[mySize];
for(int i = 0; i<mySize; i++){
if(array[i]==input){
return true;
break;
}
}
string*newArray = new string[mySize-1];
for(int i = 0; i<mySize; i++){
if(array[i]!=input){
newArray[i+=1] = array[i];
}
}
delete[]array;
array = newArray;
return true;
}
string getEntry(int input){
if(input>size){
return NULL;
}
return this->array[input];
}
void operator=(const Wrapper w){
this->size = w.returnSize();
string *newArray = new string[size];
for(int i = 0; i<size; i++){
newArray[i] = w.getEntry(i);
}
this->array = newArray;
}
~Wrapper(){
delete[] array;
}
};
int main(){
Wrapper<string> w;
w.addEntry("sam");
w.addEntry("Josh");
w.addEntry("tom");
cout<<"Here"<<endl;
cout<<w.returnSize();
for(int i = 0; i<<w.returnSize(); i++){
cout<<w.getEntry(i);
}
}
| Just to collect the findings, if you delete this line from addEntry:
string *array = new string[returnSize()];
and change your final for loop to:
for(int i = 0; i < w.returnSize(); i++){
cout<<w.getEntry(i)<<"\n";
}
then this does exactly what you expect. I've run it myself.
|
72,166,255 | 72,169,576 | When does the compiler need to compute an alias? | Consider the following code:
template <class T>
struct computation {
using type = /* something based on T that takes time to compile */;
};
Now consider two codes:
using x = computation<T>;
and:
using y = typename computation<T>::type;
I am wondering whether the standard implies that:
Option A) Any "reasonable" compiler will lead to a quick compile time for x and long compile time for y
Option B) A compiler could totally compute computation<T>::type even if only computation<T> is called, leading to long compile-time even for x
In other words, I am trying to know if the standard specifies anything that would most likely translate into option A or option B for a "reasonable" compiler implemeter. I know that the standard says nothing about compiler implementation but for example if it requires that ::type does not have to exist until it's specifically called, that would be in favor of option A.
NOTE: In my experience, I am pretty sure that g++, clang++, msvc, and intel are following option A), but I have no idea whether it's just by pure luck of it's related to something in the standard.
| I am assuming that T is an actual non-dependent type here and not another template parameter.
The line
using x = computation<T>;
does not cause implicit instantiation of computation<T>. There is therefore no reason for a compiler to try to compute type at this point, in particular since any instantiation failure would need to be ignored. The program may not fail to compile if type's computation would yield an invalid type or would otherwise fail.
The line
using y = computation<T>::type;
does require implicit instantiation of computation<T> because the scope resolution operator is applied to it. The implicit instantiation includes computation of type aliases inside computation<T>. The compiler must perform the computation, because if the computation failed or would yield an invalid type, then the program would be ill-formed and the compiler would need to diagnose it.
This doesn't actually dependent on the ::type part specifically. Even if it was ::type2 for another type alias, the implicit instantiation of the class template specialization will require computation of type.
Similarly using computation<T> in any other context requiring it to be complete will require implicit instantiation and therefore computation of type, e.g.
auto z = computation<T>{};
|
72,166,534 | 72,172,406 | Parameter pack referenced but not expanded in a using declaration: compiler bugs or not? | Consider the following code (also available here on compiler explorer)
#include <utility>
#include <type_traits>
template <std::size_t N, class = std::make_index_sequence<N>>
struct type;
template <std::size_t N, std::size_t... I>
struct type<N, std::index_sequence<I...>>
: std::integral_constant<std::size_t, I>... {
using std::integral_constant<std::size_t, I>::operator()...;
};
using x = type<4>;
For many compilers, it leads to a compiler error:
// icc 19.0.0: <source>(10): error: parameter pack "I" was referenced but not expanded
// icc 19.0.1: OK
// gcc 6.4: <source>:10:60: error: parameter packs not expanded with '...'
// gcc 7.1: OK
// clang 3.9.1: <source>:10:11: error: using declaration contains unexpanded parameter pack 'I'
// clang 4.0.0: OK
// msvc 19.22: <source>(10): error C3520: 'I': parameter pack must be expanded in this context
// msvc 19.23: OK
To me, it seems like perfectly valid c++17 code but I am surprised that it does not seem to compile on relatively recent compilers (especially for intel and msvc) (even if it compiles on all the most recent versions).
I am wondering whether:
it's completely c++17 valid code and it just took a long time for some vendors to implement it
it is not purely c++17 valid code
|
I am wondering whether:
it's completely c++17 valid code and it just took a long time for some vendors to implement it
it is not purely c++17 valid code
The code is valid but the compiler version you are listing are either very old and did not yet support this particular feature, or claimed to support this feature but contained a bug.
In general, make sure to understand the limitations of the particular version of your particular compiler. For programs diagnosed as ill-formed as the example above, it is mostly a detective exercise such as the one following below, but using old compiler versions can have far worse consequences: compiler or C++ language defects that have only been addressed in later versions of the compiler.
See details below.
What particular C++17 feature is "the culprit"?
using std::integral_constant<std::size_t, I>::operator()...;
This is a pack expansion in a using-declaration, which was included in C++17 as:
P0195R2: Pack expansions in using-declarations
C++17 standards support in various compilers
GCC
// gcc 6.4: <source>:10:60: error: parameter packs not expanded with '...'
// gcc 7.1: OK
From C++ Standards Support in GCC - C++17 Support in GCC:
P0195R2 was implemented for GCC 7.
Thus, it is expected that your program will not compile for GCC 6.4, as feature was not yet implemented in that GCC version.
Clang
// clang 3.9.1: <source>:10:11: error: using declaration contains unexpanded parameter pack 'I'
// clang 4.0.0: OK
From C++ Support in Clang - C++17 implementation status:
P0195R2 was implemented for Clang 4.
Thus, as above, we cannot expect your program to compile for Clang < 4.
MSVC
// msvc 19.22: <source>(10): error C3520: 'I': parameter pack must be expanded in this context
// msvc 19.23: OK
From Microsoft C/C++ language conformance by Visual Studio version:
P0195R2 was claimed to have been (fully) implemented for VS 2017 15.7.
However the failure of MSVC 19.22 to compile your program is a bug:
Variadic templates: invalid parameter pack context
Flagged to have been fixed in VS16.3/MSVC 19.23
|
72,166,606 | 72,166,664 | How to make data from a text file be filtered into a vector | I have a little program I don't know how to make. Basically, it is a function to create a vector with data from a text file that meets a parameter in its text.
text_in_vector("file.txt", "10")
text example:
Karen10, Lili12, Stacy13, Mack10
vector results
{"Karen10","Mack10"}
| Try something like this:
#include <fstream>
#include <vector>
#include <string>
#include <iomanip>
std::vector<std::string> text_in_vector(const std::string &fileName, const std::string &searchStr)
{
std::vector<std::string> vec;
std::ifstream inFile(fileName);
std::string str;
while (std::getline(inFile >> std::ws, str, ','))
{
if (str.find(searchStr) != std::string::npos)
vec.push_back(str);
}
return vec;
}
Online Demo
|
72,166,696 | 72,167,112 | Using "string_view" to represent the "string" key | When I use map<string, string> kv; in protobuf 3.8.0, the next code works:
std::string_view key("key");
kv[key] = "value";
While in protobuf 3.19.4, the above code doesn't work.
The error msg is:
error: no match for 'operator[]' (operand types are 'google::protobuf::Map<std::__cxx11::basic_string
, std::__cxx11::basic_string>' and 'std::string_view' {aka 'std::basic_string_view'})
| In 3.8.0, Map::operator[] is declared as:
Value& operator[](const Key& k)
Where, in your case, Key is std::string. std::string_view is convertible to std::string, which is why the code works in 3.8.0.
In 3.19.4, Map::operator[] is declared as:
template <typename K = key_type>
T& operator[](const key_arg<K>& key)
template <
typename K = key_type,
// Disable for integral types to reduce code bloat.
typename = typename std::enable_if<!std::is_integral<K>::value>::type>
T& operator[](key_arg<K>&& key)
Where key_arg is declared as:
template <typename LookupKey>
using key_arg = typename internal::TransparentSupport<key_type>::template key_arg<LookupKey>;
And, in your case, key_type is std::string. std::string_view is not convertible to TransparentSupport::key_arg, which is why the code doesn't work in 3.19.4.
|
72,166,787 | 72,271,356 | Why there is no implicit conversions to pointers of member functions | When used std::bind, I found & is necessary to get the address of member functions, while isn't necessary for regular functions, for example:
class Obj{
public:
void member_func(int val);
};
void func(int val);
int main(){
Obj obj;
auto mf1 = std::bind(&Obj::member_func, &obj, 1); // ok
auto mf2 = std::bind(Obj::member_func, &obj, 1); // error
auto f1 = std::bind(&func, 1); // ok
auto f2 = std::bind(func, 1); // ok
}
And after STFW(Search The Friendly Web :) ), I found this in cpp reference
An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.
Which explains why & is necessary for member functions, but I still don't fully understand why there is no implicit conversions to pointers of member functions?
In particular, what does "lvalues that refer to non-static member functions do not exist" mean?
And "lvalue of function type" also confuses me, does that mean the function designator func is an lvalue?
First time to ask question, hope I clearly explained my question.
|
I still don't fully understand why there is no implicit conversions to pointers of member functions.
It's primarily to stop you making mistakes like this:
if (MyClass::MyFunc) ... // oops! would always be true, if legal
when you meant to type:
if (MyClass::MyFunc ()) ...
// ^^
And that's a Good Thing (tm).
But that begs the question, why don't things work the same way for regular functions? After all, it's perfectly legal (but, as in the example above, totally meaningless) to write:
if (MyNonMemberFunc) ... // oops! always true, rats!
And this is a throwback to C, where function names decay to pointers when you leave the brackets off. That has value, but overall I think most people would prefer correctness to having to add a leading & when that is the intention.
So it's a bit unfortunate that we have different rules for member and non-member functions, but the standards committee obviously wanted to fix this particular booby trap for member functions but couldn't for non-member functions, in order to maintain backwards compatibility. And to be fair, most modern compilers do warn you if you write if (MyNonMemberFunc) so we're not in such a bad place with this, all things considered.
|
72,166,814 | 72,166,900 | How to return an error message from a fuction? | I have a function in a C++ code which should return a certain type of data (vector in this case, I have the definition typedef Eigen::VectorXd vector from the eigen library) but I have a condition where, if one of the parameters of the fuction is not valid to the kind of data I'm managing, that function should return an error message, I tried
else {cout << "the error message\n"}
With an if-else statement, but, since it does not return a vector but the print in terminal, the compiler is giving me the warning X control may reach end of non-void function every time I compile and it's kinda annoying having that message, Do you have you any idea to get rid that warning? Thank you in advance.
P.S: The code is working, I just want to fix that warning, if you need the implementation of the function please ask for it
| Usually you handle this kind of errors by throwing an exception.
here an example:
Eigen::VectorXd Foo(int p1, int p2)
{
.....
if (!IsParamsValid(p1,p2))
{
throw std::invalid_argument("p1 or p2 is invalid");
}
.....
}
|
72,166,859 | 72,208,434 | Errors linking to tdh.lib | I'm trying to use functions from the Microsoft TDH library building with Visual Studio 2019. The project is using WindowsApplicationForDrivers10.0 Platform Toolset and the program is very simple:
#include <windows.h>
#include <tdh.h>
#pragma comment(lib, "tdh.lib")
int __cdecl wmain(_In_ int argc, _In_ wchar_t* argv[]) {
::TdhCloseDecodingHandle(nullptr);
return 0;
}
When building the program I'm getting the following error:
Build started...
1>------ Build started: Project: main, Configuration: Debug x64 ------
1>Building 'main' with toolset 'WindowsApplicationForDrivers10.0' and
the 'Universal' target platform.
1>main.cpp
1>main.vcxproj -> C:\Play\wpp\cpp\x64\Debug\main.exe
1>ApiValidation : error : main.exe has unsupported API call to
"tdh.dll!TdhCloseDecodingHandle"
1>C:\Program Files (x86)\Windows
Kits\10\build\WindowsDriver.common.targets(1794,5): error MSB3721: The
command ""C:\Program Files (x86)\Windows
Kits\10\bin\10.0.19041.0\x64\ApiValidator.exe"
-DriverPackagePath:C:\Play\wpp\cpp\ctrl..\x64\Debug\main.exe -SupportedApiXmlFiles:"C:\Program Files (x86)\Windows Kits\10\build\universalDDIs\x64\UniversalDDIs.xml"
-ModuleWhiteListXmlFiles:"C:\Program Files (x86)\Windows Kits\10\build\universalDDIs\x64\ModuleWhiteList.xml"
-ApiExtractorExePath:"C:\Program Files (x86)\Windows Kits\10\bin\10.0.19041.0\x64"" exited with code -1.
1>Done building project "main.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Does anyone knows what the problem is or how to prevent ApiValidator.exe form running as part of the build?
Thanks in advance,
-Uri
| Finally found the Visual Studio settings:
|
72,166,886 | 72,167,085 | Preventing the timer from updating the counter variable for more than once | I have a qt application with cpp. The application is Falling ball game, when the ball is catched by basket the score needs to be incremented.
The application uses some timerEvent to update the score. The slot for timeout is called for every 10 msec. My problem is the score is updated more than once and
is very random in its incrementation. How can I solve this problem.
MainWindow.cpp
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug() <<"mainWindow constructor";
basket = new Basket(this);
sprite = new Sprite(this);
timer=new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::onTimer);
timer->start(3000);
scoreTimer=new QTimer(this);
connect(scoreTimer, &QTimer::timeout, this, &MainWindow::onScoreTimer);
scoreTimer->start(10);
timerIdForScoreTimer=scoreTimer->timerId();
score = 0;
}
MainWindow::~MainWindow()
{
qDebug() <<"mainWindow destructor";
delete ui;
}
void MainWindow::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.fillRect(rect(), QBrush(QColor(Qt::white)));
painter.setPen(Qt::black);
painter.setBrush(QBrush(QColor(Qt::darkBlue)));
emit draw(painter);
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if(event->key() == Qt::Key_Right)
{
emit move(1);
}
if(event->key() == Qt::Key_Left)
{
emit move(0);
}
}
void MainWindow::on_actionStart_triggered()
{
connect(this, &MainWindow::draw, sprite, &Sprite::drawBall);
connect(this, &MainWindow::draw, basket, &Basket::drawBar);
connect(this, &MainWindow::move, basket, &Basket::move);
}
void MainWindow::onTimer()
{
std::cout << "Tick!-----------------------------------------------------------------------------" << std::endl;
sprite = new Sprite(this);
connect(this, &MainWindow::draw, sprite, &Sprite::drawBall);
}
void MainWindow::onScoreTimer()
{
// qDebug() <<"Timer event called in Mainwindow.cpp";
if( (((sprite->y - 15) >= 500)&& sprite->y <530 ) && ( (sprite->x <= (basket->x1 + 80)) && (sprite->x >= (basket->x1 - 80)) ) )
{
// qDebug("x and y position when condition is met and also x1 and y1");
// qDebug()<<x;
// qDebug()<<y;
// qDebug()<<x1;
// qDebug()<<y1;
sprite->dy *= -1;
sprite->dx *= -1;
qDebug() << "score update";
qDebug() <<score;
score ++;
// ui->lcdNumber->setDigitCount(score);
ui->score_label->setText(QVariant(score).toString());
}
}
In MainWindow::onScoreTimer() the "score" variable is incremented randomly and more than once. How can I prevent this.
| So with all the debugging cruft removed, onScoreTimer() looks like this:
void MainWindow::onScoreTimer()
{
if( (((sprite->y - 15) >= 500)&& sprite->y <530 ) && ( (sprite->x <= (basket->x1 + 80)) && (sprite->x >= (basket->x1 - 80)) ) )
{
sprite->dy *= -1;
sprite->dx *= -1;
score++;
ui->score_label->setText(QVariant(score).toString());
}
}
It reverses the sprite's direction, increments the score, and updates the score_label. All well and good, but note that what it doesn't do is anything that would prevent that same if-test (at the top of the method) from succeeding again the next time onScoreTimer() is called.
Therefore, it's entirely likely that when the sprite reaches the target area, onScoreTimer() (which is called every 10mS) will do all of the above many times in a row, changing the sprite's direction every time, and increasing the score quite a bit as the sprite vibrates back-and-forth.
As for how to avoid that behavior, I can think of two possible solutions:
Along with what you're doing inside the above block of code, also change sprite->x and sprite->y to some location outside of the target-area, so that the next call to onScoreTimer won't trigger the same routine again.
or
Add a boolean member-variable to track the current in-target/not-in-target state of the sprite, and only run the routine when that variable's state changes from false to true
e.g.:
class MainWindow {
[...]
private:
bool spriteWasInTarget = false;
};
void MainWindow::onScoreTimer()
{
const bool spriteIsInTarget = ( (((sprite->y - 15) >= 500)&& sprite->y <530 ) && ( (sprite->x <= (basket->x1 + 80)) && (sprite->x >= (basket->x1 - 80)) ) );
if ((spriteIsInTarget)&&(!spriteWasInTarget))
{
sprite->dy *= -1;
sprite->dx *= -1;
score++;
ui->score_label->setText(QVariant(score).toString());
}
spriteWasInTarget = spriteIsInTarget;
}
... so that way the routine only executes on the first call after the sprite (re)enters the target-area.
|
72,166,923 | 72,168,379 | C++ Linked List Queue pointers causing undefined behavior | I've read the questions and not seen answer to mine.
Most people use structs for these and after testing reference code I see the struct version is functional but, why is class version not?
#include <iostream>
using namespace std;
// I'm still bad at pointer logic but it makes sense.
// REFERENCES
// https://www.geeksforgeeks.org/queue-linked-list-implementation/
// stack linked list assignment earlier in semester
// https://stackoverflow.com/questions/29787026/c-queue-from-linked-list
class Node {
public:
int data;
Node *next; // controls flow of nodes
};
class Queue {
public:
Queue();
~Queue();
void enQueue(int data);
void deQueue();
bool isEmpty();
//private: all set to public because I don't want to make a print function
Node *front;
Node *rear;
int counter;
};
Queue::Queue()
{
front = NULL;
rear = NULL;
}
Queue::~Queue() {
if (rear == NULL && front == NULL)
{
cout << "Nothing to clean up!" << endl;
}
else
{
cout << "Delete should be happening now...";
}
}
void Queue::enQueue(int data) {
// create new node of queue structure
Node *temp = new Node;
temp->data = data;
// write like this line below if not temp->data = data;
// Node *temp = new Node(data);
// if the queue is empty, first node.
if (rear == NULL)
{
front = temp;
rear = temp;
return;
}
// assign data of queue structure
rear->next = temp; // point rear pointer to next pointer = assign to temp
rear = temp; // assign rear to temp keep front pointer at beginning fifo
}
void Queue::deQueue()
{
// if queue is empty, return NULL
if (front == NULL)
{
cout << "Queue is empty, sorry!";
return;
}
Node* temp = front; // assign front
//problem here
front = front->next; // move front one node ahead
if(front == NULL)
{
rear = NULL;
}
delete (temp);
return;
}
bool Queue::isEmpty()
{
// cout << "functions";
// cout << endl;
return (front == NULL && rear == NULL);
}
int main()
{
Queue yay;
yay.isEmpty();
yay.deQueue();
cout << endl;
yay.enQueue(5);
yay.enQueue(6);
cout << "Queue Front : " << (yay.front)->data << endl;
yay.deQueue();
cout << "After deqQueue " << endl;
cout << "Queue Front : " << (yay.front)->data << endl;
yay.deQueue();
cout << "Queue Front : " << (yay.front)->data << endl;
yay.deQueue(); // <- Problem here
yay.deQueue();
cout << "completed" << endl;
}
I've isolated the problem to line 90
//problem here
front = front->next; // move front one node ahead
it causes this code in int main() to not print
yay.deQueue(); // <- Problem here
yay.deQueue();
cout << "completed" << endl;
I know I am weak at pointer directing and so forth, so if could please tell me what I am not seeing would be appreciated, I've been poking at it for a while now and did not resolve.
This link for code through online gdb
https://onlinegdb.com/0B0KzcHMa
This is the output with line
Queue is empty, sorry!
Queue Front : 5
After deQueue
Queue Front : 6
And the output with line 90 and 96 commented out //96 commented to avoid double free
Queue is empty, sorry!
Queue Front : 5
After deQueue
Queue Front : 5
Queue Front : 5
completed
Delete should be happening now...
Now I know, I know I should be better at this traversal of nodes business
but, I am not seeing it and this may help me remember it in the future :X
I believe its a simple fix but, everything I try reaches the former output
rather than the later with intended data represented, I believe it is
nexting out into random memory making memory leak or memory pointing wherever
thus it never goes back to main to complete terminal messages
| The problem is here:
Queue yay;
yay.isEmpty();
yay.deQueue();
cout << endl;
yay.enQueue(5);
yay.enQueue(6);
cout << "Queue Front : " << (yay.front)->data << endl;
yay.deQueue();
cout << "After deqQueue " << endl;
cout << "Queue Front : " << (yay.front)->data << endl;
yay.deQueue();
cout << "Queue Front : " << (yay.front)->data << endl; // <<==== HERE
The queue had two elements, 5 and 6, inserted. Then one was popped, then the other. That means yay.front is now nullptr per your deQueue logic reading the end of the list. Therefore, reading (yay.front)->data invoke undefined behavior by dereferencing an invalid pointer (in this case a pointer containing nullptr).
Lose that dereference (one way or another) and the code shouldn't fault any longer.
|
72,166,934 | 72,172,082 | mmap's worst case memory usage when using MAP_PRIVATE vs MAP_SHARED | I haven't seen this explicitly anywhere so I just wanted to clarify. This is all in the context of a single threaded program: say we have a 10GB text file when we open with mmap, using the MAP_PRIVATE option. Initially of course, I should expect to see 0GB resident memory used. Now say I modify every character in the file. Will this then require 10GB in resident memory? And if not, why not?
Now what if we did the same thing but with MAP_SHARED, what should I expect the resident memory usage to look like?
| MAP_SHARED creates a mapping that is backed by the original file. Any changes to the data are written back to that file (assuming a read/write mapping).
MAP_PRIVATE creates a mapping that is backed by the original file for reads only. If you change bytes in the mapping, then the OS creates a new page that is occupies physical memory and is backed by swap (if any).
The impact on resident set size is not dependent on the mapping type: pages will be in your resident set if they're actively accessed (read or write). If the OS needs physical memory, then pages that are not actively accessed are dropped (if clean), or written to either the original file or swap (if dirty, and depending on mapping type).
Where the two types differ is in total commitment against physical memory and swap. A shared mapping doesn't increase this commitment, a private mapping does. If you don't have enough combined memory and swap to hold every page of the private mapping, and you write to every page, then you (or possibly some other process) will be killed by the out-of-memory daemon.
Update: what I wrote above applies to memory-mapped files. You can map an anonymous block (MAP_ANONYMOUS) with MAP_SHARED, in which case the memory is backed by swap, not a file.
|
72,167,059 | 72,167,327 | Are pointers to non-static member function "formally" not considered pointers | I came across this which states:
Member function pointers are not pointers. Pointers to non-member functions, including static member functions, are pointers.
The above quote seems to suggest that pointers to non-static member function are not pointers.
Similarly, i read here:
A member pointer is a different type category from a ordinary pointer.
My question is that are the above quotes technically(formally according to the standard) correct? I mean we use the term, "pointer" to non-static member function. But if they are not actually pointers then why use the term "pointers" in the first place? My understanding is that it is because although "pointer to member functions" differ in many respect with ordinary pointers they still are similar to ordinary pointers in one respect which is that they point to something(meaning hold addresses).
I also tried:
std::cout<<std::is_pointer_v<void(A::*)()><<std::endl;
which gives 0 confirming that a pointer to non-static member function is not considered a pointer.
| The quoted statements in question seems to be validated by the following statements from the standard.
From dcl.mptr#3's note:
[ Note: See also [expr.unary] and [expr.mptr.oper]. The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer declarator syntax. There is no “reference-to-member” type in C++. — end note ]
And from basic.compound#3:
...Except for pointers to static members, text referring to “pointers” does not apply to pointers to members...
|
72,168,300 | 72,168,439 | Is there still a need to provide default constructors to use STL containers? | I remember that back in C++98, if you wanted to make an STL container of MyClass, you needed to provide default constructor to MyClass.
Was this specific to some implementations of STL? or was it mandated by the standard?
Q: Is this not necessary anymore?
Because it is not a good practice to provide default constructors when it makes no sense to have one...
Of course, I am not talking about the calls like
vector<MyClass> v(6);
where you explicitly request that 6 default-initialized objects are to be created...
| This quote is from the C++ Programming Language, Special edition , 2005 by Bjarne Stroustrup in section 16.3.4:
If a type does not have a default constructor, it is not possible to create a vector with elements of that type, without explicitly providing the value of each element.
So it was indeed a standard requirement. It was also required that (section 17.1.4) :
To be an element of a container, an object must be of a type that allows the container implementation to copy it. The container may copy it using a copy constructor or an assignment; in either case the result of the copy must be an equivalent object.
So yes, there were "official" constructor requirementsand the library implementation were supposed to be interchangeable and not add other requirements. (Already in the very first proposal for STL in 1995, the authors tried as much as possible to clearly indicate specifications and narrow down the implementation dependent flexibility.)
You therefore had to provide a default constructor in the case where you declared other constructors:
If a user has declared a default constructor, that one will be used; otherwise, the compiler will try to generate one if needed and if the user hasn't declared other constructors.
Nowadays, this requirement is relaxed. Since C++11:
The requirements that are imposed on the elements depend on the actual operations performed on the container.
So you can define a vector for a class without default constructor, if it doesn't make sense. This for example perfectly works (online demo):
class MyClass {
public:
MyClass(int x) {}
};
int main() {
vector<MyClass> v;
MyClass test{1};
v.push_back(test);
}
But it works only as long as you don't use any operation that would need the default constructor. For instance v.resize(6); would fail to compile.
|
72,168,537 | 72,168,838 | C++, template class as function's return type problem | static absl::StatusOr<ImageFrame> ReadTextureFromFile() {
ImageFrame image_frame(width, height);
return image_frame;
}
Why return type is ImageFrame, not absl::StatusOr ?
| This is just a "syntactic sugar". The return type is abseil::StatusOr<ImageFrame>. abseil::StatusOr<T> allows you to return both abseil::Status and the type T from your function. When there is an error you can directly return the error status. On success, you return the object with type T.
So you could also write something like that:
static absl::StatusOr<ImageFrame> ReadTextureFromFile() {
try {
ImageFrame image_frame(width, height);
}
catch{
return absl::AbortedError("Could not create image frame.");
}
return image_frame;
}
When you call this function, you need to check if everything went smooth.
auto image_frame_or = ReadTextureFromField();
ImageFrame image_frame;
if (image_frame_or.ok()){
image_frame = image_frame_or.value();
}
|
72,168,834 | 72,168,855 | How can I make a std::vector of function pointers? | I have seen some similar questions but I can't get this to work.
This fails:
std::vector<void (CChristianLifeMinistryEntry::* pfnSetAssignName)(CString)> = xx;
I want a vector so that I can pre-fill it with a series of &CChristianLifeMinistryEntry::SetXXX functions. This is so that I can quickly determine the right function to use in a for loop I have.
| std::vector<void (CChristianLifeMinistryEntry::*)(CString)> pfnSetAssignName = xx;
|
72,169,038 | 72,169,103 | QInputDialog with suffix | I'm getting double value quickly from user with QInputDialog. Actually, everything is fine just wondering if there is a way to write suffix next to this value.
My code:
double value = QInputDialog::getDouble(this,
tr("Change World Box Size"),
tr("Set each axis length:"),
projectJson.value("worldBox").toObject()["length"].toString().toDouble(),
0,
10000,
2,
&isOK,
Qt::Dialog,
0.1);
| That seems to work;
auto dialog = new QInputDialog(this);
dialog->setWindowTitle("Change World Box Size");
dialog->setLabelText("Set each axis length:");
dialog->setDoubleDecimals(2);
dialog->setDoubleMaximum(10000);
dialog->setDoubleMinimum(0);
dialog->setDoubleValue(projectJson.value("worldBox").toObject()["length"].toString().toDouble());
auto doubleEdit = dialog->findChild<QDoubleSpinBox *>();
doubleEdit->setSingleStep(0.1);
doubleEdit->setSuffix(" mm");
if (dialog->exec() == QDialog::Accepted) {
m_worldBoxGenerator->generate(dialog->doubleValue());
}
|
72,170,102 | 72,171,177 | Cast an array of strings to an array of char* | I'm trying to get rid of the ISO C++ forbids converting a string constant to ‘char*’ warning, my code looks like the following:
char* var[] = {"abc", "def"};
// many more lines like this ...
One solution is to prepend each string literal with (char*) however that's ugly and unmaintainable. Ideally I'd like to be able to edit these lines to say
char* var[] = array_cast<char*>({"abc", "def"});
I found a solution here for almost the same problem except it deals with std::array instead of plain C arrays and array variables rather than initializer lists.
I want to avoid using std::array, std::string, const char*, std::vector since the functions that eventually get called accept non-const char**.
| I have arrived at a solution. It requires two arrays one of which needs to be cleaned up afterwards so it can surely be improved.
template<size_t N, size_t... Is>
constexpr char**
array_cast(const std::array<const char*, N>& arr, std::index_sequence<Is...>)
{
return new char*[]{const_cast<char*>(std::get<Is>(arr))...};
}
template<size_t N>
constexpr char**
array_cast(const std::array<const char*, N>& arr)
{
return array_cast(arr, std::make_index_sequence<N>());
}
const std::array var {"abc", "def"};
char** result = array_cast(var);
|
72,170,302 | 72,171,164 | Does constexpr really imply const? | Compare the following:
I have a static member in a class that is either const constexpr or just constexpr. According to this explanation on MS Docs constexpr implies constness:
All constexpr variables are const.
However, this issues a warning in gcc 8.4:
#include <iostream>
#include <string>
struct some_struct
{
static constexpr char* TAG = "hello";
void member() {
printf("printing the tag %s", TAG);
}
};
int main()
{
some_struct A;
A.member();
}
While this doesn't:
#include <iostream>
#include <string>
struct some_struct
{
static const constexpr char* TAG = "hello";
void member() {
printf("printing the tag %s", TAG);
}
};
int main()
{
some_struct A;
A.member();
}
Try it in CompilerExplorer.
What is the difference?
|
Does constexpr really imply const?
Yes. Constexpr variables are always const.
What is the difference?
const T* is a non-const pointer to const. It is not const.
T* const is a const pointer to non-const. It is const.
const T* const is a const pointer to const. It is const.
constexpr T* is a const pointer to non-const. It is const by virtue of being constexpr.
const constexpr T* is a const pointer to const. It is const by virtue of being constexpr.
String literals are arrays of const char, and they don't implicitly convert to a pointer to non-const char (since C++11).
|
72,170,444 | 72,170,708 | Why is there a signedness issue when comparing uint16_t and unsigned int? | I have a code like this :
#include <iostream>
using std::cout;
using std::endl;
int main() {
uint16_t a = 0;
uint16_t b = 0;
if ( a - b < 3u )
{
cout << "cacahuète" << endl;
}
return 0;
}
When I compile it using g++ with -Wall, I get :
temp.cpp: In function ‘int main()’:
temp.cpp:9:13: warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Wsign-compare]
9 | if ( a - b < 3u )
| ~~~~~~^~~~
That warning doesn't show up if I write if ( a - b < static_cast<uint16_t>(3u) ) instead.
So what's going on, here ? Where does the int come from?
Can this actually result in an incorrect behavior?
Is there a less verbose way to silence it? (or a less verbose way to write a uint16_t literal?)
|
So what's going on, here ? Where does the int come from?
Integer promotion is going on here. On systems where std::uint16_t is smaller than int, it will be promoted to int when used as an operand (of most binary operations).
In a - b both operands are promoted to int and the result is int also. You compre this signed integer to 3u which is unsigned int. The signs differ, as the compiler warns you.
That warning doesn't show up if I write if ( a - b < static_cast<uint16_t>(3u) ) instead.
Here, the right hand operand is also promoted to int. Both sides of comparison are signed so there is no warning.
Can this actually result in an incorrect behavior?
if ( a - b < static_cast<uint16_t>(3u) ) does have different behaviour than a - b < static_cast<uint16_t>(3u). If one is correct, then presumably the other is incorrect.
Is there a less verbose way to silence it? (or a less verbose way to write a uint16_t literal?)
The correct solution depends on what behaviour you want to be correct.
P.S. You forgot to include the header that defines uint16_t.
|
72,170,645 | 72,171,041 | Using boost::counting_iterator with an existing vector? | At the moment I am doing this:
const int n = 13;
std::vector<int> v(boost::counting_iterator<int>(0), boost::counting_iterator<int>(n + 1));
std::copy(v.begin(), v.end(), back_inserter(m_vecAssignmentIndex));
m_vecAssignmentIndex is defined liek this:
ByteVector m_vecAssignmentIndex;
And, ByteVector:
using ByteVector = std::vector<BYTE>;
Is it possible to assign directly to m_vecAssignmentIndex and avoid std::copy?
Update
So, code like this is OK:
std::vector<BYTE> v2(boost::counting_iterator<BYTE>(0), boost::counting_iterator<BYTE>(n + 1));
std::vector<int> v(boost::counting_iterator<int>(0), boost::counting_iterator<int>(n + 1));
std::copy(v.begin(), v.end(), back_inserter(m_vecAssignmentSortedIndex));
Thus, I can directly increment BYTE values. So how can I avoid the requirement for the temp vector?
| I have now found the samples in the official docs:
int N = 7;
std::vector<int> numbers;
typedef std::vector<int>::iterator n_iter;
std::copy(boost::counting_iterator<int>(0),
boost::counting_iterator<int>(N),
std::back_inserter(numbers));
std::vector<std::vector<int>::iterator> pointers;
std::copy(boost::make_counting_iterator(numbers.begin()),
boost::make_counting_iterator(numbers.end()),
std::back_inserter(pointers));
std::cout << "indirectly printing out the numbers from 0 to "
<< N << std::endl;
std::copy(boost::make_indirect_iterator(pointers.begin()),
boost::make_indirect_iterator(pointers.end()),
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
So:
std::copy(boost::counting_iterator<BYTE>(0),
boost::counting_iterator<BYTE>(n), std::back_inserter(m_vecAssignmentSortedIndex));
|
72,170,819 | 72,183,642 | How is Phong Shading implemented in GLSL? | I am implementing a Phong Shader in GLSL for an assignment, but I don't get the same specular reflection as I should. The way I understood it, it's the same as Gouraud Shading, but instead of doing all the calculations in the vertex shader, you do them in the fragment shader, so that you interpolate the normals and then apply the phong model at each pixel. As part of the assignment I had to develop also the Gouraud shader and that works as supposed and I thought you just needed to put the vertex shader code into the fragment shader, but that doesn't seem to be the case.
What I do in the vertex shader is that I simply transform the vertex position into view coordinates and I apply the transpose inverse of the model view matrix to the vertex normal. Then, in the fragment shader I apply just the view transform to the light position and use these coordinates to calculate the vectors needed in the Phong model The lighting is almost correct, but some specular light is missing. All the parameters have been tested, so I would assume it's the light's position that is wrong, however I have no idea why my code wouldn't work when it does so in the other shader. Also, I know this isn't the most efficient way of doing it (pre-computing the normal matrix would be faster), I'm just trying to first get it to work properly.
| The problem is the way how the light source position is calculated. The following code
vec3 l = normalize(mat3(VMatrix)*light);
treats light as a direction (by normalizing it and because the translation part of the view matrix is ignored), but it actually is a position. The correct code should be something like
vec3 l = (VMatrix * vec4(light, 1.0)).xyz
|
72,171,380 | 72,171,505 | How do I access Sound Hardware in Dev-C++? | I was following a video tutorial for playing music in c++:
https://www.youtube.com/watch?v=tgamhuQnOkM&t=1030s
I am using Dev-C++ and I keep getting an error in the header file that "I'm not supposed to worry about"
The line is:
auto d = std::find(devices.begin(), devices.end(), sOutputDevice);
And the error says:
>92 68 C:\Users\benna\Documents\Starting Over\wave_music\olcNoiseMaker.h [Error] no matching function for call to 'find(std::vector<std::basic_string<wchar_t> >::iterator, std::vector<std::basic_string<wchar_t> >::iterator, std::wstring&)'
I am a noob here and I really don't get it.
My code is the same, and I've looked at linkers, project settings and other IDEs (VS Code & Eclipse) and nothing changes. (Especially the other IDEs, I can't even get them to run "Hello World".)
I just thought I could learn something through a little experimentation but I am getting nowhere. Is it a problem with my software?
I think it may be a problem with accessing my sound hardware.
I am still learning so any help would be appreciated, thank you!
The header file is here:
https://github.com/OneLoneCoder/synth/blob/master/olcNoiseMaker.h
And my main file is this:
using namespace std;
#include "olcNoiseMaker.h"
atomic<double> dFrequencyOutput = 0.0;
double MakeNoise(double dTime)
{
return 0.5 * sin(440.0 * 2 * 3.14159 * dTime);
//double dOutput 1.0* sin(dFrequencyOutput * 2.0 * 3.14159 * dTime);
//return dOutput * 0.5;
//if (dOutput > 0.0)
// return 0.2;
//else
// return -0.2;
}
int main()
{
wcout << "onelonecoder.com - Synthesizer Part 1" << endl;
// Get all sound hardware
vector<wstring> devices = olcNoiseMaker<short>::Enumerate();
// Display findings
for (auto d : devices) wcout << "Found Output Device:" << d << endl;
// Create sound machine!!
olcNoiseMaker<short> sound(devices[0], 44100, 1, 8, 512);
// Link make noise function with sound machine
sound.SetUserFunction(MakeNoise);
while (1)
{
}
return 0;
}
| This is a bug in the linked header file. It should include <algorithm> which is required for std::find, but doesn't.
I haven't checked the rest of the header file or your posted code for bugs, but I also noticed
while (1)
{
}
Infinite loops without IO, atomic, volatile or synchronization operations have undefined behavior in C++. You can't use such a loop to infinitely pause the program or thread.
The header seems to not be tested well in multiple different environments. For example this issue mentions similar problems to get it working under MinGW and has a list of changes that user needed to make.
|
72,171,848 | 72,171,977 | move semantics for `this`? | Imagine the following situation:
class C {
public:
C(std::vector<int> data): data(data) {}
C sub_structure(std::vector<size_t> indices){
std::vector<int> result;
for(auto i : indices)
result.push_back(data[i]); // ***
return C(result);
}
std::vector<int> data;
};
C f(){
...
}
...
C c = f().sub_structure(...);
I guess in the line marked ***, copies of the elements of data are made, altough sub_structure is called on an object that's about to be destroyed.
If my call was something like sub_structure(f(), ...), I could overload sub_structure by rvalue reference; however, as a class method, I'm not aware how to do that, basically based on if *this is an rvalue reference.
Is such a behaviour possible without resorting to global functions?
|
If my call was something like sub_structure(f(), ...), I could overload sub_structure by rvalue reference; however, as a class method, I'm not aware how to do that, basically based on if *this is an rvalue reference.
Do you mean overloading on value category?
Not sure if this is what you mean, but if get your problem correctly, I'd go this way:
struct S
{
std::vector<int> data;
S doStuff() &&
{
std::cout << "rvalue\n";
return {std::move(data)};
}
S doStuff() const&
{
std::cout << "const lvalue\n";
return {data};
}
};
Demo https://godbolt.org/z/5c89edMKv
This is by no means exhaustive, one can easily return e.g reference to const *this on the const& overload, copy on non-const etc.
|
72,171,889 | 72,171,985 | Exactly how are parameters initialized by the arguments passed in the function call in C++? | In the following code :
#include<iostream>
using namespace std;
void fun(T1 x, T2 y, T3 z){
// some code
}
int main(){
T1 a;
T2 b;
T3 c;
fun(a,b,c);
}
I wanted to understand, how the parameters(x, y, and z) in the function "fun" are getting initialized by the arguments(a,b, and c) passed during the function call. Is the copy constructor invoked and then initialization happens like T1 x = a; T2 y = b; T3 z = c; or something else take place?
Please explain.
|
Is the copy constructor invoked and then initialization happens like T1 x = a; T2 y = b; T3 z = c;
Yes, it happens exactly like this. Which, given the amount of different kinds of initializations in C++, is an impressive guess.
It's called copy-initialization: (which in general doesn't necessarily imply that a copy constructor is called)
[dcl.init.general]/14
The initialization that occurs in the = form of a brace-or-equal-initializer or condition ([stmt.select]), as well as in argument passing, function return, throwing an exception ([except.throw]), handling an exception ([except.handle]), and aggregate member initialization ([dcl.init.aggr]), is called copy-initialization.
"the = form of a brace-or-equal-initializer" refers to T1 x = a;, and "argument passing" speaks for itself.
|
72,172,104 | 72,175,002 | How to do color filtering with PCL | I am learning to use pcl.I want to filter out point clouds whose color is red(rgb 255,0,0),But not work.what should I do?
The PCL version I am using is 1.12.1.
#include <pcl/point_types.h>
#include <pcl/filters/conditional_removal.h>
int main()
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered(new
pcl::PointCloud<pcl::PointXYZRGB>);
cloud->width = 5;
cloud->height = 1;
cloud->points.resize((cloud->width) * (cloud->height));
//creat point cloud
for (size_t i = 0; i < cloud->points.size(); ++i)
{
cloud->points[i].x = 1024 * rand() / (RAND_MAX + 1.0f) / 1000;
cloud->points[i].y = 1024 * rand() / (RAND_MAX + 1.0f) / 1000;
cloud->points[i].z = 1024 * rand() / (RAND_MAX + 1.0f) / 1000;
cloud->points[i].r = 110;
cloud->points[i].g = 110;
cloud->points[i].b = 110;
}
//set rbg 255,0,0
cloud->points[2].r = 255;cloud->points[2].g = 0;cloud->points[2].b = 0;
pcl::ConditionAnd<pcl::PointXYZRGB>::Ptr range_cond(new pcl::ConditionAnd<pcl::PointXYZRGB>());
range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZRGB>::ConstPtr(new pcl::FieldComparison<pcl::PointXYZRGB>("r", pcl::ComparisonOps::EQ, 255)));
range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZRGB>::ConstPtr(new pcl::FieldComparison<pcl::PointXYZRGB>("g", pcl::ComparisonOps::EQ, 0)));
range_cond->addComparison(pcl::FieldComparison<pcl::PointXYZRGB>::ConstPtr(new pcl::FieldComparison<pcl::PointXYZRGB>("b", pcl::ComparisonOps::EQ, 0)));
pcl::ConditionalRemoval<pcl::PointXYZRGB> condrem;
condrem.setCondition(range_cond);
condrem.setInputCloud(cloud);
condrem.setKeepOrganized(true);
condrem.filter(*cloud_filtered);
std::cerr << "Cloud before filtering: " << std::endl;
for (size_t i = 0; i < cloud->points.size(); ++i)
std::cerr << " " << cloud->points[i].x << " "
<< cloud->points[i].y << " "
<< cloud->points[i].z << " "
<< (int)cloud->points[i].r << " "
<< (int)cloud->points[i].g << " "
<< (int)cloud->points[i].b << std::endl;
std::cerr << "Cloud after filtering: " << std::endl;
for (size_t i = 0; i < cloud_filtered->points.size(); ++i)
std::cerr << " " << cloud_filtered->points[i].x << " "
<< cloud_filtered->points[i].y << " "
<< cloud_filtered->points[i].z << " "
<< (int)cloud_filtered->points[i].r << " "
<< (int)cloud_filtered->points[i].g << " "
<< (int)cloud_filtered->points[i].b << std::endl;
return (0);
}
Cloud after filtering is None.
result:
enter image description here
| The warning message gives you a hint: "field not found!" (three times). PointXYZRGB does not have r, g, and b fields. You can use getFields() to find out which fields a point type has. PointXYZRGB has a combined field rgb that you can use for filtering. However, you might want to consider using PointXYZRGBA instead (with field rgba) because the other point type uses a float for storage (historic reasons) and I am not sure how well that works with filtering.
|
72,173,127 | 72,173,754 | SFINAE doesn't work in recursive function | Let's create currying function.
template <typename TFunc, typename TArg>
class CurryT
{
public:
CurryT(const TFunc &func, const TArg &arg)
: func(func), arg(arg )
{}
template <typename... TArgs>
decltype(auto) operator()(TArgs ...args) const
{ return func(arg, args...); }
private:
TFunc func;
TArg arg ;
};
template <typename TFunc, typename TArg>
CurryT<decay_t<TFunc>, remove_cv_t<TArg>>
Curry(const TFunc &func, const TArg &arg)
{ return {func, arg}; }
And function that decouple function to single argument functions:
// If single argument function (F(int)).
template <typename F>
static auto Decouple(const F &f, enable_if_t<is_invocable_v<F, int>> * = nullptr)
{
return f;
}
// If multiple arguments function (F(int, int, ...)).
template <typename F>
static auto Decouple(const F &f, enable_if_t<!is_invocable_v<F, int>> * = nullptr)
{
return [f](int v) { return Decouple( Curry(f, v) ); };
}
Everything works fine if 2 arguments function is passed:
auto f1 = Decouple(
[](int a, int b)
{ std::cout << a << " " << b << std::endl; }
);
f1(3)(4); // Outputs 3 4
But if I add more arguments
auto f2 = Decouple(
[](int a, int b, int c)
{ std::cout << a << " " << b << " " << c << std::endl; }
);
f(5)(6)(7);
The compilation breaks: https://coliru.stacked-crooked.com/a/10c6dba670d17ffa
main.cpp: In instantiation of 'decltype(auto) CurryT<TFunc, TArg>::operator()(TArgs ...) const [with TArgs = {int}; TFunc = main()::<lambda(int, int, int)>; TArg = int]':
main.cpp:17:26: error: no match for call to '(const main()::<lambda(int, int, int)>) (const int&, int&)'
17 | { return func(arg, args...); }
It breaks in instantiation of std::is_invocable.
Since debugging the standard library is hard, I created simple versions of standard type traits classes:
template <typename F> true_type check(const F &, decltype( declval<F>()(1) )* );
template <typename F> false_type check(const F &, ...);
template <typename F>
struct invocable_with_int : decltype(check(declval<F>(), nullptr))
{};
template <typename F>
inline constexpr bool invocable_with_int_v = invocable_with_int<F>::value;
template<bool B>
struct my_enable_if {};
template<>
struct my_enable_if<true>
{ using type = void; };
template <bool B>
using my_enable_if_t = typename my_enable_if<B>::type;
The problem remains the same https://coliru.stacked-crooked.com/a/722a2041600799b0:
main.cpp:29:73: required by substitution of 'template<class F> std::true_type check(const F&, decltype (declval<F>()(1))*) [with F = CurryT<main()::<lambda(int, int, int)>, int>]'
It tries to resolve calling to this function:
template <typename F> true_type check(const F &, decltype( declval<F>()(1) )* );
But decltype (declval<F>()(1))*) fails. But shouldn't this function be removed from overload resolution because template substitution fails? It works when Decouple is called first time. But when it is called second time the SFINAE seems to be disabled, and the first failure of template substitution gives a compilation error. Are there some limitation on secondary SFINAE? Why calling template function recursively doesn't work?
The problem is reproduced in GCC and Clang. So it is not a compiler bug.
| Your operator() overload is completely unconstrained and therefore claims to be callable with any set of arguments. Only declarations, not definitions, are inspected to determine which function to call in overload resolution. If substitution into the definition then fails, SFINAE does not apply.
So, constrain your operator() to require TFunc to be callable with TArg and TArgs... as arguments.
For example:
template <typename... TArgs>
auto operator()(TArgs ...args) const -> decltype(func(arg, args...))
|
72,173,184 | 72,173,260 | How to assign two dimensional initializer list in c++? | I inherited my class from vector and I would like to be able to assign list to my class like to vector.
My code is as follows:
#include <vector>
using namespace std;
template<typename T>
class Matrix
: public vector<vector<T>>
{
public:
Matrix( vector<vector<T>> && m )
: vector<vector<T>>( m )
{}
// Tried this approach, but it doesn't work
// Matrix(std::initializer_list<std::initializer_list<T>> l){
// }
}
int main()
{
Matrix<int> m({{0, 1}, {2, 3}}); // it works
// Matrix<int> m = {{0, 1}, {2, 3}}; // error: no instance of constructor "Matrix<T>::Matrix [with T=int]" matches the argument list -- argument types are: ({...}, {...})
}
| Just bring std::vector constructor to your class scope:
template <typename T> class Matrix : public vector<vector<T>> {
public:
using vector<vector<T>>::vector;
};
https://godbolt.org/z/b3bdx53d8
Offtopic: inheritance is bad solution for your case.
|
72,173,334 | 72,173,499 | Unable to get CMake Tutorial example to compile... Why? | I'm trying to follow the official tutorial for CMake for adding a version number and configured header file. I have two directories:
Step1
Step1_build
Step1 contains CMakeLists.txt, TutorialConfig.h.in and tutorial.cxx. Contents of each file follow:
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
# set the project name
project(Tutorial VERSION 1.0)
# configure a header file to pass the version number to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)
# add directory to list of paths to search for include files
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
)
# add the executable
add_executable(Tutorial tutorial.cxx)
TutorialConfig.h.in
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
tutorial.cxx
#include "TutorialConfig.h"
#include <iostream>
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << argv[0] << "Version" << Tutorial_VERSION_MAJOR << "."
<< Tutorial_VERSION_MINOR << std::endl;
return 1;
}
std::cout << "argc=" << argc << std::endl;
std::cout << "argv[1]=" << argv[1] << std::endl;
}
I then try to build using cmake -S Step1 -B Step1_build. But I get an error:
CMake Error at CMakeLists.txt:10 (target_include_directories)
Cannot specify include directories for target "Tutorial" which is not built by this project
I've checked the instructions again and again, and I'm not sure what I'm doing wrong. Why won't the project compile?
| In CMake targets need to be defined before any modification of their properties (like include directories), so this line:
# add the executable
add_executable(Tutorial tutorial.cxx)
should be moved before the call to target_include_directories.
|
72,173,769 | 72,174,691 | VS reporting error with every variable of a class | I have realized a typical class called "FCB", and VS didn't report any problem while I was coding, and can recognize its members when referred to.
Yet as I try to compile it, it shows that every variable whose type is FCB or FCB* appear to be unrecognizable. Here is my class.
FileControlBlock.h
#pragma once
#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
#include "hash.h" //a custom head file that I use to use string as hash index
//file authority
#define AUTH_ALL 0
#define AUTH_NO_DEL 1
#define AUTH_READ_ONLY 2
#define THIS_DIR 0
#define CHIL_DIR 1
#define SUC 0
#define ERR -1
#define C_ERR_DUP_NAME -1
#define C_ERR_ILL_NAME -2
#define D_ERR_LACK_AUTH -1
#define D_ERR_IS_OCCUPY -2
#define R_ERR_IS_WRITE -1
#define W_ERR_IS_OCCUPY -1
extern FCB* POS_POINTER;
class FCB
{
public:
string name; //file name
char type; //directory(.f), .exe(.e), .txt(.t)
FCB* parent;
int size;
int auth;
//only for directories
unordered_map<unsigned int, FCB> directoryTree;
string printRoute(); //print the route
vector<FCB> saveDirectory();
FCB* findFile(string fileName);
vector<string> printFile(char fileType);//find a certain kind of file
FCB(string fileName = "~", int fileSize = 0);
string printDirectory(string dirRoute = ".", int mode = THIS_DIR);
};
FCB::FCB(string fileName, int fileSize)
{
this->name = fileName;
int nameLen = fileName.size();
this->type = fileName[nameLen - 1];
this->parent = POS_POINTER;
this->size = fileSize;
this->auth = POS_POINTER->auth;
}
string FCB::printRoute()
{
string route = this->name;
return route;
}
string FCB::printDirectory(string dirRoute, int mode)
{
string result = "";
return result;
}
vector<string> FCB::printFile(char fileType)
{
vector<string> result;
return result;
}
vector<FCB> FCB::saveDirectory()
{
vector<FCB> result;
return result;
}
FCB* FCB::findFile(string fileName)
{
FCB* result = NULL;
return result;
}
FileSystem.h(it is not completed yet)
#pragma once
#include <fstream>
#include "FileControlBlock.h"
#define WRITE_HEAD 0
#define WRITE_TAIL 1
#define MAX_NAME_LEN 16
//save on the computer
const string dirLoc = "PD_OS_FS\\directory.txt";
class FileSystem
{
public:
FCB myDir;
FileSystem();
~FileSystem();
int changeRoute(string route);
int creatFile(string fileName);
int deleteFile(string fileName);
int readFile(string fileName, int pid);
int writeFile(string fileName, string writeObj, int mode, int pid);
};
main.cpp
#include "FileSystem.h"
FCB* POS_POINTER = NULL; //位置指针
int main()
{
return 0;
}
There is nothing special with my main(), and the error info is as follow:
enter image description here
Sorry that I can't translate it into English. Basically, myDir is a member of another class "FileSystem" whose type is FCB, but VS reports that myDir does not belong to FileSystem. Most of the errors are like that, related with class FCB, as if there is no such class.
| Like @RichardCritten ’s comment, I wrongly declared POS_POINTER before FCB. Just move it after the class and before the member functions will fix most of the porbl
|
72,174,209 | 72,174,322 | Testing implementation details for automated assessment of sorting algorithms | I'm looking at automated assignments for an introductory algorithms and data structures course. Students submit code, I run boost tests on them, the number of passed tests gives a grade, easy. But I want to assess sorting algorithms, for example "Implement bubble-, insertion-, selection- and merge-sort". Is there a clever way to test the implementations of each to know they did in fact implement the algorithm requested?
Obviously I can check they sorted the inputs. But what I really want is something better than just comparing the timings for various inputs to check complexities.
|
Is there a clever way to test the implementations of each to know they
did in fact implement the algorithm requested?
Make them write a generic sort that sorts (say) a std::vector<T>, and then in your unit test provide a class where you overload the comparison operator used by the sorting algorithm to log which objects it's sorting. At the end your test can examine that log and determine if the right things were compared to one another in the right order.
What distinguishes one sorting algorithm from another is ultimately the order in which elements are compared.
EDIT: Here's a sample implementation. Not the cleanest or prettiest thing in the world, but sufficient as a throwaway class used in a unit test.
struct S
{
static std::vector<std::pair<int, int>> * comparisonLog;
int x;
S(int t_x) : x(t_x) { }
bool operator <(const S & t_other) const
{
comparisonLog->push_back({x, t_other.x});
return x < t_other.x;
}
};
std::vector<std::pair<int, int>> * S::comparisonLog;
Sample usage in a unit test:
std::vector<std::pair<int, int>> referenceComparisons, studentComparisons;
const std::vector<S> values = { 1, 5, 4, 3, 2 };
S::comparisonLog = &referenceComparisons;
{
auto toSort = values;
std::sort(toSort.begin(), toSort.end());
}
S::comparisonLog = &studentComparisons;
{
auto toSort = values;
studentSort(toSort);
assert(std::is_sorted(toSort.begin(), toSort.end()));
}
assert(referenceComparisons == studentComparisons);
This checks that studentSort implements the same sorting algorithm as std::sort. (Of course, what it doesn't check is that studentSort doesn't just forward to std::sort...)
EDIT TO ADD: An alternative, which may generalize better to things other than sorting algorithms specifically, would be to make them write a generic sort taking begin and end iterators of a particular type and instrumenting the pointer arithmetic and dereferencing operators for the iterators you hand them.
|
72,174,397 | 72,188,590 | Force creation of method on intel compiler with optimization level 3 | Working on a +95% C++ 11 code (the rest is C) that is generally used compiled w/ optimization level 3 we profiled it and found a really time-consuming method.
Toy code:
myClass::mainMethod()
{
// do stuff here
/ ...
// do more stuff here
/ ...
}
We splitted its inner sections into other methods in order to precisely measure which is the problematic part, e.g.
myClass::mainMethod()
{
this->auxiliaryMethod1();
this->auxiliaryMethod2();
}
myClass::auxiliaryMethod1()
{
// do stuff here
// ...
}
myClass::auxiliaryMethod2()
{
// do more stuff here
// ...
}
But the (intel) compiler is smart enough to notice this only usage and assemble it back together into a single method.
Besides this two obvious other possible solutions, i.e. compiling without optimization (irrealistic) and adding other spurious usages (a wasteful process), is there an intel compiler flag to indicate "please explicitly code this method into the class"???
Thanks!
| As the comments suggested, splitting with attribute noinline did the trick.
void __attribute__((noinline)) myClass::mainMethod()
{
this->auxiliaryMethod1();
this->auxiliaryMethod2();
}
void __attribute__((noinline)) myClass::auxiliaryMethod1()
{
// do stuff here
// ...
}
void __attribute__((noinline)) myClass::auxiliaryMethod2()
{
// do more stuff here
// ...
}
|
72,174,473 | 72,174,553 | Call db.close() on Button_Click (QT/C++) | how can i close a database connction from Button_onClick funktion?
Artikelverwaltung::Artikelverwaltung(QWidget *parent) :
QDialog(parent),
ui(new Ui::Artikelverwaltung)
{
...
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
...
}
void Artikelverwaltung::on_pushButton_clicked()
{
db.close(); // <---- This is not working of cause. how can i do this?
}
Best regards
| It is not working because db is a local variable in Artikelverwaltung::Artikelverwaltung you need to make it a class attribute.
class Artikelverwaltung
{
private:
QSqlDatabase m_db;
};
Artikelverwaltung::Artikelverwaltung(QWidget *parent) :
QDialog(parent),
ui(new Ui::Artikelverwaltung)
{
...
m_db = QSqlDatabase::addDatabase("QODBC");
...
}
void Artikelverwaltung::on_pushButton_clicked()
{
m_db.close();
}
|
72,174,644 | 72,175,260 | OpenMP parallel reduction (min) incorrect result | i am using OpenMP reduction(min) to get the minimum number of lock acquisitions in a parallel section over all participating threads.
When printing each threads counter inside the parallel section, I get correct results but after the parallel section, the min counter is at 0.
This is the code:
int counter = 0, maxV, minV;
bool _continue = true; //variable to indicate when one second is over
#pragma omp parallel private(id) shared(lock, _continue) reduction(min:minV) reduction(+:counter) reduction(max:maxV)
{
id = omp_get_thread_num();
if(id == 0)
{
auto start = std::chrono::high_resolution_clock::now(); //start time measurement
while(_continue)
{
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::micro> elapsed = finish - start;
if(elapsed.count() > std::chrono::microseconds(sec).count())
{
_continue = false;
}
}
}
else
{
while(_continue) //during timeframe, try to obtain lock as often as possible
{
lock.lock(id);
lock.unlock(id);
counter++;
}
minV = counter;
maxV = counter;
}
#pragma omp critical
{
std::cout << id << ": " << minV << std::endl;
}
}
std::cout << minV << std::endl;
The typical output is something like:
0: 2147483647
7: 256985
4: 255973
1: 256975
6: 255740
5: 256658
3: 256856
2: 256943
0
So even for thread 0, the thread that is not acquiring the lock but just taking the time, the minV is correctly initialized as largest representable number in the reduction list item type (int).
Depending on what compiler options I choose, I can alter the result of minV (last line in cout) to the following values (always wrong...):
minV = 32767 | -std=c++14 -fopenmp
minV = 0 | -std=c++14 -fopenmp -O3
minV = 32766 | -std=c++14 -fopenmp -Wall
minV = 32767 | -std=c++14 -fopenmp -Wall -pedantic -march=native -fconcepts
So I assume it has something to do with my compiler options? Strangely though, the max and sum reduction appear to work fine...
Any help is appreciated.
| You have a confusion between the init value that OMP uses internally, and the init value from the user code. The partial reductions are done with the internal value, but at some point there also has to be a reduction against the user-supplied initial value. If you don't set that, anything can happen.
Here is a cute picture: https://theartofhpc.com/pcse/omp-reduction.html#Initialvalueforreductions
|
72,174,690 | 72,174,740 | How to not use friend declaration when equipping a class with `operator<<` | I understand that we'd want to do something like this to override operator<<
#include <iostream>
class Point
{
private:
double m_x{};
double m_y{};
double m_z{};
public:
Point(double x=0.0, double y=0.0, double z=0.0)
: m_x{x}, m_y{y}, m_z{z}
{
}
friend std::ostream& operator<< (std::ostream& out, const Point& point);
};
std::ostream& operator<< (std::ostream& out, const Point& point)
{
// Since operator<< is a friend of the Point class, we can access Point's members directly.
out << "Point(" << point.m_x << ", " << point.m_y << ", " << point.m_z << ')'; // actual output done here
return out; // return std::ostream so we can chain calls to operator<<
}
int main()
{
const Point point1{2.0, 3.0, 4.0};
std::cout << point1 << '\n';
return 0;
}
source: https://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/
But what if I don't need to access private member variables? I could continue to use friend but I'd prefer not to as in my opinion that would be confusing code. But I couldn't figure out how to not use friend. I tried:
Just dropping friend, but then the compiler would insert the implicit this pointer as the first argument, which is not what I want.
Changing friend to static, but my IDE complains that operator<< cannot be static.
| You can just declare operator<< as a free function in the same namespace as Point (in this case, the global namespace) and ADL will take care of it:
#include <iostream>
class Point {
private:
double m_x{};
double m_y{};
double m_z{};
public:
Point(double x = 0.0, double y = 0.0, double z = 0.0)
: m_x{x}, m_y{y}, m_z{z} {}
};
std::ostream& operator<<(std::ostream& out, const Point& point) {
out << "Point";
// Use public interface of point here.
return out;
}
int main() {
const Point point1{2.0, 3.0, 4.0};
std::cout << point1 << '\n';
return 0;
}
|
72,174,838 | 72,182,783 | Indirect perfect forwarding via function pointer? | Lets consider ordinary perfect forwarding:
class Test
{
public:
Test() = default;
Test(Test const&) { std::cout << "copy\n"; }
Test(Test&&) { std::cout << "move\n"; }
};
void test(Test)
{ }
template <typename T>
void f(T&& t)
{
test(std::forward<T>(t));
}
int main()
{
std::cout << "expect: copy\n";
Test t;
f(t);
std::cout << "expect: move\n";
f(Test());
return 0;
}
So far everything is fine. But if we now introduce a function pointer I get the problem that I seem not to be able to declare universal (forwarding) references:
decltype(&f<Test>) ptr = &f<Test>;
// above produces ordinary r-value references
// making below fail already on compilation:
ptr(t);
Template function pointers get problematic as well:
template <typename T>
void(*ptr)(T&& t) = &f<T>; // again resolved to r-value reference
At first, they resolve to pure r-value reference as well, additionally they define a bunch of pointers instead of a single one, making the approach unusable within class scope:
class C
{
template <typename T>
void(*ptr)(T&& t); // fails (of course...)
};
So question now is: Is it possible at all to have indirect perfect forwarding via function pointers?
Admitted, already fearing the answer is 'no' (and currently falling back to l-value references), but still in hope of having overlooked something somewhere...
| Background of the question is a mis-reading of Scott Meyer's article about forwarding references (called 'universal references' there).
The article gave the impression of such forwarding references existing as a separate type in parallel to ordinary l-value and r-value references. This is not the case, though, instead it is a hypothetical construct to explain special deduction rules that exist if template parameters serve as function parameter types.
As such a type does not exist in consequence it is not possible to declare a function pointer using that type, proving indirect perfect forwarding via function pointer impossible to realise.
|
72,174,984 | 72,211,349 | SFML setFillColor doesn't work to a class member | I think I should write implementation for my Circle class, but I'm not sure and I don't know, how to transfer Color as function parameter in main bcz compiler doesn't work with sf::Color::Red or just Red as function parameter in main function
#include <SFML/Graphics.hpp>
using namespace sf;
const int APPLICATION_WIDTH = 400;
const int APPLICATION_HEIGHT = 300;
class Figure : public sf::Shape{
protected:
double m_x0 = 0, m_y0 = 0;
float m_angle = 0;
double m_scale;
public:
virtual ~Figure() {}
void setCoordX(double x0) { m_x0 = x0; }
void setCoordY(double y0) { m_y0 = y0; }
void setAngle(float angle) { m_angle = angle; }
void setScale(double scale) { m_scale = scale; }
double getCoordX() { return m_x0; }
double getCoordY() { return m_y0; }
float getAngle() { return m_angle; }
double getScale() { return m_scale; }
virtual void drawFigure(sf::RenderWindow& w) = 0;
//virtual void moveFigure(sf::RenderWindow& w, const double vx, const double vy) = 0;
void hideFigure(sf::RenderWindow& w);
virtual void rotateFigure(sf::RenderWindow& w) = 0;
//virtual void scaleFigure(const double vx, const double vy) = 0;
};
void Figure::rotateFigure(sf::RenderWindow& w) {
sf::Shape::rotate(m_angle);
}
void Figure::hideFigure(sf::RenderWindow& w) {
sf::Shape::setFillColor(sf::Color::Transparent);
}
class Circle : public Figure {
private:
CircleShape m_obj;
//double m_x1 , m_y1;
double m_radius = 1;
Vector2f getPoint(std::size_t index) const override {
return m_obj.getPoint(index);
}
std::size_t getPointCount() const override {
return m_obj.getPointCount();
}
public:
//void setCoordX1(double x1) { m_x1 = x1; }
void setRad(double r) { m_radius = r; }
double getRad() { return m_obj.getRadius(); }
double getCenterX() { return m_obj.getRadius(); }
double getCenterY() { return m_obj.getRadius(); }
void drawFigure(sf::RenderWindow& w);
//void moveFigure(sf::RenderWindow& w, const double vx, const double vy);
//void hideFigure(sf::RenderWindow& w) override;
void rotateFigure(sf::RenderWindow& w) override;
};
void Circle::drawFigure(sf::RenderWindow& w) {
m_obj.setRadius(m_radius);
m_obj.setPosition(m_x0, m_y0);
w.draw(m_obj);
}
//void Circle::hideFigure(sf::RenderWindow &w) {
// m_obj.setFillColor(sf::Color::Transparent);
//}
void Circle::rotateFigure(sf::RenderWindow& w) {
//m_obj.setFillColor(sf::Color::Magenta); // if I'll paint it here, it works
m_obj.rotate(m_angle);
}
int main()
{
RenderWindow window(VideoMode(APPLICATION_WIDTH, APPLICATION_HEIGHT), "Lab 6 using SFML");
Circle a, b, c, d;
a.setFillColor(sf::Color::Red);
b.setFillColor(sf::Color::Green);
//c.setFillColor(sf::Color::Blue);
//d.setFillColor(sf::Color::Magenta);
a.setRad(32);
a.setCoordX(50); a.setCoordY(34);
b.setRad(16);
b.setCoordX(10); b.setCoordY(34);
b.setAngle(45);
b.rotateFigure(window);
//b.hideFigure(window);
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
}
//sf::CircleShape circle;
//circle.setRadius(50);
//circle.setFillColor(sf::Color::Green);
//circle.setPosition((APPLICATION_WIDTH - (circle.getRadius()*2))/2.0,
// (APPLICATION_HEIGHT - (circle.getRadius()*2))/2.0);
//circle.move(30, 30);
//window.draw(circle);
a.drawFigure(window);
b.drawFigure(window);
window.display();
}
return 0;
}
| sf::Color is a class that can be passed as a parameter. You can read how sf::Color works in the documentation: https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Color.php
Example:
#include <SFML/Graphics.hpp>
class MyCircle
{
public:
MyCircle()
{
mCircle.setRadius(50.f);
}
void setColor(sf::Color color)
{
mCircle.setFillColor(color);
}
void draw(sf::RenderWindow& window)
{
window.draw(mCircle);
}
private:
sf::CircleShape mCircle;
};
int main()
{
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
MyCircle circle;
circle.setColor(sf::Color::Red);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
circle.draw(window);
window.display();
}
return 0;
}
|
72,175,072 | 72,176,111 | Multithreading in C++ - Display animation until another thread has completed | Preface: this is my first attempt at writing a program in any language with multi-threading. I have no prior experience with std::thread, or with describing multi-threaded programs at all. Please let me know if you need more information to answer this question, or if I can reword anything to make my question clearer.
Suppose I have a simple animation function animate, which (for now) runs indefinitely; and another function task, which represents some arbitrary code to execute.
#include <string>
// a simple rotating stick animation: | -> / -> - -> \
void animate()
{
std::string syms = "|/-\\";
while (true)
{
for (unsigned int ii = 0; ii < syms.length(); ++ii)
{
std::cout << syms[ii];
std::cout << std::string(1, '\b');
}
}
}
// arbitrary function
void task()
{
// code to do something else goes here
}
int main (int argc, char* argv[])
{
// execute task and animate at the same time;
// return from animate once task has completed
return 0;
}
How can I use std::thread (or some other header/library) to allow task and animate to communicate with each other, such that task runs in the "background" and animate runs until task has completed?
| I've taken your example code and tried to fill in the blanks from your intention with std::thread. I've added some comments inline to explain what's going on. If something's not clear, or I got it wrong, feel free to ask in the comments.
I want to stress though that this example only uses std::thread to create and join a separate thread in a toy example.
It does not synchronize shared data between threads in a correct way.
Shared data in MT environments is where things get hairy and the worst thing is that it can create some of the hardest to debug bugs out there. That's why the books and working examples are important for any substantial multithreaded program.
#include <string>
#include <thread>
#include <chrono>
#include <iostream>
// a simple rotating stick animation: | -> / -> - -> \
//
void animate(bool * should_animate)
{
// Using this namespace lets us use the "100ms" time literal in the sleep_for() function argument.
using namespace std::chrono_literals;
std::string syms = "|/-\\";
while (*should_animate)
{
for (unsigned int ii = 0; ii < syms.length(); ++ii)
{
std::cout << syms[ii];
std::cout << std::string(1, '\b');
// I had to flush cout so that the animation would show up
std::cout.flush();
// I added some delay here so that the animation is more visible
std::this_thread::sleep_for(100ms);
}
}
}
// arbitrary function
void task()
{
using namespace std::chrono_literals;
// I have this thread waiting for 2 seconds to simulate a lot of work being done
std::this_thread::sleep_for(2s);
}
int main (int argc, char* argv[])
{
// This line creates a thread from the animate() function
// The std::thread constructor is flexible, in that it can take a function with any number and type of arguments and
// make a thread out of it
// Once the thread is created, it gets sent to the operating system for scheduling right away in a separate thread
// I'm passing in a pointer to `should_animate` to use that value as a basic way to communicate to the animate thread to signal when it should stop running.
// I'm doing this to keep the example simple, but I stress that this isn't a good idea for larger scale programs
// Better to use propper signals or event queues
bool should_animate = true;
std::thread thread_animate(animate, &should_animate);
// This line creates a thread for the worker task
// That separate thread can be referenced by tis std::thread object
// Once the functions finish running, the thread associated with it is "joined"
std::thread thread_task(task);
// 'join' pauses the main thread to wait for the associated thread to finish running in the background.
thread_task.join();
// By this point in the program, the `task()` function has finished running, so we can flag
// the animate task to finish running so its thread can be joined
should_animate = false;
// Wait for the animate thread to get the message and finish
thread_animate.join();
std::cout << "Done!" << std::endl;
return 0;
}
If you want to take it a little further, here's some links I'd recommend.
This was the best tutorial I could find in the first page of google (most results seemed bad). Seems like a good jumping off point https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/
cppreference is the best C++ reference site I know of, and I usually have at least one tab on it all day. Because it is reference, its difficult to dig straight into it. Each section header of this page covers one multithreaded topics. "Threads" and "Mutual Exclusion" are the most common things uses in MT. https://en.cppreference.com/w/cpp/thread
|
72,175,338 | 72,175,608 | Why are we using currsum[n+1] and then on line no. 23 currsum[i] = currsum[i-1] + arr[i-1];? |
Why is she using [n+1] instead of N directly and then that line no. 23 what is that equality?
Why do we use INT_MIN for Maximum numbers or arrays, and `INT_MAX for minimum things?
#include <bits/stdc++.h>
using namespace std;
//Question is of Find the Subarray with Maximum sum//
int main(){
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int currsum[n+1]; //CurrentSum = currsum[]
currsum[0] = 0;
for (int i = 1; i <= n; i++)
{
currsum[i] = currsum[i-1] + arr[i-1];
}
int MaxSum = INT_MIN;
for (int i = 1; i <= n; i++)
{
int sum = 0;
for (int j = 0; j <i; j++){
sum = currsum[i] + currsum[j];
MaxSum = max(sum, MaxSum);
}
}
return 0;
}
|
Have you heard of prefix sums? (aka running totals, cumulative sums, scans). N+1 is used because prefix sums also needs to include an empty subarray.
You use INT_MIN for maximum because the max() function takes the larger of the two values, so MaxSum is always increasing. If you make MaxSum = 0 at the beginning, or some other number, there is a chance that 0 is larger than any of the actual sums. To make sure that the default value does not override the actual values, you set it to as low as possible.
|
72,175,611 | 72,202,473 | How to save last BFS of Edmonds-Karp algorithm? | I have implemented the following C++ Edmonds-Karp algorithm:
#include <iostream>
// Part of Cosmos by OpenGenus Foundation //
#include <limits.h>
#include <string.h>
#include <queue>
using namespace std;
#define V 6
/* Returns true if there is a path from source 's' to sink 't' in
* residual graph. Also fills parent[] to store the path */
bool bfs(int rGraph[V][V], int s, int t, int parent[])
{
// Create a visited array and mark all vertices as not visited
bool visited[V];
memset(visited, 0, sizeof(visited));
// Create a queue, enqueue source vertex and mark source vertex
// as visited
queue <int> q;
q.push(s);
visited[s] = true;
parent[s] = -1;
// Standard BFS Loop
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v = 0; v < V; v++)
if (visited[v] == false && rGraph[u][v] > 0)
{
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
// If we reached sink in BFS starting from source, then return
// true, else false
return visited[t] == true;
}
// Returns tne maximum flow from s to t in the given graph
int fordFulkerson(int graph[V][V], int s, int t)
{
int u, v;
// Create a residual graph and fill the residual graph with
// given capacities in the original graph as residual capacities
// in residual graph
int rGraph[V][V]; // Residual graph where rGraph[i][j] indicates
// residual capacity of edge from i to j (if there
// is an edge. If rGraph[i][j] is 0, then there is not)
for (u = 0; u < V; u++)
for (v = 0; v < V; v++)
rGraph[u][v] = graph[u][v];
int parent[V]; // This array is filled by BFS and to store path
int max_flow = 0; // There is no flow initially
// Augment the flow while tere is path from source to sink
while (bfs(rGraph, s, t, parent))
{
// Find minimum residual capacity of the edges along the
// path filled by BFS. Or we can say find the maximum flow
// through the path found.
int path_flow = INT_MAX;
for (v = t; v != s; v = parent[v])
{
u = parent[v];
path_flow = min(path_flow, rGraph[u][v]);
}
// update residual capacities of the edges and reverse edges
// along the path
for (v = t; v != s; v = parent[v])
{
u = parent[v];
rGraph[u][v] -= path_flow;
rGraph[v][u] += path_flow;
}
// Add path flow to overall flow
max_flow += path_flow;
}
// Return the overall flow
return max_flow;
}
(source: https://iq.opengenus.org/edmonds-karp-algorithm-for-maximum-flow/)
I would like to save the last BFS of the algorithm, so I can print the minimal cut (which would be {last BFS} {everything else not found in the last BFS})
How do I do that?
I have tried creating a BFS vector every time the bfs function is called, and reset it, but somehow it doesn't seem to work how I imagined:
in bfs function:
bool bfs(int rGraph[V][V], int s, int t, int parent[], vector<int>& search)
{
...
while (!q.empty())
{
int u = q.front();
search.push_back(u);
q.pop();
...
in the fordFulkerson section:
vector<int>tempsearch;
vector<int>search;
while (bfs(rGraph, s, t, parent, search))
{
...
tempsearch.resize(search);
tempsearch = search //this is now a pseudo-code variant
search.resize(0);
}
//at this point tempsearch or search should be the last bfs, no?
return max_flow;
| Okay so I found a solution.
We need to have the visited array as a global array (or you can pass it through every single parameter list). This way, every time the array is refreshed, it is also saved in the whole program.
From there, all we have to do is write the output function for the minimal cut:
void printMinCut(){
for(int i = 0; i < visited.size(); i++){
if(visited[i] == true) cout << i;
}
cout << endl;
for(int i = 0; i < visited.size(); i++){
if(visited[i] == false) cout << i;
}
}
And there you have it!
|
72,175,650 | 72,177,636 | openmp increasing number of threads increases the execution time | I'm implementing sparse matrices multiplication(type of elements std::complex) after converting them to CSR(compressed sparse row) format and I'm using openmp for this, but what I noticed that increasing the number of threads doesn't necessarily increase the performance, sometimes is totally the opposite! why is that the case? and what can I do to solve the issue?
typedef std::vector < std::vector < std::complex < int >>> matrix;
struct CSR {
std::vector<std::complex<int>> values; //non-zero values
std::vector<int> row_ptr; //pointers of rows
std::vector<int> cols_index; //indices of columns
int rows; //number of rows
int cols; //number of columns
int NNZ; //number of non_zero elements
};
const matrix multiply_omp (const CSR& A,
const CSR& B,const unsigned int num_threds=4) {
if (A.cols != B.rows)
throw "Error";
CSR B_t = sparse_transpose(B);
omp_set_num_threads(num_threds);
matrix result(A.rows, std::vector < std::complex < int >>(B.cols, 0));
#pragma omp parallel
{
int i, j, k, l;
#pragma omp for
for (i = 0; i < A.rows; i++) {
for (j = 0; j < B_t.rows; j++) {
std::complex < int > sum(0, 0);
for (k = A.row_ptr[i]; k < A.row_ptr[i + 1]; k++)
for (l = B_t.row_ptr[j]; l < B_t.row_ptr[j + 1]; l++)
if (A.cols_index[k] == B_t.cols_index[l]) {
sum += A.values[k] * B_t.values[l];
break;
}
if (sum != std::complex < int >(0, 0)) {
result[i][j] += sum;
}
}
}
}
return result;
}
| You can try to improve the scaling of this algorithm, but I would use a better algorithm. You are allocating a dense matrix (wrongly, but that's beside the point) for the product of two sparse matrices. That's wasteful since quite often the project of two sparse matrices will not be dense by a long shot.
Your algorithm also has the wrong time complexity. The way you search through the rows of B means that your complexity has an extra factor of something like the average number of nonzeros per row. A better algorithm would assume that the indices in each row are sorted, and then keep a pointer for how far you got into that row.
Read the literature on "Graph Blas" for references to efficient algorithms.
|
72,175,652 | 72,175,962 | brace-inititialisation of boost::json::value converts it from an object to an array | In the below example I parse a json object using boost::json.
When I print the type of the returned boost::json::value it is of type object, as expected.
I then have 2 classes which are identical in every way, other than in BraceInit I initialise my member boost::json::value using brace initialisation and in ParenInit I initialise my member boost::json::value using parens.
Using brace initialisation causes my object to be converted into an array, of size 1, containing my original object.
#include <iostream>
#include <boost/json.hpp>
namespace json = boost::json;
void print_type(const json::value& jv)
{
switch (jv.kind())
{
case json::kind::object: std::cout << "object\n"; break;
case json::kind::array: std::cout << "array\n"; break;
default: std::cout << "other\n"; break;
}
};
struct BraceInit
{
BraceInit(json::value jv)
: _jv{jv}
{
print_type(_jv);
}
json::value _jv;
};
struct ParenInit
{
ParenInit(json::value jv)
: _jv(jv)
{
print_type(_jv);
}
json::value _jv;
};
int main()
{
const std::string str = R"({ "foo": "bar" })";
const json::value jv = json::parse(str);
print_type(jv);
BraceInit b(jv);
ParenInit p(jv);
return 0;
}
Output:
object
array
object
What is happening here?
Is my "brace initialisation" actually not doing brace initialisation as I expect, but rather creating an std::initializer_list of size 1?
| From [class.base.init]/7
The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in
the case of a delegating constructor, the complete class object) according to the initialization rules of 11.6 for
direct-initialization.
11.6 here refers to [dcl.init], which, under paragraph 17 states:
The semantics of initializers are as follows. The destination type is the type of the object or reference being
initialized and the source type is the type of the initializer expression. If the initializer is not a single (possibly
parenthesized) expression, the source type is not defined.
(17.1) — If the initializer is a (non-parenthesized) braced-init-list or is = braced-init-list, the object or reference is
list-initialized (11.6.4).
11.6.4 simply refers to [dcl.init.list].
So, to me, it sounds like _jv{jv} calls the initialization-list version of the constructor (if it exists), which, according to the boost documentation, produces an array.
Note: all items from C++17 draft N4659
You can see this in a simplified version here: https://godbolt.org/z/9qrf3EooY
Edit: cppreference simplifies this to:
A std::initializer_list object is automatically constructed when:
a braced-init-list is used to list-initialize an object, where the corresponding constructor accepts an std::initializer_list parameter
|
72,176,747 | 72,176,929 | cpp - alias for member functions` return types | I've been watching this CppCon talk where the speaker was talking about writing classes resistant to future changes. He provided the following code as an example (that I show here abridged):
template< typename Type, size_t Cap >
class FixedVector final
{
using iterator = Type*;
iterator begin();
}
My question is, basically the following - Does he use type aliasing here only because the type itself is already provided by the user of the class (and is a priory know to them)? I mean, if that was not the case, then there is not way the user can use the aliased return type, right?
| The point they are trying to make is if they had
template< typename Type, size_t Cap >
class FixedVector final
{
Type* begin();
}
and later they decide that instead of a Type*, they want to use a my_custom_iterator<Type>, then they need to make that change to all places that use Type*. By using
class FixedVector final
{
using iterator = Type*;
iterator begin();
}
if you want to make that same change it is as simple as changing
using iterator = Type*;
to be
using iterator = my_custom_iterator<Type>;
|
72,176,779 | 72,176,955 | How to return objects of different types from RcppArmadillo function | l would like to return objects of different types from the function RcppArmadillo.
For example, below is a code where I've tried returning both a vector and function using std::tuple.
#include <RcppArmadillo.h>
#include <tuple>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace arma;
// [[Rcpp::export]]
std::tuple<arma::vec, arma::mat> test_tuple(arma::vec avec, arma::mat amat) {
arma::vec bvec = avec;
arma::mat bmat = amat;
return std::make_tuple(bvec, bmat);
}
However, I get the following error:
static assertion failed: cannot convert type to SEXP
I also tried unsuccessfully using List::create as suggested here:
How to return multiple objects from Rcpp back to R?
How correctly return objects of different types and fix the above error?
| I'm not sure what you mean by "tried unsuccessfully" to use List::create. Does the following work for you?
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
Rcpp::List test_tuple(arma::vec avec, arma::mat amat) {
arma::vec bvec = avec;
arma::mat bmat = amat;
return Rcpp::List::create(
Rcpp::Named("avec") = avec,
Rcpp::Named("amat") = amat
);
}
|
72,176,896 | 72,176,942 | How to open fli files | I'm new to C++ and was tasked with processing a fli file, but have no idea how to open them correctly.
So far my code looks like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream newfile;
newfile.open("testvid.fli", ios::in);object
if (newfile.is_open()) {
string tp;
while (getline(newfile, tp)) {
cout << tp << "\n";
}
newfile.close();
}
std::cin.ignore();
}
But it gives me gibberish. Can anyone help?
| I haven't worked with .fli files before. Is it a FLIC file (used to store animations)? Then it makes sense that trying to reading them as strings produces gibberish. You could try either the Aseprite FLIC Library or LibFLIC.
EDIT: I used the Asperite's library and gif-h to convert a FLIC file to a GIF. Sorry for the inefficient code -- it's just a quick code to make it work.
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <vector>
#include <string>
#include <gif.h>
#include <flic.h>
int main() {
std::string fname_input { "../data/2noppaa.fli" };
std::string fname_output { "../data/2noppaa.gif" };
// Set up FLIC file
FILE *f = std::fopen(fname_input.c_str(), "rb");
flic::StdioFileInterface file(f);
flic::Decoder decoder(&file);
flic::Header header;
if (!decoder.readHeader(header)) {
std::cout << "Error: could not read header of FLIC file." << std::endl;
return 2;
}
const size_t frame_size = header.width * header.height;
// Set up FLIC reader
std::vector<uint8_t> buffer(frame_size);
flic::Frame frame;
frame.pixels = &buffer[0];
frame.rowstride = header.width;
// Set up GIF writer
GifWriter g;
GifBegin(&g, fname_output.c_str(), header.width, header.height, 0);
std::vector<uint8_t> gif_frame(frame_size * 4, 255);
flic::Color flic_color;
for (int i = 0; i < header.frames; ++i) {
if (!decoder.readFrame(frame)) {
break;
}
// Convert FLIC frame to GIF
for (size_t j = 0; j < frame_size; ++j) {
flic_color = frame.colormap[ frame.pixels[j] ];
gif_frame.at(j*4) = flic_color.r;
gif_frame.at(j*4 + 1) = flic_color.g;
gif_frame.at(j*4 + 2) = flic_color.b;
}
GifWriteFrame(&g, gif_frame.data(), header.width, header.height, 0);
}
GifEnd(&g);
}
|
72,176,917 | 72,206,586 | HDF5: How to read an array from a dataset | I have never seen this before, but I have a file with a 1x1 dataset where the only value is a Array[3] of 64-bit floating point. I can see this using the HDFView tool, but no matter what I try, I get errors. Is there a special type I need to create for this to work?
Edit if I use H5Sget_simple_extent_npoints() to get the number of data points, the result is 1. So, it appears to be 1 array of 3 elements.
The last thing I tried was manually reading 3 doubles:
hid_t dataset = ...; // open the dataset (dataset is valid)
double var[3];
hsize_t memdim[] = { 3 };
hid_t space = H5Screate_simple(1, memdim, nullptr); // (space is valid)
auto rc = H5Dread(dataset, H5T_NATIVE_DOUBLE, space, space, H5P_DEFAULT, &var[0]);
// rc = -1
Also tried just reading the whole dataset:
hid_t dataset = ...; // open the dataset (dataset is valid)
double var[3];
auto rc = H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &var[0]);
// rc = -1
Error text from the above tests:
HDF5-DIAG: Error detected in HDF5 (1.10.5) thread 17272:
#000: \hdf5-1.10.5\src\H5Dio.c line 199 in H5Dread(): can't read data
major: Dataset
minor: Read failed
#001: \hdf5-1.10.5\src\H5Dio.c line 467 in H5D__read(): unable to set up type info
major: Dataset
minor: Unable to initialize object
#002: \hdf5-1.10.5\src\H5Dio.c line 983 in H5D__typeinfo_init(): unable to convert between src and dest datatype
major: Dataset
minor: Feature is unsupported
#003: \hdf5-1.10.5\src\H5T.c line 4546 in H5T_path_find(): can't find datatype conversion path
major: Datatype
minor: Can't get value
#004: \hdf5-1.10.5\src\H5T.c line 4762 in H5T__path_find_real(): no appropriate function for conversion path
major: Datatype
minor: Unable to initialize object
| I figured out that there is an array type that can be made that is required:
hsize_t size = { 3 };
hid_t type = H5Tarray_create(H5T_NATIVE_DOUBLE, 1, &size);
hid_t dataset = H5Dopen(...);
double var[3];
hsize_t memdim[] = { 1 }; // or how many arrays[3]'s to read
hid_t space = H5Screate_simple(1, memdim, nullptr);
auto rc = H5Dread(dataset, type, space, H5S_ALL, H5P_DEFAULT, &var[0]);
|
72,177,171 | 72,177,230 | What does *&Var - 1.0f means? | Working with some tutorial, I met a strange C++ expression:
uint64_t var = ....
return (*&var) - 1.f;
What does this mean? Is it a reference to a pointer? What's the point of substracting 1 from reference? It should be an implementation of the LCG algorithm.
| var is an identifier. It names a variable.
The unary & operator is the addressof operator. The result of addressof operator is a pointer to the object named by its operand. &var is a pointer to the variable var.
The unary * operator is the indirection operator. Given a pointer operand, it indirects through that pointer and the result is an lvalue to the pointed object. It is an inverse of the addressof operator.
When you get the address to an object, and then indirect through that pointer, the resulting value is the object whose address you had taken. Essentially, in this case *&var is an unnecessarily complicated way to write var.
What's the point of substracting 1 from reference?
In this case, the referred value is an integer. The point of subtracting 1.f from an integer is to get a smaller value of floating point type.
|
72,177,241 | 72,181,588 | How to add C library to Visual Studio project | I am trying to add https://github.com/mlabbe/nativefiledialog this C library to my C++ project in visual studio 2022. I've built and generated the .lib file and added it to my project by going to Project->Properties->Linker. I added the path to this .lib file to Additional Library Directories. After doing this, I am still receiving "unresolved external symbol" linker errors. Specifically LNK2019 and LNK1120. I've also added the header file to the Additional Include Directories. What other steps am I missing?
Thanks for the help in advance!
EDIT:
Here is the code implementation:
StartupLayer.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "Walnut/Application.h"
#include "ExcelReader.h"
#include "nfd.h"
#define BUFFER_SIZE 255
class StartupLayer : public Walnut::Layer {
private:
ExcelReader reader;
char inputPath[BUFFER_SIZE] = "enter folder";
public:
StartupLayer() : reader(ExcelReader()) {}
~StartupLayer() {}
virtual void OnUIRender() override;
};
StartupLayer.cpp
#include "StartupLayer.h"
void StartupLayer::OnUIRender() {
ImGui::Begin("Select Folder");
ImGui::InputText("select folder", inputPath, BUFFER_SIZE);
// when browse button is clicked
if (ImGui::Button("Browse")) {
nfdchar_t* outpath = NULL;
nfdresult_t result = NFD_OpenDialog(NULL, NULL, &outpath);
}
ImGui::End();
}
It's a Dear ImGui project, and I wanted to use this open file dialog library in one of my layers. The above code is that layer class, and I'm getting the unresolved external symbol on the NFD_OpenDialog function call.
| I just forgot to add the path to the generated .lib file (nfd.lib) to Projects->Properties->Linker->Input Additional Dependencies. After doing this, everything worked perfectly.
|
72,177,535 | 72,177,598 | How can I include a C header that uses a C++ keyword as an identifier in C++? | I've been using C++ and compiling with clang++. I would like to include the <xcb/xkb.h> header for an X11 program I am writing.
Unfortunately this header uses explicit for some field names (such as line 727) and that is a keyword in C++.
Is there anyway to deal with this?
xcb/xkb.h:
// ...
#ifdef __cplusplus
extern "C" {
#endif
// ...
typedef struct xcb_xkb_set_explicit_t {
xcb_keycode_t keycode;
uint8_t explicit;
} xcb_xkb_set_explicit_t;
// ...
#ifdef __cplusplus
}
#endif
// ...
| Use a macro to rename the fields:
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wkeyword-macro"
#endif
#define explicit explicit_
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <xcb/xkb.h>
#undef explicit
Using a keyword as a macro name is ill-formed in standard C++, but GCC, Clang (with pragma), and MSVC do accept it. (The standard says you "shall not" do it, cppreference clarifies that it means "ill-formed".)
|
72,177,561 | 72,177,779 | OpenCV / C++ - OpenCV detect mouse click position and displays it, but doesn't draw a circle | I have this OpenCV Code where I want to draw a circle on a image each time i left click my mouse. It detect the position of my mouse at the time I pressed the left button and displays it aswell, but it doesn't draw a circle at the position.
Here is the code:
#include <iostream>
#include <vector>
#include <string>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
cv::Mat inputImage;
void Draw(int event, int x, int y, int flags, void* param)
{
if (event & cv::EVENT_LBUTTONDOWN)
{
std::cout << "X " << x << " Y " << y << std::endl;
cv::circle(inputImage, cv::Point(x, y), 25, cv::Scalar(0, 255, 0), cv::FILLED, cv::LINE_AA);
}
}
int main(int argc, char** argv)
{
std::string path = "C:\\Users\\dfad\\Downloads\\dyp.png";
inputImage = cv::imread(path);
cv::namedWindow("Image");
cv::setMouseCallback("Image", Draw, NULL);
cv::resize(inputImage, inputImage, cv::Size(800, 800), cv::INTER_LINEAR);
cv::circle(inputImage, cv::Point(130, 130), 10, cv::Scalar(0, 255, 0), cv::FILLED);
cv::imshow("Image", inputImage);
cv::waitKey(0);
return 0;
}
| Simply put:
cv::imshow("Image", inputImage);
into a while loop, so that it updates the image being displayed after drawing the circle.
|
72,177,691 | 72,177,958 | Designing a C++ concept with multiple invocables / predicates | I'm trying to make a C++20 concept by using an existing class as a blueprint. The existing class has 8 member functions that each take in a predicate:
struct MyGraphClass {
auto get_outputs(auto n, auto predicate) { /* body removed */ };
auto get_output(auto n, auto predicate) { /* body removed */ }
auto get_outputs_full(auto n, auto predicate) { /* body removed */ }
auto get_output_full(auto n, auto predicate) { /* body removed */ }
auto get_inputs(auto n, auto predicate) { /* body removed */ }
auto get_input(auto n, auto predicate) { /* body removed */ }
auto get_inputs_full(auto n, auto predicate) { /* body removed */}
auto get_input_full(auto n, auto predicate) { /* body removed */ }
/* remainder of class removed */
}
To support this in my concept, I've used 8 different concept parameters of std::predicate, one for each member function. The reason I did this (as opposed to using a single concept parameter for all predicates) is that the type of each predicate isn't known before-hand (e.g. an invocation of get_outputs(n, predicate) could be using a function pointer for the predicate while an invocation of get_inputs(n, predicate) could be using a functor for the predicate).
template<typename P, typename E, typename N, typename ED>
concept EdgePredicateConcept = std::predicate<P, E, N, N, ED>;
template<typename DG, typename N, typename ND, typename E, typename ED, typename EP1, typename EP2, typename EP3, typename EP4, tpyename EP5, typename EP6, typename EP7, typename EP8>
concept ConstantDirectedGraphConcept =
requires EdgePredicateConcept<EP1, E, N, ED>
&& requires EdgePredicateConcept<EP2, E, N, ED>
&& requires EdgePredicateConcept<EP3, E, N, ED>
&& requires EdgePredicateConcept<EP4, E, N, ED>
&& requires EdgePredicateConcept<EP5, E, N, ED>
&& requires EdgePredicateConcept<EP6, E, N, ED>
&& requires EdgePredicateConcept<EP7, E, N, ED>
&& requires EdgePredicateConcept<EP8, E, N, ED>
&& requires(DG g, N n, ND nd, E e, ED ed, EP1 ep1, EP2 ep2, EP3 ep3, EP4 ep4, EP5 ep5, EP6 ep6, EP7 ep7, EP8 ep8) {
{ g.get_outputs(n, ep1) } -> /* return removed */;
{ g.get_output(n, ep2) } -> /* return removed */;
{ g.get_outputs_full(n, ep3) } -> /* return removed */;
{ g.get_output_full(n, ep4) } -> /* return removed */;
{ g.get_inputs(n, ep5) } -> /* return removed */;
{ g.get_input(n, ep6) } -> /* return removed */;
{ g.get_inputs_full(n, ep7) } -> /* return removed */;
{ g.get_input_full(n, ep8) } -> /* return removed */;
/* remainder of requirements removed */
};
Since I don't know the exact types of the predicates beforehand, I'm not sure what to set EP1 - EP8 to when I'm applying this concept. Even if I did, the number of concept parameters makes this concept difficult to use.
Is there a sane way of getting this to work?
| I would do it this way.
First, your graph concept has several associated types. Similar to how a range in C++ has an iterator type (amongst others). We don't write range<R, I>, we just write range<R>. If R is a range, then it has some iterator type - we don't ask if R is a range with iterator I. We may not know I ex ante. Similarly, we have input_iterator<I>, and not input_iterator<I, value_type, reference, difference_type>. I defines those other things (if it's actually an iterator).
So we'll start with some aliases:
template <class G> using node_type = /* ... */;
template <class G> using edge_type = /* ... */;
// ...
Next, you want your graph type to accept an arbitrary predicate. There's no way to phrase arbitrary predicate in C++. But we can do the next best thing: just pick one arbitrary one. If the graph type works for some arbitrary private type that you define, it probably works for any such thing. Thus:
namespace impl {
template <class G>
struct some_predicate {
// intentionally not default constructible
// since predicate doesn't have to be
some_predicate() = delete;
// likewise doesn't have to be copyable, though you
// may just want to default these anyway (to allow
// having by-value predicates, for instance)
some_predicate(some_predicate const&) = delete;
some_predicate& operator=(some_predicate const&) = delete;
// but it does need this call operator
auto operator()(edge_type<G> const&,
node_type<G> const&,
node_type<G> const&,
edge_data_type<G> const&) const
-> bool;
};
}
We don't need to define that call operator since we're not using it anyway. But we can use some_predicate to build up our concept:
template <typename G>
concept ConstantDirectedGraphConcept =
requires(G g, node_type<G> n, impl::some_predicate<G> p) {
g.get_outputs(n, p);
g.get_output(n, p);
g.get_outputs_full(n, p);
g.get_output_full(n, p);
g.get_inputs(n, p);
g.get_input(n, p);
g.get_inputs_full(n, p);
g.get_input_full(n, p);
};
That should get you most of the way there. If a user's graph type works with this arbitrary predicate, then it probably will work for any arbitrary predicate.
Possibly (depending on how node_type and friends are defined) this needs to be:
template <typename G>
concept ConstantDirectedGraphConcept = requires {
typename node_type<G>;
typename edge_type<G>;
typename node_data_type<G>;
typename edge_data_type<G>;
} && requires(G g, node_type<G> n, impl::some_predicate<G> p) {
// ...
}
};
|
72,178,357 | 72,178,439 | Inheriting from template instanciated with incomplete type | I have a struct template like the following:
// S.h
#pragma once
#include <vector>
template <typename T>
struct S
{
std::vector<T*> ts;
virtual ~S() { for (auto* t : ts) t->foo(); }
void attach(T& t) { this->ts.push_back(&t); }
};
Then, I inherit a non-template struct, ConcreteS, from S<A>; struct A
being incomplete at this point, as I only forward declare it in
ConcreteS.h:
// ConcreteS.h
#pragma once
#include "S.h"
struct A;
struct ConcreteS : public S<A>
// struct A incomplete here ^
{
ConcreteS();
~ConcreteS() override;
};
I include A.h in ConcreteS.cpp to make the definition of struct A visible
to the implementation of ConcreteS's destructor:
// ConcreteS.cpp
#include "ConcreteS.h"
#include "A.h"
#include <cstdio>
ConcreteS::ConcreteS() { std::puts("ConcreteS()"); }
ConcreteS::~ConcreteS() { std::puts("~ConcreteS()"); }
Finally, I instanciate ConcreteS in function main:
// main.cpp
#include "ConcreteS.h"
int main()
{
ConcreteS concreteS{};
}
The above code compiles (and runs) fine with:
GCC 11.3.0;
Clang 14.0.0.
The output is:
ConcreteS()
~ConcreteS()
But fails to compile on:
Visual Studio 2019 (compiler: MSVC 19.29.30133.0);
Visual Studio 2013 (compiler: MSVC 18.0.40629.0).
Here you are the error message from VS13 (the one from VS19 is similar):
Microsoft (R) Build Engine version 12.0.40629.0
[Microsoft .NET Framework, version 4.0.30319.42000]
Copyright (C) Microsoft Corporation. All rights reserved.
Checking Build System
Building Custom Rule <proj_path>/CMakeLists.txt
cl : Command line warning D9002: ignoring unknown option '/permissive-' [<proj_path>\build_vs13\tmp.vcxproj]
A.cpp
ConcreteS.cpp
main.cpp
<proj_path>\S.h(10): error C2027: use of undefined type 'A' [<proj_path>\build_vs13\tmp.vcxproj]
<proj_path>\ConcreteS.h(5) : see declaration of 'A'
<proj_path>\S.h(10) : while compiling class template member function 'S<A>::~S(void)'
<proj_path>\ConcreteS.h(8) : see reference to class template instantiation 'S<A>' being compiled
<proj_path>\S.h(10): error C2227: left of '->foo' must point to class/struct/union/generic type [<proj_path>\build_vs13\tmp.vcxproj]
Generating Code...
Question: Who is right? Visual Studio or GCC/Clang?
For reference, I also post the declaration and definition of struct A and my
CMakeLists.txt:
// A.h
#pragma once
struct A
{
void foo() const;
};
// A.cpp
#include "A.h"
#include <cstdio>
void A::foo() const { std::puts("A::foo()"); }
# CMakeLists.txt
cmake_minimum_required(VERSION 3.6)
project(tmp)
add_executable(tmp A.cpp A.h ConcreteS.cpp ConcreteS.h S.h main.cpp)
if (MSVC)
target_compile_options(tmp PRIVATE /W4 /WX /permissive-)
else()
target_compile_options(tmp PRIVATE -Wall -Wextra -pedantic -Werror)
endif()
| Using S<A> as base class causes it to be implicitly instantiated.
Generally that wouldn't be a problem since your class doesn't require A to be complete when it is instantiated.
However, the definition of your destructor for S<A> requires A to be complete (because of the member access). That would normally also not be a problem, because generally definitions of member functions are not implicitly instantiated with implicit instantiation of the class template specialization, but only when they are used in a context requiring a definition to exist or in the case of the destructor when it is potentially invoked.
However, your destructor is virtual. For virtual member functions in particular it is unspecified whether they are instantiated with implicit instantiation of the containing class. ([temp.inst]/11)
So, the implementation may or may not choose to instantiate S<A>::~S<A> in the translation unit for main.cpp. If it does, the program will fail to compile since the member access in the definition is ill-formed for an incomplete type.
In other words, it is unspecified whether or not the program is valid and all mentioned compilers behave conforming to the standard.
If you remove virtual (and override) on the destructor(s) the only instantiation of the S<A> destructor allowed will be in the ConcreteS.cpp translation unit where A is complete and instantiation valid. The program is then valid and it should compile under MSVC as well.
|
72,178,685 | 72,178,798 | Counter for unique types where instances are independent from each other | I am attempting to create a counter for each unique template argument that the counter receives.
For example, I pass an int. The counter returns zero. I pass a float. The counter returns one. I pass an int again. The counter returns zero. Essentially, it generates a unique integer for each templated type.
struct Counter {
template<typename T>
int type();
int tick();
};
template<typename T>
int Counter::type() {
static int index = tick();
return index;
}
int Counter::tick() {
static int index = 0;
return index++;
}
int main() {
Counter countera;
Counter counterb;
std::cout << countera.type<int>() << std::endl;
std::cout << countera.type<float>() << std::endl;
std::cout << countera.type<double>() << std::endl;
std::cout << counterb.type<float>() << std::endl;
std::cout << counterb.type<int>() << std::endl;
std::cout << counterb.type<double>() << std::endl;
return 0;
}
Above we see an example of this counter. However, there is a problem. If I declare two instances of the counter, the next counter memorizes the order from the previous one. For example, the above code prints the order, 0 1 2 1 0 2. My ideal counter would print 0 1 2 0 1 2. I haven't explained why here, but for my purposes, this is a problem. The solution here seems to be more templates.
template<typename T, int Version>
int Counter<V>::type() {
static int index = tick();
return index;
}
Very similar to the previous code, however there is another template. Now, I can declare my counters like the following.
Counter<0> countera;
Counter<1> counterb;
This solution works, but I don't want to have to manually type in each number for each instance of the counter. I tried the following.
constexpr inline int tick() {
static inline int i = 0;
return i++;
}
template<typename T, int Version = tick()>
int Counter<V>::type() {
static int index = tick();
return index;
}
This however does not work as I have a non-constexpr variable inside a constexpr function. Does anyone know of a solution for this? Maybe an example for how I can approach this problem another way?
Thanks
Note: I am doing this for performance reasons. This will be called often and I want to avoid using maps.
Another Note: Integers must be contiguous. They will be used as indices into a deque. Therefore, any typeid() stuff won't work.
| You want the counter values to be computed at compile time, where different instances of Counter have separate counters. The main obstacle here is that it can't always be determined at compile time whether the counter instance that you're using is the same as some other counter instance that has already been used. In other words, when you do counter.type<T>(), the result depends on the current counter value of the Counter object that counter refers to. But that itself: the identity of that Counter object: may not be known at compile time. For example:
Counter countera;
Counter counterb;
countera.type<int>();
std::cin >> x;
std::cout << (x ? countera : counterb).type<double>();
The last line forces, at run-time, a check of the current counter value of whichever Counter instance the ternary expression evaluates to, to determine whether to return 1 or 0.
To solve this problem, you can specify which counter instance you want to use, in a manner that is guaranteed to be fixed at compile-time:
struct Counter {};
template <Counter& counter>
int tick() {
static int index = 0;
return index++;
}
template <Counter& counter, typename T>
int type() {
static int index = tick<counter>();
return index;
}
int main() {
static Counter countera;
static Counter counterb;
std::cout << type<countera, int>() << std::endl;
std::cout << type<countera, float>() << std::endl;
std::cout << type<countera, double>() << std::endl;
std::cout << type<counterb, float>() << std::endl;
std::cout << type<counterb, int>() << std::endl;
std::cout << type<counterb, double>() << std::endl;
return 0;
}
This gives your desired output. Godbolt
|
72,179,302 | 72,493,183 | Capturing post data from C++ application in Codeigniter 4 | I am upgrading our site from Codeigniter 3 to Codeigniter 4. So far it has been tedious, but mostly gone well. I am running into an issue now with a controller that will not recognize posted values from an app written in C++. This app has been working with CI 3 for many years now, but... well, CI4. I don't know all the details about the C++ app, but the developer assures me he is definitely using HTTP_VERB_POST to send the data to the controller. ----EDIT----- Here is the code from the C++ app that calls the controller in question:
subscriptioninfo = pSession->OpenRequest(CHttpConnection::HTTP_VERB_POST, address, NULL, NULL, NULL, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE);
I have created a view for the controller and CAN successfully Post values from a form using my browser.
However - Posting from the app 1) tells me the request method is GET and 2) NO values at all have been passed. It DOES however - send me the response I would expect if no values are passed to the controller......
After adding the following to my controller:
header('Access-Control-Allow-Origin: *');
echo $this->request->getMethod();
echo "\n POST VARS = ";
print_r($_POST);
echo "\n GET VARS = ";
print_r($_GET);
echo "\n";
I get the following result:
get
POST VARS = Array
(
)
GET VARS = Array
(
)
Activation: No
Error: No parameters sent.
The last two lines (Activation and Error) are what I would expect to get from this controller if, indeed, no parameters are sent.
Oh - and no, I do not have CSRF (except for default Cookie based CSRF Protection) enabled in my CI 4 application.
Any ideas would be greatly appreciated!
I've tried a number of different things, and think the issue is that CI4 is not receiving the Content-Type header from the C++ app. It is explicitly set with this:
CString strHeaders = _T("Content-Type: application/x-www-form-urlencoded");
Here is a simple print of the headers received by both CI4 and CI3 on the same server. (I have copied my old CI3 app to a directory called 'dev' inside the Public directory of CI4.)
Headers from CI3 in Public folder
host: test.site.com
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: Basic XXXXXXXXXXXXXXXXXXXX
Content-Type: application/x-www-form-urlencoded
Cookie: ci_session=9do54stine1po2c0tren49gr17eq068g
User-Agent: CustomName
X-Forwarded-For: 96.68.149.126
X-Forwarded-Port: 443
X-Forwarded-Proto: https
Content-Length: 164
Connection: keep-alive
Response from CI3
Subscription number: 9999999999999999
Activation: No
Error: Activation Key does not exist.
Headers from CI4
host: test.site.com
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: Basic XXXXXXXXXXXXXXXXXXXX
Cookie: ci_session=g6v3qlgms2bv3ijv19hpl3cgnvnbg4kk
User-Agent: CustomName
X-Forwarded-For: 96.68.149.126
X-Forwarded-Port: 443
X-Forwarded-Proto: https
Connection: keep-alive
Response from CI4
Subscription number:
Activation: No
Error: No parameters sent.
As you can see - the C++ app connects to the CI3 controller, with the Content-Type in the header and returns what I would expect given the parameters I passed in. However, CI4 is not receiving the Content-Type header and tells me that no parameters were passed.
Any thoughts as to why CI4 would be unable to recognize the Content-Type sent by the C++ app?
| Codeigniter 4 has the following in the public .htaccess file:
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
which removes the trailing slash from urls. REMming out those three lines
# Redirect Trailing Slashes...
# RewriteCond %{REQUEST_FILENAME} !-d
# RewriteCond %{REQUEST_URI} (.+)/$
# RewriteRule ^ %1 [L,R=301]
leaves the trailing slash in place. And now the C++ app is able to successfully post to the CI controller.
I don't know yet what can of worms that may open, but it did solve the problem.
|
72,179,447 | 72,179,926 | Alias that transforms a template type to the same type but templated on something different | I have a
template <typename T, typename U>
struct A;
and a
template <typename U>
struct B;
How do I make an alias that transforms an A<T, U> type to a A<T, B<U>> type? i.e. something that looks like this:
template <typename TypeA>
using ModifiedTypeA = TypeA<T, B<U>>; // <--- I don't know how to get T and U from TypeA
where ModifiedTypeA only needs to be templated on TypeA?
I was thinking that the above could be achieved if TypeA is always guaranteed to have member aliases
template <typename T_, typename U_>
struct A
{
using T = T_;
using U = U_;
};
and then do
template <typename TypeA>
using ModifiedTypeA = TypeA<typename TypeA::T, B<typename TypeA::U>>;
But is there another cleaner way + that doesn't make the above assumption?
| Try
template <typename TypeA, template<typename> typename TemplateB>
struct ModifiedTypeAWtihImpl;
template <template<typename, typename> typename TemplateA,
typename T, typename U,
template<typename> typename TemplateB>
struct ModifiedTypeAWtihImpl<TemplateA<T, U>, TemplateB> {
using type = TemplateA<T, TemplateB<U>>;
};
template <typename TypeA, template<typename> typename TemplateB>
using ModifiedTypeAWtih = typename ModifiedTypeAWtihImpl<TypeA, TemplateB>::type;
Demo
|
72,179,641 | 72,202,870 | using LLVM-C api from MSYS2 returns exit code 1, but using WSL works fine | i installed llvm+clang using MSYS2, and all the tools work fine for me, but the LLVM-C always returns exit code 1, here is my sample code:
#include <llvm-c/Core.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
LLVMModuleRef mod = LLVMModuleCreateWithName("my_module");
LLVMPrintModuleToFile(mod, "my_module.ll", NULL);
LLVMDisposeModule(mod);
return 0;
}
it compiles on MSYS2, but it returns exit code 1, and does not write the module to the file,
but when compiled using WSL, it returns exit code 0 and writes to the file.
i am using these MSYS2 packages:
https://packages.msys2.org/package/mingw-w64-x86_64-clang?repo=mingw64
https://packages.msys2.org/package/mingw-w64-x86_64-llvm?repo=mingw64
i did not try the C++ LLVM api, but i am assuming that does not work as well.
here are the commands i run:
powershell:
$x = llvm-config --cflags --ldflags core --system-libs --libs
clang $x hello.c -fuse-ld=lld
./a.exe
echo $lastExitCode # returns 1
bash:
clang `llvm-config --cflags --ldflags core --system-libs --libs` hello.c
./a.out
cat my_module.ll
| nvm i fixed it, my solution is that instead of using powershell, i used the MSYS2 (MinGW-w64) shell.
|
72,180,103 | 72,187,635 | How to get a control's handle in WinUI3 in C++? | I am working on a C++ WinUI3 project and got this problem. How do I obtain the handle of a XAML grid?
Something like this in QT can achieve it:
HWND m_hWnd;
m_hWnd = (HWND)(ui.label->winId());
But I couldn't find the similar thing in WinUI3.
I look up on the Internet, but only find this solution which is in C#:
Get-a-controls-handle-in-XAML
And the Microsoft provide this, but it is only working for window handle, not XAML controls.
Retrieve a window handle (HWND)
Could anyone help me with it? Any suggestions will be great!
|
How do I obtain the handle of a XAML grid?
You can't because there is none.
All XAML controls on the screen are ultimately backed by a single HWND that belongs to the parent window, i.e. an individual control doesn't have its own handle in Win UI.
There is only a single top-level handle and the controls are rendered as content inside this HWND.
|
72,180,112 | 72,180,141 | When should I mark the static method of a specific class as private other than public? | When should I mark the static method of a specific class as private other than public?
What aspects should I consider when making such considerations.
What are the advantages for mark the static method as private?
Any simple example would be appreciated, which could help me fully understand this matter.
UPDATE:
As per this answer, which says that[emphasise mine]:
This function could easily have been made freestanding, since it doesn't require an object of the class to operate within. Making a function a static member of a class rather than a free function gives two advantages:
It gives the function access to private and protected members of any object of the class, if the object is static or is passed to the function;
It associates the function with the class in a similar way to a namespace.
How to fully understand the statements above?
| The general rule for methods (static or otherwise) is to make them private if possible — i.e. unless you absolutely need them to be callable from other classes (which is to say, you need them to be part of your class’s public API)
The reason for making as much as possible private is simple: in the future, you’ll be able to change anything that is private, without breaking a bunch of other classes that were written to call the old version of the method. Changing a public method is more problematic, because other classes might be depending on it.
|
72,180,366 | 72,181,790 | I run `"crash_demo.run"` by `spawn-fcgi` . How to collect `core` file | 1. Question
I run "crash_demo.run" by spawn-fcgi .
How to collect core file .
2. Background & Environment
I'm exolore C++ Web Programming .
web-server : nginx
CGI(FastCGI) : fastcgipp 3.0
CGI Wrapper : spawn-fcgi
I didn't use FCGI Wrap which ngifix supplied .
I understand FCGI Wrap be drive by spawn-fcgi , Of course this is off topic .
My c++ application . (be called crash_demo) .
3. Step to reproduce exception
crash_demo insert code throw "test exception str, check _core_ file" , build got crash_demo.run
run nginx : sudo nginx -c my_nginx_custom.config
ulimit -c unlimited
run crash_demo.run by spawn-fcgi : spawn-fcgi -a 127.0.0.1 -p 9000 -f /path/crash_demo.run
test the normal http request , and http request can be completed normally .
test the crash_demo http request , got 5xx response .
The directory where crash_demo.run is located does not see the core file
My guess
core file not generate .
core file is generated , but i don't the file path .
Does anyone know what happened?
Solution update
My question is flawed .
Thanks @sehe , my step :
I read two webpage
https://man7.org/linux/man-pages/man5/core.5.html
https://zhuanlan.zhihu.com/p/240633280
update my /proc/sys/kernel/core_pattern
core -> core_%e_%p_%t
ulimit -c unlimited
spawn-fcgi -a 127.0.0.1 -p 9000 -f /path/crash_demo.run
sudo find / core_ | grep core_crash_demo
result /path/core_crash_demo._5080_1652169152
So , my guess on my question is failed .
The fact is , I don't generate core file , when my question.
When my generated core file successed , the core file path is crash_demo.run parent directory .
Solution update 2
we whant to know two point :
how generate core dump file
how to fine exception code by core dump file
how generate core dump file?
Reference the file : core manual
core manual write many point , I just list the point i care :
system limit core dump file size , we need unlimit it:
ulimit -a check limit / ulimit -c unlimited cancel limit
fix /proc/sys/kernel/core_pattern
default value is core
fix it to -> core_%e_%p_%t mean core_your_execute_file_name_pid_timestemp
fix cmd : sudo bash -c 'echo core_%e_%p_%t > /proc/sys/kernel/core_pattern'
now run your exception , you can got core file .
maby you need search it : sudo find / core_ | grep core_
how to fine exception code by core dump file ?
I use vscode , fix launch.json , add coreDumpPath , refrence : https://code.visualstudio.com/docs/cpp/cpp-debug#_memory-dump-debugging
| This question is probably more for askubuntu.com or serverfault.stackexchange.com.
You likely need to configure core dump. Since we don't know the platform, I'm assuming likely a Linux. See e.g. core(5):
There are various circumstances in which a core dump file is not
produced
In my experience what's required is setting a core pattern (/proc/sys/kernel/core_pattern)
|
72,180,865 | 72,180,947 | Is there any in-built function or header file I need to add for Single Inheritance? | This Single Inheritance code has no error but when I run this void the function void B::get_ab() gets executed first as expected, but the line which is second in the function(cin>>a>>b;) gets executed first and then the first line, anyone know whats happening here?
#include<iostream>
#include<stdio.h>
using std::equal_range;
using std::lower_bound;
using std::upper_bound;
using std::pair;
using std::string;
using std::getline;
using std::vector;
using std::cout;
using std::ios;
using std::set;
using std::cin;
class B
{
int a;
public: int b;
void get_ab();
int get_a(void);
void show_a(void);
};
class D:private B{
int c;
public: void mult();
void display();
};
void B::get_ab()
{
cout<<"Enter values of a&b";
cin>>a>>b;
}
int B::get_a()
{
return a;
}
void B::show_a()
{
cout<<"a="<<a<<"\n";
}
void D::mult()
{
get_ab();
c=b*get_a();
}
void D::display()
{
show_a();
cout<<"b="<<b<<"\n"<<"c="<<c<<"\n";
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
D d;
d.mult();
d.display();
return 0;
}```
| The reason for this is that you untied the cin from the cout, in the cin.tie(0);. You can't expect the output to be flushed before the program prompts input from the user.
If you need to preserve this configuration for some reason (i.e. untied streams) and still need the prompt to be printed, you need to flush the output explicitly (e.g. by using either std::flush or std::endl I/O manipulators).
You may want to check this thread: Force std::cout flush print to screen.
And this one: Why do we need to tie std::cin and std::cout
|
72,181,800 | 72,188,787 | C++ Variadic function with inherited objects references and base class | I am writing a class to implement and signal-slot mechanism.
The signal can emit a series of events that are all derived from a base struct called "base_event". Below is how I defined the base_event and an example of a derived struct:
struct base_event
{
std::string _id = "base_event";
};
struct select_next_event : public base_event
{
select_next_event(uint32_t tr_num) : base_event(), _tr_num(tr_num)
{
base_event::_id = "select_next_event";
};
uint32_t _tr_num;
};
Then my emit function signature is:
template<typename... Args>
void emit(Args... args)
{
..... All the logic .....
}
Then when I want to emit an event, I write something like:
slot.emit(select_next_event{3});
Up to there, everything is working fine.
My issue is that I would like to add an asynchronous (non-blocking) emit function to my library. To that goal, I write a second function (I am using c++20 so I can do perfect forwarding):
void emit_async(Args... args)
{
auto send_async = std::async(std::launch::async,
[this, ... args = std::forward<Args>(args)](){ emit(std::forward<Args>(args)...); });
}
The problem arises if I write:
slot.emit_async(select_next_event{3});
Then when I read the event in my slot function, the value of _tr_num is not forwarded (always equal to 0)
However, if I write :
auto send_async = std::async(std::launch::async,
[this](){slot.emit(select_next_event{3});});
Then the value of _tr_num is correctly forwarded to the slot function.
I do not see where is my error?
Pi-r
[EDIT]
As requested, and sorry for my lack of clarity, please find bellow a minimal example that demonstrates my problem:
#include <iostream>
#include <utility>
#include <future>
#include <vector>
struct base_event
{
std::string _id = "base_event";
};
struct select_next_event : public base_event
{
select_next_event(uint32_t tr_num) : base_event(), _tr_num(tr_num)
{
base_event::_id = "select_next_event";
};
uint32_t _tr_num;
};
template<typename... Args>
void emit(Args... args)
{
int i = 0;
([&] (auto & arg)
{
++i;
std::cout << "input " << i << " = " << arg._id.c_str() << " " << arg._tr_num << std::endl;
} (args), ...);
}
template<typename... Args>
void emit_async(Args... args)
{
auto send_async = std::async(std::launch::async,
[... args = std::forward<Args>(args)](){ emit(std::forward<Args>(args)...); });
}
int main()
{
emit(select_next_event{3});
//emit_async(select_next_event{3}); // if added, it produces a compilation eror
}
I do compile the code with:
g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
I think this example presents the problem I have as if I remove the comment for the async, I do have a compilation error:
main.cpp:38:82: error: binding reference of type ‘std::remove_reference<select_next_event>::type&’ {aka ‘select_next_event&’} to ‘const select_next_event’ discards qualifiers
I do hope that now I have created a clearer explanation of my issue! If anything is missing/misleading, please let me know!
| There are two problems here.
First, emit_async(Args... args) is pass by value, so Args... is always a value type, you need to add forwarding reference to it.
Second and more important, you construct args with init-capture [... args = std::forward<Args>(args)], but since lambda's operator() is implicitly const, you cannot forward args in the function body since args are also const-qualified, instead you need to add mutable keyword for lambda
template<typename... Args>
void emit_async(Args&&... args) {
auto send_async = std::async(
std::launch::async,
[...args = std::forward<Args>(args)] mutable
{ emit(std::forward<Args>(args)...); });
}
Demo
|
72,181,983 | 72,182,759 | After running qmake, how to make debug/release? | The qmake project file (.pro) contains
CONFIG -= debug_and_release
I would like to keep project file as it is but decide later (from the command line) to do debug or release build.
Currently, when I build from command line
qmake project.pro
make
It does a release build.
How can I choose debug/relase from the command line?
I tried make debug and it returns
make: *** No rule to make target `debug'. Stop.
Then I tried make release and it returns
make: *** No rule to make target `release'. Stop.
| You can simply do this by followed command
qmake project.pro "CONFIG+=debug"
make
|
72,182,067 | 72,182,135 | Reversing vectors in a vector error troubleshoot | vector<vector<string>> Reverse(vector<vector<string>> a){
vector<string> dd;
for(int i = 0; i < a.size()/2; i++){
dd = a[i];
a[i] = a[-1*(i) - 1];
a[-1*(i) - 1] = dd;
}
return a;
}
I want to make a Reverse function that reverses vectors in a vector but i get and error:
libc++abi: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
| You are trying to access negative positions in a vector. Positions starts from 0 to vector.size(). It's very bad what you are doing.You are getting a matrix and try to transform it in a vector?
You should review your code. Maybe you meant something like this?
vector<vector<string>> reverseRows(vector<vector<string>> a){
for(int i=0;i<a.size();i++){
for(int j=0;j<a[i].size()/2;i++){
string temp=a[i][j];
a[i][j]=a[i][a[i].size()-j-1];
a[i][a[i].size()-j-1]=temp;
}
}
return a;
}
vector<vector<string>> reverseMatrix(vector<vector<string>> a){
for(int i=0;i<a.size()/2;i++){
vector<string> temp=a[i][j];
a[i][j]=a[i][a[i].size()-j-1];
a[i][a[i].size()-j-1]=temp;
}
return a;
}
|
72,182,138 | 72,182,190 | Calling C++ standard header (cstdint) from C file | I have an external library written in C++ such as
external.h
#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H
#include <cstdint>
extern "C" uint8_t myCppFunction(uint8_t n);
#endif
external.cpp
#include "external.h"
uint8_t myCppFunction(uint8_t n)
{
return n;
}
Currently I have no choice but use this C++ library in my current C project. But my compiler is telling me
No such file or director #include <cstdint>
when used in my C project
main.c
#include "external.h"
int main()
{
int a = myCppFunction(2000);
return a;
}
I understand that this is because cstdint is a C++ standard library that I'm trying to use through my C file.
My questions are:
Is there a way I can manage to use this C++ library in my C project without modifying my libary ?
If no, what whould I have to do on the library side to make it possible ?
| The c prefix in cstdint is because it's really a header file incorporated from C. The name in C is stdint.h.
You need to conditionally include the correct header by detecting the __cplusplus macro. You also need this macro to use the extern "C" part, as that's C++ specific:
#ifndef OUTPUT_FROM_CPP_H
#define OUTPUT_FROM_CPP_H
#ifdef __cplusplus
// Building with a C++ compiler
# include <cstdint>
extern "C" {
#else
// Building with a C compiler
# include <stdint.h>
#endif
uint8_t myCppFunction(uint8_t n);
#ifdef __cplusplus
} // Match extern "C"
#endif
#endif
|
72,182,178 | 72,183,940 | Converting a Console Program into an MFC app (Thread issues) (Pleora SDK) | Back to stackoverflow with another question after hours of trying on my own haha.
Thank you all for reading this and helping in advance.
Please note the console program has following functionalities:
connect to a frame grabber
apply some configs
store the incoming data (640 * 480 16-bit grayscale imgs) in a stream of buffers inside a while loop
Exits the while loop upon a key press.
disconnect from device
And I'm only adding the displaying the images functionality on the MFC GUI app. In short,
i) Converting a console app to an MFC app (dialog based)
ii) decided to use thread for displaying images, but DK how to properly exit from thread when there are certain tasks to be done (such as call disconnectFromDevice(); freeBuffers();, etc) before exiting the thread.
iii) have tried making the while loop condition false but didn't work
( I actually want this to be a callback function that's called repeatedly but IDK how to implement it inside a thread)
iv) forcing AfxEndThread didn't work and it's not even the way it should be done (I think).
So my question is,
1. Are you supposed to use a while loop to excuete a certain job that should repeatedly be done? If not, do you have to implement a callback inside a thread? Or use Windows message loop? Why and how? Please provide a hello-world-like sample code example
(for example, you are printing "hello world" repeatedly inside a thread with a condtion in an MFC GUI app. How do you update or check the condition to end the thread if you can't just AfxEndThread() inside the threadproc)
2. If it's ok with a while, how do you exit from the while loop, in other words how do you properly update the exit condition outside the thread the while loop's in?
Please refer to the source code in the provided link
ctrl+F OnBnClickedConnectButton, AcquireImages and OnBnClickedDisconnectButton
https://github.com/MetaCortex728/img_processing/blob/main/IR140Dlg.cpp
| Worker threads do not have message-queues, the (typically one and only) UI one does. The message-queue for a thread is created by the first call of the GetMessage() function. Why use messages to control processing in a worker thread? You would have to establish a special protocol for this, defining custom messages and posting them to the queue.
Worker threads can be implemented as a loop. The loop can be terminated based on various conditions, like failures to retrieve any data or request from the user. You can simply exit the thread proc to terminate the thread's execution. If the thread doesn't respond it may have stuck (unless it performs a really lengthy operation) and the UI thread must provide some mechanism to kill it. That is first request termination and if it doesn't respond within some set time then kill it.
The condition mechanism to terminate should best be some synchronization object (I would recommend a manual-reset event), interlocked variable or a simple boolean which you should access and set using a critical section.
Some considerations:
You pass a parameter block to the thread. Make sure that it remains alive throughout the thread's lifetime. For example, it should NOT be a local variable in a function that exits before the thread's termination.
The loop must be "efficient", ie do not loop infinitely if data are not available. Consider using blocking functions with timeouts, if available.
Resource management (eg connecting/disconnecting, allocating/releasing etc) should best be performed by the same thread.
An alternative implementation can be APCs. Then the thread's proc function is a while(!bTerminate) { SleepEx(INFINITE, TRUE); } loop, and other threads issue requests using a the QueueUserAPC() function.
The AfxEndThread(0) call in OnBnClickedDisconnectButton() is wrong, it terminates the current thread, which in this case is the main (UI) thread. Check the documentation.
A sidenote, my suggestion about the project type is not a dialog-based application but instead a normal MFC application without a document class (uncheck the Document/View architecture support option), as it offers features like menus, toolbars and the like, and most importantly the ON_UPDATE_COMMAND_UI handlers.
|
72,182,371 | 72,182,462 | How to overload the operator[] with multiple subscripts | C++23 added support for overloading operator[] with multiple subscripts. It's now available on GCC 12. How should one make use of it?
An example struct:
struct Foo
{
int& operator[]( const std::size_t row,
const std::size_t col,
const std::size_t dep )
{
return matrix[row][col][dep];
}
int matrix[5][5][5];
};
I want to use it like this:
Foo fooObject;
fooObject.matrix[ 0, 0, 0 ] = 5;
But it does not compile;
error: incompatible types in assignment of 'int' to 'int [5][5]'
It also shows a warning:
warning: top-level comma expression in array subscript changed meaning in C++23 [-Wcomma-subscript]
| fooObject[ 0, 0, 0 ] = 5;
not
fooObject.matrix[ 0, 0, 0 ] = 5;
you should also add compile option --std=c++23.
|
72,182,444 | 72,184,703 | How do I find the element by coordinate in VTK? | I have a mesh file generate by Gmsh(*.vtu), the mesh is a cube area and consist of tetrahedrons. Then I have a point (given by coordinate) in the cube, I want to find which tetrahedron contains the point, how did I do?
with pygmsh.occ.Geometry() as geom:
geom.add_box([0, 0, 0],
[1, 1, 1], mesh_size=0.1)
mesh = geom.generate_mesh()
mesh.write('original_gmsh.vtu')
uGridReader = vtkXMLUnstructuredGridReader()
uGridReader.SetFileName('original_gmsh.vtu')
uGridReader.Update()
uGrid: vtkUnstructuredGrid = uGridReader.GetOutput()
givenPoint = [0.5, 0.5, 0.5]
| You should be able to use the FindAndGetCell() method that vtkUnstructuredGrid inherits from vtkDataSet. The python documentation for this can be found using help(vtkUnstructuredGrid.FindAndGetCell) within your python shell (assuming you have imported vtkUnstructuredGrid, if not prepend with vtk. as usual.
As a recommendation, consider check out the PyVista package, its far easier to use in my experience and uses VTK as its backend as well.
|
72,182,753 | 72,187,449 | How can I inspect DYLIB contents in terms of size? | After moving from a manually created Xcode project to a CMake-generated Xcode C++ project, my compiled binary DYLIB size has grown significantly: from about 35 MB to about 53 MB.
All the compilation and linking settings I could compare in Xcode projects look pretty much the same (including vs. not including debug symbols, optimization levels, etc.). I wonder if there are any tools to inspect DYLIB contents - what occupies size in the first place.
| I would personally go with nm tool. You can inspect any DYLIB file iteratively, section-by-section or just print everything:
nm -a /path/to/my/lib.dylib
|
72,183,078 | 72,183,635 | How to store a state of custom allocator used for allocation of different types | In a situation where one needs to work with custom stateful allocator, what is the idiomatic way to store the state, if the state should be used to allocate objects of different types? E.g. if one needs a allocator-aware object, that uses data-structures of different types, such as the following:
struct Foo
{
std::vector<int> ints;
std::vector<double> doubles;
void bar() { std::vector<std::string> strs; }
}
I tried two solutions:
(1)
template<typename Alloc>
struct Foo
{
Foo(const Alloc& alloc) : alloc(alloc), ints(alloc), doubles(alloc) {}
Alloc alloc;
std::vector<int, typename std::allocator_traits<Alloc>::template rebind_alloc<int>> ints;
std::vector<double, typename std::allocator_traits<Alloc>::template rebind_alloc<double>> doubles;
void bar() { std::vector<std::string, typename std::allocator_traits<Alloc>::template rebind_alloc<std::string>> strs(alloc); }
};
custom_allocator<char> alloc(state); // any type, will be rebound
Foo<custom_allocator<char>> foo(alloc);
Assuming the state of the allocator is easy to copy, than this solution is fine, but writing the rebind machinery (typename allocator_traits::template rebind) and the fact that I have to specify (some) type (char) is giving me a headache.
(2)
template<template<typename> typename Alloc>
struct Foo
{
struct dummy_t{};
Foo(const Alloc<dummy_t>& alloc) : alloc(alloc), ints(alloc), doubles(alloc) {}
Alloc<dummy_t> alloc;
std::vector<int, Alloc<int>> ints;
std::vector<double, Alloc<double>> doubles;
void bar() { std::vector<std::string, Alloc<std::string>> strs(alloc); }
};
custom_allocator<char> alloc(state); // any type, will be rebound, or
custom_allocator alloc2(state); // if I make <T = char> in my allocator implementation
Foo<custom_allocator> foo(alloc);
Which seems better with the declaration noise, but is somehow different to how STL looks (as that accepts a specific allocator, whereas (2) accepts an allocator template).
Ideally I would want a single allocator (i.e. non-template) with templated construct, as that wouldn't require any rebinding/conversions, but that's sadly not what the STL containers accept.
Am I missing something obvious, or are these ((1) or (2)) the reasonable ways?
EDIT:
In my proposals the state of the allocator is actually not shared between the vectors, but rather copied, but I am fine with that, as in my problem, the state is immutable.
| Maybe you can use pmr.
#include <vector>
#include <memory_resource>
struct foo {
std::pmr::memory_resource& mem {*std::pmr::get_default_resource()};
std::pmr::vector<int> vi{&mem};
std::pmr::vector<double> vd{&mem};
};
|
72,183,897 | 72,184,096 | setw() and setfill() not working...what am i doing wrong? | what i am trying to do is print double datatype with precision 2,setw(15),fill spaces with _(underscore) and with prefix - or +.for example if number is 2006.008 output should be _______+2006.01
my code is :
cin>>b;
if(b>0){
cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<"+"<<b<<endl;
}
else{
cout<<setw(15)<<setfill('_');
cout<<fixed<<setprecision(2)<<"-"<<b<<endl;
}
output i am getting is :
______________+2006.01
difference: my output is getting 14 underscores
but in result there should be only 7 underscores
what i tried?
without prefix my answer is accurate because if i am adding prefix setw(15) is counting my prefix as 15th character and adding 14 underscores before it
| The io-manipulators apply to single insertions to the stream. When you insert "+" into the stream, then the width of it is 1 and the remaining 14 are filled with _ because of setfill('_').
If you want io-manipulators to apply to concatenated strings you can concatenate the strings. I use a stringstream here, so you can apply setprecision and fixed:
if(b>0){
std::stringstream ss;
ss << "+" << fixed << setprecision(2) << b;
cout << setw(15) << setfill('_') << s.str() << endl;
|
72,183,914 | 72,184,101 | How copy initialization works in the case of argument passing to a function? | I googled about copy initialization and found out that whenever we write T a = b; ,copy initialisation takes place. It was also mentioned that copy initialization also takes when we pass arguments by value in a function call.
I wanted to know that whenever we pass arguments to a function, is the " = " operator used by the compiler to copy initialize the parameters of the function? I know that "=" is not needed in syntax of the function call but does the copy initialization itself use "=" during function call by value?
For example , In the code given below :
#include<iostream>
using namespace std;
void fun(T1 x, T2 y){
// some code
}
int main(){
T1 a;
T2 b;
solve(a,b);
}
Does initialization of parameters take place as T1 x = a ; and T2 y = b ; ? Is the "=" operator involved during the copy initialization of parameters in the function?
| Argument passing to the parameter of a function happens using copy initialization which is different than using copy assignment operator=. Note that initialization and assignment are two different things in C++. In particular, passing argument happens using "copy initialization" and not "copy assignment".
From decl.init.general#14:
The initialization that occurs in the = form of a brace-or-equal-initializer or condition ([stmt.select]), as well as in argument passing, function return, throwing an exception ([except.throw]), handling an exception ([except.handle]), and aggregate member initialization ([dcl.init.aggr]), is called copy-initialization.
(end quote)
Similarly, from copy initialization:
Copy initialization is performed in the following situations:
when passing an argument to a function by value
(end quote)
Also, note that the order of the copy initialization of the parameter from the arguments is unspecified.
Does initialization of parameters take place as T1 x = a ; and T2 y = b ; ?
In your example, when you passed arguments a and b to parameters x and y, the observed behavior would be as if we wrote T1 x = a; and T2 y = b;. You can verify this using this demo. Note again that the order of copy is unspecified.
|
72,184,084 | 72,184,282 | Does declaring struct Name make Name equivalent to struct Name? | I am a bit confused when using struct in c/c++. Traditionally, when I use struct, I usually use it as:
typedef struct Name{
int a;
};
Name var;
Although it is considered a bad practice from Linus, it's somehow common.
Yet, I wonder
struct Name{
int a;
};
Name var;
Seems to serve the same purpose, is typedef really necessary?
In fact, shouldn't it be
struct Name{
int a;
};
struct Name var;
Why is the struct from "Name" omitted? If it can always be omitted, does that mean typedef struct is totally useless?
| For:
typedef struct Name{
int a;
};
Name var;
The definition should be:
typedef struct Name{
int a;
} Name;
Name var;
Otherwise you are not aliasing the type.
In C++ this doesn't make sense, when you declare struct Name you can already instantiate Name omitting the struct keyword, as you do in the second code snippet, which would not work for C. It behaves similarly to class, in this regard, you don't declare class Name var;, just Name var;.
In C I don't agree it's a bad practice, it's a user defined type, why would you always use struct if you can omit it, any programmer worthy of that name should be able to identify a user defined type, it's not rocket science. This though is opinion based. If it's bad practice we will need to revise the whole notion, not only in C++ but also C#, where class and struct keywords are always omitted when instantiating objects.
As for aliasing pointers, I completely agree, I do not like it one bit, though this can also be seen as opinion based.
So to answer your direct questions:
Seems to serve the same purpose, is typedef really necessary?
For the purpose you describe in C yes, in C++ no.
Why is the struct from "Name" omitted?
In C it cannot be ommited, unless you typedefine it, in C++ not only it can, but it should, it's not needed at all.
If it can always be omitted, does that mean typedef struct is totally useless?
As you can see, it's not useless.
|
72,184,108 | 72,193,723 | Boost space in path not being handled correctly | I'm using the Boost process header and I can't seem to get the boost::process::system to take in my .cpp file path due to a space in the directory.
auto path = bp::search_path("g++");
int result = bp::system(path, "\"C:\\Users\\Sachin Chopra\\Documents\\rchat\\console_process\\src\\main.cpp\"");
I get the following error when I execute my code:
g++.exe: error: "C:\Users\Sachin: Invalid argument
g++.exe: error: Chopra\Documents\rchat\console_process\src\main.cpp": No such file or directory
g++.exe: fatal error: no input files
The file path formatting works for me .exe file, and will launch from boost if I use it. e.g.
bp::system("\"C:\\Users\\Sachin Chopra\\Documents\\rchat\\build\\console_process\\consoleproc.exe\"");
But when I introduce the g++ path, it seems to mess up. Any help would be appreciated.
Cheers.
| You're confusing shell script with the system interface.
You can either use old style, error-prone system:
bp::system(R"(bash -c "echo hello; echo world")");
Or you can pass raw arguments instead of relyng on shell escaping
bp::system(bp::search_path("bash"),
std::vector<std::string>{
"-c",
"echo foo; echo bar",
});
Which could also be written more like
bp::system(bp::search_path("bash"), "-c", "echo 42; echo answer");
In fact, you should probably use the bp::child interace instead of the
system compatible one:
bp::child compiler_job(
bp::search_path("g++"),
R"(C:\Users\Sachin Chopra\Documents\rchat\console_process\src\main.cpp)");
compiler_job.wait_for(5s);
if (compiler_job.running()) {
compiler_job.terminate();
}
int result = compiler_job.exit_code();
std::cout << "compiler_job exit_code: " << result << "\n";
Live Demo
Live On Coliru
#include <boost/process.hpp>
#include <iostream>
namespace bp = boost::process;
using namespace std::chrono_literals;
int main() {
// either use old style, error-prone system
bp::system(R"(bash -c "echo hello; echo world")");
// or pass raw arguments instead of relyng on shell escaping
bp::system(bp::search_path("bash"),
std::vector<std::string>{
"-c",
"echo foo; echo bar",
});
// Which can aslo be written as
bp::system(bp::search_path("bash"), "-c", "echo 42; echo answer");
// in fact, you should probably use the `bp::child` interace instead of the
// `system` compatible one:
bp::child compiler_job(
bp::search_path("g++"),
R"(C:\Users\Sachin Chopra\Documents\rchat\console_process\src\main.cpp)");
compiler_job.wait_for(5s);
if (compiler_job.running()) {
compiler_job.terminate();
}
int result = compiler_job.exit_code();
std::cout << "compiler_job exit_code: " << result << "\n";
}
Prints e.g.
hello
world
foo
bar
42
answer
g++: error: C:\Users\Sachin Chopra\Documents\rchat\console_process\src\main.cpp: No such file or directory
g++: fatal error: no input files
compilation terminated.
compiler_job exit_code: 1
|
72,184,187 | 72,184,456 | return address of dlsym and Address of Function Pointer assigned | void* l = dlsym(lib,"_ZN11Environment9LibLogger14log_processingEiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEjS6_z");
*(void **)&log_fcn = l;
std::cout<<"Address"<<<<l<<"LOG_FCN "<<log_fcn<<std::endl;
I am trying to print address of l and log_fcn but both are not same. Why is that, and how can I get address of dlsym assign to function pointer?
Output example:
l= 0x7efe10eabaa0 LOG_FCN 1
void (*log_fcn)(int level, std::string frmt, unsigned int line_no, std::string file_name, ...); function decleration
| There is an operator << for void*, but not for function pointers.
Function pointers are implicitly converted to bool, not void*, and bool prints as 0 or 1 by default.
Your 1 output indicates that log_fcn is not the null pointer.
Convert it when printing:
std::cout << "Address" << l << "LOG_FCN "<< reinterpret_cast<void*>(log_fcn) << std::endl;
I would recommend that you also do the assignment in the conventional form, by casting the right-hand side:
log_fcn = reinterpret_cast<decltype(log_fcn)>(l);
|
72,184,430 | 72,185,959 | QT C++ access to a Class Member of another Class | i really dont understand the following behavior:
3 Code snippets to explain
sqlconnection.h
class SqlConnection
{
public:
SqlConnection();
QSqlDatabase db;
} ;
sqlconnection.cpp
SqlConnection::SqlConnection()
{ if (!db.open()){ //no different with or without that
db = QSqlDatabase::addDatabase("QODBC");
...
}
artikelverwaltung.cpp
Artikelverwaltung::Artikelverwaltung(){
SqlConnection().db.open();
...(code to do works fine)
}
void Artikelverwaltung::on_pushButton_2_clicked()
{
SqlConnection().db.close(); // "HERE"
}
"HERE" it cycles the full Contructor of the Class again, but why it don't just close the connection? (this is the Main question about and how to fix that.)
I can't even access "db" from another Method inside the Class but outside of the Constructor, like:
sqlconnection.cpp:
void closeDB() {db.close();} is not possible.`
What i am doing wrong?
Thank you guys
| In general, you do not need to use any wrapper class to hold database connections in Qt. You should create a database connection once using QSqlDatabase::addDatabase and open it. After that you can get a database connection anywhere by calling QSqlDatabase::database static method. So to close the database connection you should simply call QSqlDatabase::database().close().
|
72,184,441 | 72,184,926 | About the pimpl syntax | I have a question about the C++ usage used in the pimpl syntax.
First, why is it not necessary to write pimpl( new impl ) as pimpl( new my_class::impl )
Second, why is the lifetime of new impl extended even though it is a temporary object?
//my_class.h
class my_class {
// ... all public and protected stuff goes here ...
private:
class impl; unique_ptr<impl> pimpl; // opaque type here
}
// my_class.cpp
class my_class::impl { // defined privately here
// ... all private data and functions: all of these
// can now change without recompiling callers ...
};
my_class::my_class(): pimpl( new impl )
{
// ... set impl values ...
}
|
First, why is it not necessary to write pimpl( new impl ) as pimpl( new my_class::impl )
Scope. When constructor is defined you are inside a cope of a class, so name lookup is able to find it without problems.
Second, why is the lifetime of new impl extended even though it is a temporary object?
You are passing temporary pointer to as constructor argument of std::unique_ptr<impl> so value is consumed by a field pimpl. impl value s not temporary since it is created on a heap, control of its lifetime was passed to smart pointer.
Extra:
You did using namespace std; in header (the only case when you can skip std:: before unique_ptr)! This is BIG mistake do not do it. This will impact dangerously all sources which will include this header. You can have symbol ambiguity error because of that.
Even having using namespace std; in cpp file is considered a bad practice.
|
72,184,458 | 72,508,759 | How to canonicalize and digest the Body of SOAP with xmlib2 | I am trying to sign manually a SOAP request. Using libxml2 in my cpp app I can canonicalize and digest the whole xml soap document using the xmlC14NDocDumpMemory function with xmlNodeSetPtr as null argument. However for the actual signature I need specifically process only the Body of the SOAP.
xmlChar* canon;
int canonLength = xmlC14NDocDumpMemory(
doc,
nullptr,
xmlC14NMode::XML_C14N_EXCLUSIVE_1_0,
nullptr,
1,
&canon
);
std::string canonizedString(reinterpret_cast<const char*>(canon), canonLength);
std::cout << "canonized string:\n" << canonizedString << std::endl;
//freeing the original parsed file:
xmlFreeDoc(doc);
//digesting the value:
const EVP_MD* md = EVP_sha1(); // algorithm
unsigned char digest_value[EVP_MAX_MD_SIZE]; //the digest result value
unsigned int dv_length; //the digest result length
EVP_MD_CTX* mdctx = EVP_MD_CTX_new(); //create msg digest context
EVP_DigestInit_ex(mdctx, md, NULL); // Initialise the context (engine null value?)
EVP_DigestUpdate(mdctx, canon, canonLength); //digesting
EVP_DigestFinal_ex(mdctx, digest_value, &dv_length); //finalizing
EVP_MD_CTX_free(mdctx); //free the context
char* base64convert;
size_t base64convertLength;
base64::Encode(
reinterpret_cast<const char*>(digest_value),
dv_length,
&base64convert,
&base64convertLength);
std::string digest64(base64convert, base64convertLength);
std::cout << "\ndigest value:\n" << digest64;
Example SOAP:
<?xml version="1.0" encoding="UTF-8"?>
<e:Envelope xmlns:e="http://schemas.xmlsoap.org/soap/envelope/">
<e:Header/>
<e:Body>
<!-- doctor-E,EGN:XXXXXXXXXX -->
<ws:hbIn xmlns:ws="http://pis.technologica.com/ws/">
<ws:egn>XXXXXXXXXX</ws:egn>
<ws:date>2015-06-11</ws:date>
</ws:hbIn>
</e:Body>
</e:Envelope>
The result from the sign-example:
<e:Envelope xmlns:e="http://schemas.xmlsoap.org/soap/envelope/">
<e:Header>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#signedContent">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>93BoBU73Y0Efm1rarqzUGw5x4SU=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>jQGU7xsoSVGx/a......</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>MIICjzCCAfi......</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</e:Header>
<e:Body id="signedContent">
<!-- doctor-E,EGN:XXXXXXXXXX -->
<ws:hbIn xmlns:ws="http://pis.technologica.com/ws/">
<ws:egn>XXXXXXXXXX</ws:egn>
<ws:date>2015-06-11</ws:date>
</ws:hbIn>
</e:Body>
</e:Envelope>
So the question is how to get the 93BoBU73Y0Efm1rarqzUGw5x4SU= value?
I've noticed the signed soap body has URI id "signedContent". I'm not sure if this URI is inserted before or after digestion (it could potentially change the whole hash if it is inserted before).
| My advice to anyone, who stumbles here is - DON'T try to canonicalize, digest and sign by yourself. Use xmlsec. Although it's pain in the ass to build (I'm on windows) and the documentation is almost non-existent, it gets the job done. The final answer can be found here:
Sign part of XML using xmlsec
|
72,184,696 | 72,184,917 | erasing nlohmann::json object during iteration causes segmentation fault | I have a simple database consisting of objects with strings containing unix time as keys and strings containing instructions as values
I want to iterate though the database and erase any object who's key is smaller that current time ( so erase objects with dates before current date)
for (auto it = m_jsonData.begin(); it != m_jsonData.end(); it++) {
if (std::stoi(it.key()) <= (std::time(NULL))) {
std::cout << "command is behind schedule, removing\n";
m_jsonData.erase(it);
} else {
/*
*/
}
}
this code works fine as long as m_jsonData.erase(it); isn't invoked. when it does, in the next iteration std::stoi(it.key()) causes a segfault, after a bit of playing with it I came to a conclusion that is somehow loses track of what it's actually iterating. Is my conclusion true? If not then what is? And how do I fix it?
| It's extremely normal for mutating container operations to invalidate iterators. It's one of the first things you should check for.
Documentation for nlohnmann::json::erase():
Notes
Invalidates iterators and references at or after the point of the erase, including the end() iterator.
References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
That means after this line:
m_jsonData.erase(it);
the iterator it can't be used for anything including incrementing it to the next element. It is invalid.
Fortunately, the documentation also points out that the successor to the removed element is returned, so you can just write
for (auto it = m_jsonData.begin(); it != m_jsonData.end(); ) {
if (std::stoi(it.key()) <= (std::time(NULL))) {
it = m_jsonData.erase(it);
} else {
++it;
}
}
Note that when I say this is extremely normal, it's because the standard containers often have similar behaviour. See the documentation for examples, but this is something everyone should be aware of:
std::vector::erase Iterator invalidation
std::unordered_map::erase Iterator invalidation
etc.
This is exactly the reason std::erase was added in C++20, and previously std::remove_if was provided to suppport the erase(remove_if(...), end) idiom, instead of writing fragile mutating loops.
|
72,185,086 | 72,185,169 | use static var, it will block, how to explain this situation | int Test(int i)
{
i--;
if(i <= 0 || i > 2) {
return 0;
} else {
static int y = Test(i);
return (y+1);
}
}
int main() {
cout << Test(3);
return 0;
}
when run to Test(i), it will block.
how to explain this situation?
| It is undefined behaviour if during initialization of a static variable, the code reaches the initialization block again.
Which happens for Test(3) -> y=Test(2)->y=Test(1).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.