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 |
|---|---|---|---|---|
69,336,635 | 69,336,896 | MFC CPP A problem with putting picture in picture control on load | I got MFC app and I wanted to upload a picture using those 3 lines:
cbitmap_.LoadBitmap(IDB_BITMAP1);
picture_control_.SetBitmap((HBITMAP)cbitmap_.Detach());
UpdateData(FALSE);
When I did it on the main Dialog it worked. I tried to use it on a second Dialog that I open and it doesnt work on load. If I use it with a button on the second dialog it works as well...
Where in the cpp file of the second dialog should I paste that code?
Thank you !
| Final initialization of controls in a dialog is commonly done in response to the WM_INITDIALOG message. It is sent by the system after all controls have been created, but before the dialog is displayed. The CDialog class provides the virtual OnInitDialog member you can override in a derived implementation.
The call to UpdateData(FALSE) is not required either way. Assuming that picture_control_ is of type CStatic and properly attached to the control with a call to DDX_Control from the DoDataExchange implementation.
|
69,336,769 | 69,337,085 | static CArray C++ MFC | I simply cannot seem to be able to make a static CArray and work with it.
Here's my code:
class WhiteBoard
{
public:
static CArray<WhiteBoard, WhiteBoard> test;
void tester()
{
test.Add(*this);
}
};
And upon calling the tester method, I get an unresolved external symbol.
Full error code is:
Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol "public: static class CArray<class WhiteBoard,class WhiteBoard> WhiteBoard::test" (?test@WhiteBoard@@2V?$CArray@VWhiteBoard@@V1@@@A) MFCApplication2 C:\Users\sw.eng\source\repos\MFCApplication2\MFCApplication2Dlg.obj 1
This is my first time working with CArray but I messed around with CArray of int and all worked alright.
Could it be that I'm trying to have a CArray of WhiteBoard inside of WhiteBoard? (I do need this functionality to keep track of all child objects made, which is why I do it)
Removing the static keyword makes everything run. But then it's not a static member, and I need it to be one.
Anyways, all help would be incredible and very much appreciated.
EDIT 1:
I've made another class which I called BoardBoss.
WhiteBoard inherits BoardBoss.
CArray is now of BoardBoss type. CArray<BoardBoss, BoardBoss> test;
The issue persists.
| Static class members need to be defined. As posted, the WhiteBoard class merely declares the identifier test. That makes the compiler happy, but the linker fails, because it cannot find the referenced symbol when it is used.
To fix this you need to add the following to a compilation unit:
CArray<WhiteBoard, WhiteBoard> Whiteboard::test;
|
69,337,035 | 69,442,414 | Comparison between 2 different ways of writing Merge Sort | I have learned Merge Sort algorithm in C++ recently and have come across 2 different ways by which it is implemented in tutorials.
1st way:
void merge(int arr[], int low, int mid, int high) {
const int n1 = (mid - low + 1);
const int n2 = (high - mid);
int *a = new int[n1], *b = new int[n2];//dynamically allocated because of MSVC compiler
for (int i = 0; i < n1; i++)
a[i] = arr[low + i];
for (int i = 0; i < n2; i++)
b[i] = arr[mid + 1 + i];
int i = 0, j = 0, k = low;
while (i < n1 && j < n2) {
if (a[i] < b[j]) {
arr[k] = a[i];
i++;
} else {
arr[k] = b[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = a[i];
k++, i++;
}
while (j < n2) {
arr[k] = b[j];
k++, j++;
}
delete[] a;
delete[] b;
}
void mergeSort(int arr[], int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, mid, end);
}
}
int main() {
int arr[] = { 9, 14, 4, 8, 6, 7, 5, 2, 1 };
unsigned size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size);
mergeSort(arr, 0, size - 1);
printArray(arr, size);
return 0;
}
2nd way:
Using temp array passed in the arguments.
void merge(int arr[], int temp[], int low, int mid, int high) {
int i = low, k = low, j = mid + 1;
while (i <= mid && j <= high) {
if (arr[i] < arr[j]) {
temp[k] = arr[i];
i++;
} else {
temp[k] = arr[j];
j++;
}
k++;
}
while (i <= mid) {
temp[k] = arr[i];
k++, i++;
}
while (j <= high) {
temp[k] = arr[j];
k++, j++;
}
for (int i = low; i <= high; i++)
arr[i] = temp[i];
}
void mergeSort(int arr[], int temp[], int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
mergeSort(arr, temp, start, mid);
mergeSort(arr, temp, mid + 1, end);
merge(arr, temp, start, mid, end);
}
}
int main() {
int arr[] = { 9, 14, 4, 8, 6, 7, 5, 2, 1 };
unsigned size = sizeof(arr) / sizeof(arr[0]);
int *buffer = new int[size];
printArray(arr, size);
mergeSort(arr, buffer, 0, size - 1);
printArray(arr, size);
delete[] buffer;
return 0;
}
printArray method:-
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
Which way of writing Merge Sort is better and faster ?
| The second implementation allocates ancillary memory just once and passes the pointer recursively whereas the first calls the allocator and deallocator once per merge call. For large arrays, the second code is likely faster than the first.
Note however that both codes have problems:
they use int for the index variables, limiting the length of arrays to INT_MAX, which is smaller than capabilities of current hardware.
the compute mid as int mid = (start + end) / 2; which causes an arithmetic overflow for arrays larger than INT_MAX / 2, leading to undefined behavior and likely crashes. mid should be computed this way: int mid = start + (end - start) / 2;
they allocate too much memory: the second temporary array is useless in the first code and the temporary array could be half the size for the second code.
they copy too much data: copying the remainder of the second half is useless as these elements are already in place.
they do not implement stable sorting: elements should be compared with arr[i] <= arr[j] instead of arr[i] < arr[j].
the top down recursive merge sort algorithm is suboptimal: bottom-up merge sort implementations are usually more efficient, switching to insertion sort for small chunks tends to improve performance and testing for sorted subranges further improves performance in real life cases.
|
69,337,060 | 69,371,702 | Understand the sorting of a vector of pair (int and pointer to object) | I have a vector of pair defined as follows:
vector<pair<int, myClass *>> myVector;
The vector is sorted using the following:
sort(myVector.begin(), myVector.end());
This code is not mine and everything is working fine.
The only thing I don't get and I would like to understand is:
When I have two elements of my vector with the same int value as first, how the sorting is done? On which criteria?
I was thinking first, it's based on the value of the pointer to my object in the pair. But I can't see it.
I want to understand it because I need to reproduce this behavior (the sorting) on a demonstrator on Matlab.
| As I said in the comment to my question, tt's indeed the numeric value of the pointer which is use as second sorting argument. This behavior doesn't make any sense in the program itself (once again, not my program) but also it won't be reproducible in Matlab. Anyway, thanks all for your help.
|
69,337,091 | 69,349,419 | STM8 as SPI slave can't send back data | I have build a prototype board with a STM8L, and I want it to be used and configured as a SPI slave. I am testing it with a raspberry pi as master.
I use the lib provided by ST called "STM8 Standard Peripherals Library" for this, but the documentation is very poor and doesn't expain how to do this...
I can send data from the Raspberry Pi with no issue and receive it on the STM8 but I can't send back any data to the raspberry from the STM8 on MISO.
Is anybody known how I can send back some data to the Raspberry Pi master? Where is my mistake?
Here is the main code:
void main(void)
{
// GPIO
GPIO_Init(GPIOA, GPIO_Pin_7, GPIO_Mode_Out_PP_Low_Fast);
CLK_Config();
// Set the MOSI and SCK at high level
GPIO_ExternalPullUpConfig(GPIOB, GPIO_Pin_6 | GPIO_Pin_5, ENABLE);
SPI_DeInit(SPI1);
SPI_Init(SPI1, SPI_FirstBit_LSB, SPI_BaudRatePrescaler_2, SPI_Mode_Slave,
SPI_CPOL_Low, SPI_CPHA_2Edge, SPI_Direction_2Lines_FullDuplex,
SPI_NSS_Hard, (uint8_t)0x07);
SPI_BiDirectionalLineConfig(SPI1, SPI_Direction_Tx);
// Enable SPI
SPI_Cmd(SPI1, ENABLE);
/* Infinite loop */
while (1)
{
while(SPI_GetFlagStatus(SPI1, SPI_FLAG_BSY));
// SPI polling
if(SPI_GetFlagStatus(SPI1, SPI_FLAG_RXNE) == SET) {
while(SPI_GetFlagStatus(SPI1, SPI_FLAG_BSY));
GPIO_ToggleBits(GPIOA, GPIO_Pin_7);
uint8_t data = SPI_ReceiveData(SPI1);
while(SPI_GetFlagStatus(SPI1, SPI_FLAG_BSY));
// I can't send back data here, it doesn't work
SPI_SendData(SPI1, 0xFA);
uint8_t test = SPI1->DR;
GPIO_ResetBits(GPIOA, GPIO_Pin_7);
}
}
}
static void CLK_Config(void)
{
/* Select HSE as system clock source */
CLK_SYSCLKSourceSwitchCmd(ENABLE);
CLK_SYSCLKSourceConfig(CLK_SYSCLKSource_HSI);
/*High speed external clock prescaler: 1*/
CLK_SYSCLKDivConfig(CLK_SYSCLKDiv_2);
while (CLK_GetSYSCLKSource() != CLK_SYSCLKSource_HSI)
{}
/* Enable SPI clock */
CLK_PeripheralClockConfig(CLK_Peripheral_SPI1, ENABLE);
}
And the RPi simple code:
#include <iostream>
#include <wiringPi.h>
#include <wiringPiSPI.h>
using namespace std;
int main()
{
wiringPiSetup();
wiringPiSPISetup(0, 50000);
unsigned char data[] = {0x5A};
wiringPiSPIDataRW(0, data, 2);
std::cout<<data<<std::endl;
return 0;
Thank you for your help! :)
Edit: I think the mistake is in uC code because the spi data register still contain the data sent by the master after I read it. I can't change it even by trying to write directly in the register.
Also: is it normal that the device only contain one data register for SPI? How is it supposed to be full duplex if it haven't one for MOSI (Rx) and one for MISO(Tx)? I think there is something I don't understand about SPI. I am not very experienced with this serial protocol. I mainly used I2C before.
| I finaly found where were my mistakes.
First, I forgot to configure a pullup resistor on the MISO pin:
// Set the MOSI and SCK at high level
GPIO_ExternalPullUpConfig(GPIOB, GPIO_Pin_6 | GPIO_Pin_5 | GPIO_Pin_7, ENABLE);
Next, the SPI config were wrong. The Rpi was in MSB and the STM8 in LSB, and phase was on the second edge when it needed to be on the first edge:
SPI_Init(SPI1, SPI_FirstBit_MSB, SPI_BaudRatePrescaler_2, SPI_Mode_Slave,
SPI_CPOL_Low, SPI_CPHA_1Edge, SPI_Direction_2Lines_FullDuplex,
SPI_NSS_Hard, (uint8_t)0x07);
Finaly, not a mistake but a not optimal way to test: I were sending 0x81 with the master, but it is symetric in binary (0b10000001). I should have sent some asymetric message, for example 0x17 (0b00010111).
And the complete STM8 code:
#include "stm8l15x.h"
#include "stm8l15x_it.h" /* SDCC patch: required by SDCC for interrupts */
static void CLK_Config(void);
void Delay(__IO uint16_t nCount);
void main(void)
{
// GPIO
GPIO_Init(GPIOA, GPIO_Pin_7, GPIO_Mode_Out_PP_Low_Fast);
CLK_Config();
// Set the MOSI and SCK at high level (I added MOSI)
GPIO_ExternalPullUpConfig(GPIOB, GPIO_Pin_6 | GPIO_Pin_5 | GPIO_Pin_7, ENABLE);
SPI_DeInit(SPI1);
SPI_Init(SPI1, SPI_FirstBit_MSB, SPI_BaudRatePrescaler_2, SPI_Mode_Slave,
SPI_CPOL_Low, SPI_CPHA_1Edge, SPI_Direction_2Lines_FullDuplex,
SPI_NSS_Hard, (uint8_t)0x07);
SPI_BiDirectionalLineConfig(SPI1, SPI_Direction_Tx);
// Enable SPI
SPI_Cmd(SPI1, ENABLE);
/* Infinite loop */
while (1)
{
while(SPI_GetFlagStatus(SPI1, SPI_FLAG_BSY));
// SPI polling
if(SPI_GetFlagStatus(SPI1, SPI_FLAG_RXNE) == SET) {
// maybe this line is not necessary, I didn't have the time to test without it yet
while(SPI_GetFlagStatus(SPI1, SPI_FLAG_BSY);
uint8_t data = SPI_ReceiveData(SPI1);
while(SPI_GetFlagStatus(SPI1, SPI_FLAG_RXNE));
if(data==0x82) SPI_SendData(SPI1, 0xCD);
GPIO_ResetBits(GPIOA, GPIO_Pin_7);
}
}
}
/* Private functions ---------------------------------------------------------*/
static void CLK_Config(void)
{
/* Select HSE as system clock source */
CLK_SYSCLKSourceSwitchCmd(ENABLE);
CLK_SYSCLKSourceConfig(CLK_SYSCLKSource_HSI);
/*High speed external clock prescaler: 1*/
CLK_SYSCLKDivConfig(CLK_SYSCLKDiv_2);
while (CLK_GetSYSCLKSource() != CLK_SYSCLKSource_HSI)
{}
/* Enable SPI clock */
CLK_PeripheralClockConfig(CLK_Peripheral_SPI1, ENABLE);
}
void Delay(__IO uint16_t nCount)
{
/* Decrement nCount value */
while (nCount != 0)
{
nCount--;
}
}
/*******************************************************************************/
#ifdef USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line)
{
/* Infinite loop */
while (1)
{
}
}
#endif
PS:
I am on linux and soft tools were not adapted to my OS, so I used some tools to be able to develop with it.
I think it can be useful for some people, so I add it here:
First, the lib were not able to compile with SDCC, so I used the patch I found here:
https://github.com/gicking/STM8-SPL_SDCC_patch
To upload to the uC, I use stm8flash with a ST-LINK V2:
https://github.com/vdudouyt/stm8flash
I also had some trouble to find the lib for the STM8L. Here it is:
https://www.st.com/en/embedded-software/stsw-stm8016.html
PS2:
I understand that it is not easy to answer to hardware related questions. Does anybody knows some websites which are more specified on this kind of questions?
|
69,337,471 | 69,337,604 | How to make a simple loop more generic | The below method will concatenate all warnings into one string. It works but obviously need to create almost the same method again for info and error.
struct MyItem
{
std::vector<std::string> errors;
std::vector<std::string> warnings;
std::vector<std::string> infos;
};
std::vector<MyItem> items;
std::string GetWarnings()
{
std::string str;
for (auto item : items)
{
for (auto warn : item.warnings)
{
str += warn;
str += " ";
}
}
return str;
}
What would be a good generic way to implement one "Concatenate" method? One solution would be to define an enum (error\warning\item), pass it as input argument and make a switch case on argument value. Any more elegant solutions?
| You can use a pointer to member to extract a specific field from an object:
auto concatenate(
const std::vector<MyItem>& items,
const std::vector<std::string> MyItem::* member
) {
std::string str;
for (const auto& item : items) {
for (const auto& element : item.*member) {
str += element;
str += " ";
}
}
return str;
}
Which can be used like so:
int main() {
std::vector<MyItem> items{
{{"err11", "err12"}, {"w11"}, {"i11", "i12", "i13"}},
{{"err21"}, {"w21", "w22", "w23", "w24"}, {"i21"}}
};
std::cout << "all errors: " << concatenate(items, &MyItem::errors) << '\n'
<< "all warnings: " << concatenate(items, &MyItem::warnings) << '\n'
<< "all infos: " << concatenate(items, &MyItem::infos) << '\n';
}
And, if you have members of different types in your struct (note that the above solution works only for vectors of strings), you can turn concatenate into a function template:
struct MyItem {
std::vector<std::string> errors;
std::vector<std::string> warnings;
std::vector<std::string> infos;
std::vector<char> stuff; // added
};
template <typename T> // now a function template
auto concatenate(
const std::vector<MyItem>& items,
const T MyItem::* member
) {
std::string str;
for (const auto& item : items) {
for (const auto& element : item.*member) {
str += element;
str += " ";
}
}
return str;
}
int main() {
std::vector<MyItem> items{
{{"err11", "err12"}, {"w11"}, {"i11", "i12", "i13"}, {'1' ,'2'}},
{{"err21"}, {"w21", "w22", "w23", "w24"}, {"i21"}, {'3'}}
};
std::cout << "all errors: " << concatenate(items, &MyItem::errors) << '\n'
<< "all warnings: " << concatenate(items, &MyItem::warnings) << '\n'
<< "all infos: " << concatenate(items, &MyItem::infos) << '\n'
<< "all stuffs: " << concatenate(items, &MyItem::stuff) << '\n';
}
Note that I also changed your auto item occurrences in your for() loops to const auto& items in order to avoid unncecessary copies.
Alternatively, you can use a projection to extract your elements. In this implementation, we use a template to accept any type of a function that will take your MyItem and return the desired element:
template <typename Proj>
auto concatenate(
const std::vector<MyItem>& items,
Proj projection
) {
std::string str;
for (const auto& item : items) {
for (const auto& element : projection(item)) {
str += element;
str += " ";
}
}
return str;
}
int main() {
std::vector<MyItem> items{
{{"err11", "err12"}, {"w11"}, {"i11", "i12", "i13"}, {'1' ,'2'}},
{{"err21"}, {"w21", "w22", "w23", "w24"}, {"i21"}, {'3'}}
};
auto errors_projection =
[](const MyItem& item) -> const std::vector<std::string>& {
return item.errors;
};
auto warnings_projection =
[](const MyItem& item) -> const std::vector<std::string>& {
return item.warnings;
};
auto infos_projection =
[](const MyItem& item) -> const std::vector<std::string>& {
return item.infos;
};
auto stuff_projection =
[](const MyItem& item) -> const std::vector<char>& {
return item.stuff;
};
std::cout << "all errors: " << concatenate(items, errors_projection) << '\n'
<< "all warnings: " << concatenate(items, warnings_projection) << '\n'
<< "all infos: " << concatenate(items, infos_projection) << '\n'
<< "all stuffs: " << concatenate(items, stuff_projection) << '\n';
}
|
69,337,753 | 69,337,824 | create std::tuple using compile-time types and a run-time function | I'm trying to build (at runtime) a tuple whose types are known at compile-time.
I've gotten it pretty close I think:
#include <tuple>
// This is defined elsewhere
template<typename T>
T* create_obj();
template<typename ...Ts>
auto create_tuple()
{
std::tuple_cat(
(std::make_tuple( create_obj<std::tuple_element<Idx, Ts...>() ), ...) // Idx?
);
}
Example usage might be:
struct A{};
struct B{};
struct C{};
std::tuple<A*, B*, C*> = create_tuple<A, B, C>();
I'm stuck on how to iterate Idx at compile-time... Maybe std::index_sequence?
| I am not sure if I correctly understand the question, because I dont understand why you want to iterate Idx, why use tuple_element or tuple_cat. I think you just want to call make_tuple to return a tuple whose elements are created via create_obj:
#include <tuple>
template<typename T>
T* create_obj() { return new T{};}
template<typename ...Ts>
auto create_tuple()
{
return std::make_tuple( create_obj<Ts>() ...);
}
struct A{};
struct B{};
struct C{};
int main() {
std::tuple<A*, B*, C*> a = create_tuple<A, B, C>();
}
|
69,338,118 | 69,338,186 | Passing arrays to tesselation evaluation shader | I have this tesselation evaluation shader:
\\ vertex
#version 410 core
#define SIZE 6
layout (location = 0) in vec2 x;
layout (location = 1) in vec2 h;
layout (location = 2) in float f[SIZE];
out TC_DATA
{
vec2 x;
vec2 h;
float f[SIZE];
} tc_out;
void main()
{
tc_out.x = x;
tc_out.h = h;
tc_out.f = f;
}
\\ tess control
#version 410
layout (vertices = 1) out;
#define SIZE 6
uniform int outer0;
uniform int outer1;
uniform int outer2;
uniform int inner;
in TC_DATA
{
vec2 x;
vec2 h;
float f[SIZE];
} tc_in[];
out TE_DATA
{
vec2 x;
vec2 h;
float f[SIZE];
} te_out[];
void main()
{
if (gl_InvocationID == 0)
{
gl_TessLevelInner[0] = inner;
gl_TessLevelOuter[0] = outer0;
gl_TessLevelOuter[1] = outer1;
gl_TessLevelOuter[2] = outer2;
}
te_out[gl_InvocationID].x = tc_in[gl_InvocationID].x;
te_out[gl_InvocationID].h = tc_in[gl_InvocationID].h;
// te_out[gl_InvocationID].f = tc_in[gl_InvocationID].f; // <---- uncommenting this line crashes the app
}
\\ tess evaluation
#version 410
layout (triangles) in;
out vec4 fColor;
void main()
{
gl_Position = vec4(1.0);
fColor = vec4(1.0);
}
\\ fragment
#version 410 core
in vec4 fColor;
out vec4 oColor;
void main()
{
oColor = fColor;
}
The vertex specification:
struct Vertex
{
glm::vec2 x;
glm::vec2 h;
std::array<float, 6> f;
};
std::vector<Vertex> vertices;
// ....
glGenVertexArrays(1, &vertex_array);
glBindVertexArray(vertex_array);
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, x));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, h));
glVertexAttribPointer(2, 6, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, f));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
The render part:
glPatchParameteri(GL_PATCH_VERTICES, 1);
glBindVertexArray(vertex_array);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(decltype(vertices)::value_type), vertices.data(), GL_DYNAMIC_DRAW);
glDrawArrays(GL_PATCHES, 0, vertices.size());
I am trying to pass an array float f[6] and I crash my app if I don't comment the line indicated in the tesselation control shader. I don't understand what I'm doing wrong. I know for sure it is not the c++ part of the code. There are no errors when compiling the shaders or linking the program (opengl program).
| The size argument of glVertexAttribPointer must be 1, 2, 3 or 4. Passing 6 to the size argument generates a GL_INVALID_VALUE error.
If the type of the vertex shader attribute is an array, each element of the array has a separate attribute index. The attribute layout (location = 2) in float f[SIZE]; has the attribute indices from 2 to 7:
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE,
sizeof(Vertex), (void*)offsetof(Vertex, f));
glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE,
sizeof(Vertex), (void*)(offsetof(Vertex, f) + 4));
glVertexAttribPointer(4, 1, GL_FLOAT, GL_FALSE,
sizeof(Vertex), (void*)(offsetof(Vertex, f) + 8));
// [...]
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
// [...]
|
69,338,391 | 69,338,499 | c++ function returns two different types | I'm creating a queue template class using C++.
The queue class has multiple function members. One of the functions is called front() to retrieve the first value of queue. Basically, the front() function will first check if the queue is empty or not (using another bool function is_empty()).
If it is empty, the function will throw error message and return 1 to indicate there is an error. If the queue is not empty, it will return the first value, whose type is same as that of data in queue. As you can see, there are two different types of return values. How can I specify those two types together when define the function?
Sample code is below. The return type is T. But the function also returns 1. Is this acceptable in C++? If not, how to modify it? Thanks in advance!
template <class T>
T MyQueue<T>::front() {
if (! is_empty()) {
return my_queue[0];
}
else {
cout << "queue is empty!" << endl;
return 1;
}
}
| One option is to use std::optional:
template <class T>
std::optional<T> MyQueue<T>::front() {
// You should remove the object from the queue here too:
if (!is_empty()) return my_queue[0];
return {};
}
You can then use it like so:
if(auto opt = queue_instance.front(); opt) {
auto value = std::move(opt).value();
std::cout << "got :" << value << '\n';
} else {
std::cout << "no value right now\n";
}
|
69,338,457 | 69,369,809 | What is the fastest way to power real numbers? | Of course i know that there is a good pow() function in cmath(math.h), but not touching the background of the pow() what is the fastest way to power numbers with my own hands?
| You are asking two different questions:
What is the fastest way to power real numbers?
What is the fastest way to power numbers with my own hands?
These have different answers.
pow is fast. Standard library implementations are generally written by very smart people, reviewed by other smart people, and then refactored by even smarter people. Because of this, using a provided standard library implementation is almost always better than trying to re-implement the standard library yourself.
But, if you insist on creating your own implementation of pow, you should first implement exp and log using their Taylor series expansions. Then use the following property:
pow(base,power) = exp( power * log(base) )
Note that if base is negative, you should first compute pow(-base,power), then do a parity check on base to determine the sign of the result.
|
69,338,461 | 69,338,677 | How can I print the result from this code with four places after the decimal point? | How can I print the result with four places after the decimal point?
#include <iostream>
#include <math.h>
using namespace std;
int main() {
double A;
double R;
cin >> R;
A = 3.14159 * R * R;
cout << "A=" << A << "\n";
return 0;
}
| #include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main() {
double A;
double R;
cin >> R;
A = 3.14159*R*R;
cout << "A="<< fixed << setprecision(4) << A<< "\n";
return 0;
}
Add the library iomanip. fixed and setprecision are utilized in this case to achieve your goal of printing out up to 4 decimal points.
|
69,338,624 | 69,338,717 | Trying to pass a function as a parameter using functional library in c++ but it is not working | // I will define all the functions that are involved.
//First is the sort function that i am trying to pass.
void bubbleSort(vector<int> &vector);
//Second is the function that calls the function that is supposed to take a function as a parameter.
int testSorts(vector<int> &vector, ofstream& outfile, string data)
{
displaySort(vector, outfile, sortName, bubbleSort);
}
//This is the function that is supposed to take a vector, file, and function as parameter.
// When I run this I get the following error. [Error] template argument 1 is invalid
void displaySort(vector<int>& vector, ofstream& outfile, string data, std::function<void
(vector<int>& vector)> func)
{func(vector);}
//Here is the code I got from stack overflow that works. What I want to know is why mine does not. I did the same thing.
#include <functional>
double Combiner(double a, double b, std::function<double
(double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
| Don't do using namespace std; and specify the namespace and it should work:
void displaySort(std::vector<int>& vector, std::ofstream& outfile,
std::string data, std::function<void(std::vector<int>&)> func)
{
func(vector);
}
If you for some reason want to stick with using namespace std;, add :: before vector in the function spec:
void displaySort(vector<int>& vector, ofstream& outfile,
string data, function<void(::vector<int>&)> func)
// ^^
{
func(vector);
}
|
69,338,639 | 69,338,655 | drawing program with glut/openGL not working | This program is able to create a window and locate my mouse when it is on the window, however the display function does seem to work. What am I missing here?
float pointSize = 10.0f;
bool leftBottState;
float xvalue;
float yvalue;
void init()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
}
void dots()
{
glBegin(GL_POINTS);
glVertex3f(xvalue, yvalue, 0.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1, 0, 1);
dots();
glEnd();
glFlush();
}
void mouse(int button, int state, int x, int y)
{
y = 600 - y;
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
leftBottState = true;
}
else
{
leftBottState = false;
}
}
void motion(int x, int y)
{
if (leftBottState)
{
std::cout << "LEFt bUTTON " << std::endl;
xvalue = x;
yvalue = y;
glutPostRedisplay();
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(600, 600);
glutCreateWindow("test");
glutMotionFunc(motion);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return(0);
}
| You're using a double buffered window (see glutInitDisplayMode).
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
Therefore you must call glutSwapBuffers to swaps the buffers after rendering the scene:
void dots()
{
glBegin(GL_POINTS);
glVertex3f(xvalue, yvalue, 0.0);
glEnd();
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1, 0, 1);
dots();
// glFlush();
glutSwapBuffers();
}
Note, a glBegin \ glEnd sequence delimits the vertices of a primitive. I recommend to call this instructions in the same function, immediately before and after specifying the vertices.
glClear clears the buffers and thus the entire scene. If you want to draw the points permanently, you have to remove the glClear instruction from the display function.
glClear(GL_COLOR_BUFFER_BIT);
|
69,338,726 | 69,338,944 | Why is a function taking a pointer preferred over a function taking an array reference? | Consider the following program:
#include <iostream>
#include <cstring>
using namespace std;
void print(const char *pa) {
cout << "Print - using pointer" << endl;
}
void print(const char (&arr)[]) {
cout << "Print - using reference" << endl;
}
int main() {
char ca[] = {'B', 'A', 'D', 'C', '\0'};
print(ca);
}
Results:
Print - using reference
Why is reference preferred over pointers?
According to C++ Primer 5th Ed., section 6.6.1:
In order to determine the best match, the compiler ranks the
conversions that could be used to convert each argument to the type of its corresponding parameter. Conversions are ranked as follows:
An exact match. An exact match happens when:
• The argument and parameter types are identical.
• The argument is converted from an array or function type to the corresponding pointer type. (§ 6.7 (p. 247) covers function pointers.)
• A top-level const is added to or discarded from the argument.
Match through a const conversion (§ 4.11.2, p. 162).
Match through a promotion (§ 4.11.1, p. 160).
Match through an arithmetic (§ 4.11.1, p. 159) or pointer conversion (§ 4.11.2, p. 161).
Match through a class-type conversion. (§ 14.9 (p. 579) covers these conversions.)
No mentioned of reference here. Any idea?
Thanks
| Binding a reference directly to an argument expression is considered as an identity conversion.
For the function with a parameter of a pointer type there is required the implicit conversion from an array type to the pointer type.
So the function with the referenced type of its parameter is more viable.
From the C++ 17 Standard (16.3.3.1.4 Reference binding)
1 When a parameter of reference type binds directly (11.6.3) to an
argument expression, the implicit conversion sequence is the identity
conversion, unless the argument expression has a type that is a
derived class of the parameter type, in which case the implicit
conversion sequence is a derived-to-base Conversion (16.3.3.1).
|
69,338,737 | 69,338,809 | Passing References to Member Functions | I've been working with a doubly-threaded BST in C++, and I thought it would be cool to separate my visitor functions from my various traversals. However I can't figure out how to properly pass references to member functions into my traversal functions. Here is a massively simplified version of my problem:
class foo {
public:
foo() {};
~foo() {};
void print(int x) const { //visitor
cout << x << endl;
}
void traverse(void (*visitor)(int)) { //traversal
for (int i = 0; i < 9; i++)
visitor(myAry[i]);
}
void printAll() { //function calling the traversal and passing it a reference to the visitor
traverse(&print);
}
int myAry[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
};
The problem of course comes in the traverse(&print); statement.
Any clues what's going wrong, or what I could try differently to achieve the same effect?
| void (*visitor)(int)
In C++ this means: a pointer to a function that takes an int parameter and returns a void.
&print
The type of this expression is not "a pointer to a function that takes an int parameter and returns a void". It is "a pointer to a method of class foo that takes an int parameter and returns a void".
Class methods and functions are not the same thing. They might look the same, but they're not.
In your sample code you don't need to use a class method, for print, so just declare it as a static class member:
static void print(int x) const {
cout << x << endl;
}
And, with no other changes, this should work, since this is now a function. The difference between a class method is a function is that a class method requires an object whose method gets invoked.
It's possible that your clear code does really require a pointer to a class method. In which case traverse() should probably be something like:
void traverse(void (*foo::visitor)(int)) {
for (int i = 0; i < 9; i++)
(this->*visitor)(myAry[i]);
}
and this would be invoked as
traverse(&foo::print);
This is because void (*foo::visitor)(int) means "a pointer to a method of class foo that takes an int parameter and returns a void". And this is what your print is.
|
69,338,932 | 69,864,086 | C++ Unit tests failing when using SFML objects | I have a C++ project I am working on and I have to write Unit tests for it. It's a video game-like project so I am using SFML as my base. I tried using the Native Unit Test framework and the Google Test framework, but I always get stuck at the same point. Whenever I try to create an object that uses anything from the SFML library, the tests immediately fail. In the case of the Native Unit Test when I try to run the tests they fail with the message:
Failed to set up the execution context to run the test
In the case of Google Test, the test discovery fails to find the tests at all. The test discovery produces this output:
ERROR: Could not list test cases for executable 'C:\Users\User\Desktop\Enigma\finished\Release\EnigmaTest.exe': process execution failed with exit code -1073741515
I have set the project properties to be the exact same as the project I am testing and I have copies of the required DLL dependencies in the folder of the test project. Any ideas on what the problem could be?
I am using Visual Studio 2019 btw.
| I fixed this by adding the bin directory (C:\SFML-2.5.1\bin) of the SFML library in the Path environment variable
|
69,339,881 | 69,340,021 | Do C++ compilers align small functions to optimize cache-line fetches? | I may be misunderstanding how cache fetches work, but I'm curious if there are any compiler optimizations for aligning small functions that are not inlined.
If the cache-line-size is 64 bytes on a given machine, would it make sense to have function pointers to functions that are smaller than 64 bytes be aligned within a single cache line to prevent multiple cache fetches to retrieve the function?
Even if the function is 100 bytes in size, it could still be aligned to 2 cache lines, with the worst case being 3 if it is unaligned. Is this a viable optimization and do compilers use anything like this in real applications such as packing small commonly used functions together?
| No, mainstream compilers like gcc and clang don't leave extra unused space to start a small function at the start of a cache line, to avoid having its end cross a boundary. Nor do they choose an order within the text section that optimizes for this without reducing overall code density for I-cache and iTLB.
AFAIK, GCC doesn't even know instruction sizes; it compiles by emitting asm text to be assembled separately. Before every function, it uses .p2align 4 (assuming the default is -falign-functions=16 like on x86-64), or clang -mllvm -align-all-functions=4 (2^4 = 16), since CPUs often fetch in chunks that size, and you want the first aligned fetch to pull in multiple useful instructions.
Inside functions, GCC by default aligns branch targets (or at least tops of loops) by padding to the next multiple of 16 if it would take 10 or fewer bytes, then unconditionally align by 8, but the condition is implemented by the assembler (which does know machine-code sizes / position):
.p2align 4,,10 # GCC does this for loop tops *inside* functions
.p2align 3
Interesting idea, though, might be worth looking at whether there are any real-world benefits to doing this.
Most frequently-called functions are already hot in some level of cache (because caches work, and being frequently called means they tend to stay hot), but this possibly could reduce the number of cache lines that need to stay hot.
Another thing to consider is that for many functions, not all the code bytes are hot. e.g. the fast path might be in the first 32 bytes, with later code bytes only being if() or else blocks for error conditions or other special cases. (Figuring out which path through the function is the common one is part of a compiler's job, although profile-guided optimization (PGO) can help. Or hinting with C++20 [[likely]] / [[unlikely]] can achieve the same result if the hints are actually correct, letting the compiler lay out the code so the fast path(s) minimizes taken branches and maximizes cache locality. How do the likely/unlikely macros in the Linux kernel work and what is their benefit? has an example using GNU C __builtin_expect().
Sometimes these later parts of a function will jump back to the "main" path of the function when they're done, other times they independently end with their own ret instruction. (This is called "tail duplication", optimizing away a jmp by duplicating the epilogue if any.)
So if you were to blindly assume that it matters to have the whole function in the same cache line, but actually only the first 32 bytes typically execute on most calls, you could end up displacing the start of a later somewhat larger function so it starts closer to the end of a cache line, maybe without gaining anything.
So this could maybe be good with profile-guided optimization to figure out which functions were actually hot, and group them adjacent to each other (for iTLB and L1i locality), and sort them so they pack nicely. Or which functions tend to be called together, one after the other.
And conversely, to group functions that often go unused for a long time together, so those cache lines can stay cold (and even iTLB entries if there are pages of them).
|
69,340,012 | 69,340,022 | C++: Initialize template variable in struct | UPDATE: The issue was stemming from the fact that the Passenger class does not have a default constructor. I don't understand why that breaks the list implementation though. If someone could leave a comment explaining this to me, I'd appreciate it a lot!
OG Post:
Hello fellow stackoverflowers. I'm working on a simple university assignment but have run into a problem I can't seem to wrap my head around to solve. I'm new to C++ and I'm learning now that implementing generics is not as straightforward in C++ as it is in Java. Inside my LinkedList class there is a struct Node:
struct Node {
T data;
Node *next;
}; // Node
Simple enough. And when I create a list of integers in my main.cpp, the implementation functions as it should.
int main() {
LinkedList<int> integers;
integers.append(1);
integers.append(2);
integers.append(3);
// append, prepend, get, insert, and remove
// functions all work as they should.
} // main
I also have a Passenger class. The problem occurs when I attempt to create a list of Passenger instances.
int main() {
LinkedList<Passenger> passengers;
Passenger passenger1("LastName1", "FirstName1", 0);
Passenger passenger2("LastName2", "FirstName2", 1);
passengers.append(passenger1);
passengers.append(passenger2);
} // main
The error messages read exactly as follows:
./LinkedList.hpp:21:10: error: implicit default constructor
for 'LinkedList<Passenger>::Node' must explicitly initialize
the member 'data' which does not have a default constructor
./LinkedList.cpp:26:23: note: in implicit default constructor
for 'LinkedList<Passenger>::Node' first required here:
Node *newNode = new Node;
The append function in the LinkedList class is the following:
template<class T>
void LinkedList<T>::append(T data) {
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
newNode->next = head;
this->head = newNode;
} else {
Node *ptr = head;
while (ptr->next != NULL) {
ptr = ptr->next;
} // while
ptr->next = newNode;
} // if
length++;
} // append
Thank you so much to anyone who helps me out here!
| It appears that you call:
Node *newNode = new Node;
Which is equivalent to
Passenger *newNode = new Passenger;
Which appears to be invalid because Passenger does not have a no argument constructor. I suspect you could fix this by doing:
Node *newNode = new Node(data, nullptr);
|
69,340,062 | 69,342,881 | How to disable anti-aliasing in QMovie(or QLabel)? | I want to use QMovie in QLabel to show a pixel animation but anti-aliasing seems to be enabled by default. This makes the pixel painting not look like a pixel painting.
QMovie* movie = new QMovie(":/gif/exp.gif");
movie->setScaledSize(QSize(200,200));
label->setMovie(movie);
| QMovie just play your gif inside label, It didn't change anti-aliasing, If you didn't see that gif with the high quality you should change that gif.
The QMovie class is a convenience class for playing movies with
QImageReader.
this means that it didn't use paint.
one thing that makes you see that gif in low quality is for change scale movie->setScaledSize(QSize(200,200));
If you remove this you can see what your gif is actually, with that original quality.
|
69,340,407 | 69,340,554 | How do you write a program that tests if a user's inputs are integers and returns a message if they enter characters? | The homework is that you need to write a program that takes 4 integers between 0-100 inclusive from the user, computes their average, and displays the four integers as well as the average on the output screen, like in the following format:
Your grades were: 70 80 60 90
Your average grade is 75
You also have to make sure that the program produces a mathematically correct result, which it may not because of integer division. You also have to make it that the user cannot enter numbers outside the range 0-100, and the user cannot enter characters or strings.
So far, I have met the first two restrictions, however I am having trouble setting up the code such that the user cannot enter any characters. Can someone take a look at the following code and see what I'm doing wrong? Note that this is only the part of the code that pertains to my issue.
int main()
{
int grade1, grade2, grade3, grade4;
float grade_average;
char g1char;
cout << "Enter 4 integer grades (%): ";
cin >> grade1 >> grade2 >> grade3 >> grade4;
g1char = grade1;
if (isdigit(g1char) == 0) {
cout << "Incorrect input - characters not allowed; Please run the program again and enter proper values";
}
| The function std::isdigit expects an int with the value of a character code. However, you are not passing it a character code. If you want to pass a character code, you must read the input as a string or as individual characters, not as a number. Otherwise, you will have no character codes to pass to std::isdigit.
However, unless the task description explicitly requires you to check that every single character is a digit, you don't have to call std::isdigit. This would also not be meaningful in some cases. For example, when the user enters negative numbers such as -34, the first character is not a digit. With this specific task, the user is not supposed to enter negative numbers, but the user may want to enter +34 for the number 34, which should also be valid (unless the task description explicitly states otherwise).
You have two options to solve this problem. You can either
rely on the stream extraction operator >> and check whether an error occurred using std::cin.fail, or
read one line of input as a string using std::getline, and use std::stoi to attempt to convert the string into to a number. The function std::stoi will tell you whether the input was valid or not, i.e. whether it was possible to convert the string to a number.
The first option may be easier to use, but the second option is generally recommended for line-based user input, as it will always read one line at a time.
However, both options do have one problem: They will accept input such as 6sdfh4q as valid input for the number 6. Therefore, if you want perfect input validation, you should also check the part of the input that was not converted to a number, to check whether it is acceptable. All whitespace characters are probably harmless, but all other characters are not, so I recommend that you use std::isspace for this purpose.
|
69,340,510 | 69,349,572 | cout with pointers c++ | I can not understand why cout does not work in this code:
#include<iostream>
using namespace std;
int main() {
int v = 65;
int* q = &v;
char** o = (char**)&q;
cout << o << endl; // output: 012FFCAC
cout << *o << endl; // output: A
cout << **o << endl; // output: A
printf("%c",*o); // cause an error
printf("%p",*o); // works and the output=&v
And cout does not work else in this code
#include<iostream>
using namespace std;
int main() {
char v = 65;
cout << &v << endl; // output: A╠╠╠╠▀?╞«4°O
| Because an int is (usually) 4 bytes 65 will fit quite neatly into just the first byte and the rest of the memory allocated for the int will be 0 this byte pattern happens to match up very closely to how strings are stored in memory.
So when the memory is accessed through a char* it will print A most of the time even though most of the prints were ill formed
int v = 65; // Byte pattern on most machines [65,0,0,0]
int* q = &v;
char** o = (char**)&q; // *o now points to [65,0,0,0] ==> ['A','\0','\0','\0'] ==> "A"
std::cout << o << std::endl;
// input: char**
// printed as: pointer
// result: 012FFCAC
std::cout << *o << std::endl; // Undefined Behaviour
// input: char*
// printed as: null terminated string
// result: "A"
std::cout << **o << std::endl; // Undefined Behaviour
// input: char
// printed as: single character
// result: 'A'
printf("%c",*o); // %c expects a [char] type but is given [pointer to char] ERROR
printf("%p",*o); // %p expects a [pointer] type and is given a [pointer to char] OK
Since a char is (usually) 1 byte there is no null terminand to stop the printing once it starts and it keeps printing whatever is around in memory until it runs into a 0 or an access violation
char v = 65;
std::cout << &v << std::endl; // &v is not a well-formed null terminated string: Undefined Behaviour
// input: char*
// printed as: null terminated string
// result: "A<whatever other data is around v in memory>"
|
69,340,715 | 69,387,938 | Reading file from .csv in c++ | I am writing a program that takes input from the .csv file. The program run but the problem is it only returns the last line of the .csv file and skips all the other 9 lines.
It also does not display the average and the grade. Please help me figure out what I am doing wrong.
The professor is very specific about using what we have learned so far and that is loops and functions. I can only use loops and functions so I am not allowed to use arrays.
Here's the scores.csv file
#include <iostream>
#include <fstream>
using namespace std;
int testScore1, testScore2, testScore3, testScore4, testScore5;
double avg;
char grade;
double getAvg(int testScore1, int testScore2, int testScore3, int testScore4, int testScore5){
avg = (testScore1 + testScore2 + testScore3 + testScore4 + testScore5)/5;
return avg;
}
char getGrade(double avg){
if (avg >= 90){
grade = 'A';
cout << 'A' << endl;
}else if (avg >= 80){
grade = 'B';
cout << 'B' << endl;
}else if (avg >= 70){
grade = 'C';
cout << 'C' << endl;
}else if (avg >= 60){
grade = 'D';
cout << 'D' << endl;
}else{
grade = 'F';
cout << 'F' << endl;
}
return grade;
}
int main(){
ifstream myFile;
myFile.open("scores.csv");
if(!myFile.is_open()){
cout << "Error" << endl;
}
string testScore1, testScore2, testScore3, testScore4, testScore5;
while (myFile.good()) {
getline(myFile, testScore1, ',');
getline(myFile, testScore2, ',');
getline(myFile, testScore3, ',');
getline(myFile, testScore4, ',');
getline(myFile, testScore5, '\n');
}
cout<< setw(15) <<" Test scores"<<endl;
cout<<"--------------------"<<endl;
cout<< " 1 2 3 4 5 Avg Grade"<<endl;
cout<<"=== === === === === ===== ====="<<endl;
cout<< " "<< testScore1<< " "<< testScore2 << " "<< testScore3 << " "<< testScore4 << " "<< testScore5<< " " << getAvg << " " << getGrade <<endl;
return 0;
}
| An answer has been given already and accepted.
To be complete, I will show a refactored and working version your code.
I uses no arrays. Just loops and functions.
#include <iostream>
#include <fstream>
#include <iomanip>
double getAvg(int testScore1, int testScore2, int testScore3, int testScore4, int testScore5){
double avg = (testScore1 + testScore2 + testScore3 + testScore4 + testScore5)/5.0;
return avg;
}
char getGrade(double avg){
char grade = 'F';
if (avg >= 90){
grade = 'A';
}else if (avg >= 80){
grade = 'B';
}else if (avg >= 70){
grade = 'C';
}else if (avg >= 60){
grade = 'D';
}
return grade;
}
int main(){
std::ifstream myFile("scores.csv");
if(!myFile){
std::cerr << "\nError: Could not open input file\n";
}
else {
std::cout<< std::setw(15) <<" Test scores\n--------------------\n 1 2 3 4 5 Avg Grade\n=== === === === === ===== =====\n";
int testScore1, testScore2, testScore3, testScore4, testScore5;
char comma1, comma2, comma3, comma4;
// Read all values in one line, then next line, next line and so on
while (myFile >> testScore1 >> comma1 >> testScore2 >> comma2 >> testScore3 >> comma3 >> testScore4 >> comma4 >> testScore5) {
// Calculate
double average = getAvg(testScore1, testScore2, testScore3, testScore4, testScore5);
char grade = getGrade(average);
std::cout<< " "<< testScore1<< " "<< testScore2 << " "<< testScore3 << " "<< testScore4 << " "<< testScore5<< " " << average << " " << grade << '\n';
}
}
return 0;
}
|
69,340,745 | 69,341,098 | Compiles error:Undefined reference, which is caused mainly by dependency with libraries? | I met a c++ compile error that almost drives me mad these days. The output info is
(/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: undefined reference to symbol '__libc_start_main@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libc.so.6: error adding symbols: DSO missing from command line
it's not undefined reference to `main', to be careful.)
The basic case is very simple. library B depends on library C. excutable A depends on library B, and thus depends on library C.
Below is my code, it's very simple as well.
**c.h**
void kk();
**c.cpp**
#include <iostream>
using namespace std;
void kk()
{
cout<<"111"<<endl;
}
**b.h**
#include "c.h"
void pp();
**b.cpp**
#include "b.h"
void pp()
{
kk();
}
**a.cpp**
#include "b.h"
int main()
{
pp();
}
And This is my Compiling process: make c && b respectively to be a shared library, and build a
through linking against them.
1. g++ -fpic -shared c.cpp -o libc.so
2. g++ -fpic -shared b.cpp -o libb.so
3. g++ a.cpp -o a -lb -lc -L.
Besides,I tried many ways to solve this problem. None worked. And I found that in the fianl step, If I do not link library c, the output is the same.It seems that I failed to link c finally,But I just did it, who knows the reason. The g++ version??
| Your libc.so conflicts with the one installed by glibc. You would need to change to use another name
|
69,341,174 | 69,341,348 | Cannot use C++ QQuickPaintedItem Singleton in QML | I have to create a C++ singleton class, but it doesn't work in qml.
#include "myimage.h"
MyImage::MyImage(QQuickPaintedItem *parent)
{
}
MyImage* MyImage::myImage = new MyImage;
MyImage *MyImage::instance()
{
return myImage;
}
void MyImage::paint(QPainter *painter)
{
QRectF target(10.0, 20.0, 80.0, 60.0);
QRectF source(0.0, 0.0, 70.0, 40.0);
painter->setRenderHint(QPainter::Antialiasing, true);
painter->setRenderHint(QPainter::SmoothPixmapTransform, true );
painter->drawImage(target, this->m_Image, source);
}
const QImage &MyImage::getM_Image() const
{
return m_Image;
}
void MyImage::setM_Image(const QImage &mimage)
{
if (mimage != m_Image) {
m_Image = mimage;
emit m_ImageChanged();
}
}//This is my singleton class.
Then I register it in main.cpp.
QObject *getMySingletonImage(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
return MyImage::instance();
}
...
qmlRegisterSingletonType<MyImage>("s0.image", 1, 0, "MyImage", &getMySingletonImage);
In QML:
import s0.image 1.0
MyImage{
}
I cannot run the program successfully.
qrc:/Camview_Page.qml:371:13: Element is not creatable.
Actually, I use the singleton class both in my backend and qml.
In my backend, I will get QImage type images but not be saved local, so I cannot use QUrl and I only figure out this method.
Expectation:
My backend pass images of QImage type to the singleton class, my singleton class realize the method of paint, my qml show the image.
BTW...my backend gets images from camera.
| A singleton is already created for QML so you get that error message since by using "{}" you are trying to create the object.
In this case it is enough to set a parent and the size:
import QtQuick 2.15
import QtQuick.Window 2.15
import s0.image 1.0
Window {
id: root
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Component.onCompleted: {
MyImage.parent = root.contentItem
MyImage.width = 100
MyImage.height = 100
}
}
If you want to create a binding for example set anchors.fill: parent then you can use the Binding component, if you want to hear any signal then you must use Connections component.
import QtQuick 2.15
import QtQuick.Window 2.15
import s0.image 1.0
Window {
id: root
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Binding{
target: MyImage
property: "parent"
value: root.contentItem
}
Binding {
target: MyImage
property: "anchors.fill"
value: MyImage.parent
}
Connections{
target: MyImage
function onWidthChanged(){
console.log("width:", MyImage.width)
}
function onHeightChanged(){
console.log("height:", MyImage.height)
}
}
}
|
69,341,307 | 69,341,980 | Difference between using << operator with stringsteam and write member function | I have observed that when a uint8_t type buffer (not guaranteed to be null terminated) is read into a stringstream with the << operator using ss << buff.data, and the contained std::string is returned to Python, Python throws an error:
UnicodeDecodeError: 'utf-8' codec can't decode byte
But, if I use ss.write(buff.data, buff.size), the issue is not there.
I assume that this issue is because when using <<, there is a buffer overrun, and the data in ss might not be UTF-8 anymore. But when I do write(), I define the size and so there is no possibility of garbage data.
What is surprising is that if I do ss.write(buff.data, buff.size + 1), I always observe a segfault. So I can't figure out how << can do a buffer overrun? Is there a fundamental difference between how both of these work, and so one triggers a segfault when it makes an illegal buffer access, and the other one does not? Or, is << just getting lucky?
| uint8_t is an alias for unsigned char. When operator<< is given an unsigned char* pointer, it is treated as a null-terminated string, same as a char* pointer. So, if your data is not actually a null-terminated character string, writing it to the stream using operator<< is undefined behavior. The code may crash. It may write garbage to the stream. There is no way to know.
write() doesn't care about a null terminator. It writes exactly as many bytes as you specify. That is why you don't have any trouble when using write() instead of operator<<.
|
69,341,853 | 69,342,028 | Can pointers on std::type_info be compared for equality in constant expressions? | One can define a constexpr pointer on std::type_info object of any class T. Does the language allows one to compare such pointers for equality in compile-time?
For example:
#include <typeinfo>
template <typename T>
inline constexpr auto * pType = &typeid(T);
int main() {
static_assert( pType<int> == pType<int> );
static_assert( pType<int> != pType<char> );
}
The question arises, since Clang accepts it, but GCC returns the error:
error: non-constant condition for static assertion
8 | static_assert( pType<int> != pType<char> );
| ~~~~~~~~~~~^~~~~~~~~~~~~~
<source>:8:31: error: '(((const std::type_info*)(& _ZTIi)) != ((const std::type_info*)(& _ZTIc)))' is not a constant expression
Demo: https://gcc.godbolt.org/z/9broYrEn7
| This is a GCC bug: 85428
By the way, pType<int> == pType<int> is not always guaranteed.
|
69,342,158 | 69,342,570 | Is it possible to extend the life of an rvalue passed into a function? | I am trying to make a system for lazy evaluation, however it seems my system wont work with rvalues/temporary variable. for example
class Number;
class LazyAddition
{
public:
Number& lhs;
Number& rhs;
LazyAddition(Number& lhs, Number& rhs)
: lhs(lhs), rhs(rhs)
{
}
LazyAddition(Number&& lhs, Number&& rhs)
: lhs(lhs), rhs(rhs)
{
}
};
class Number
{
public:
Number(int x)
: x(x)
{
}
LazyAddition operator+(Number& rhs)
{
return LazyAddition(*this, rhs);
}
Number(LazyAddition lazy)
{
x = lazy.lhs.x + lazy.rhs.x;
}
private:
int x;
};
It works fine when passing in lvalues like
Number num1(3)
Number num2(4)
LazyAddition { num1, num2 }
it also function when passing in rvalues
LazyAddition { Number(3), Number(4) }
however after the constructor is called, the number rvalues are immediately destroyed. this is problematic since I have references to them. I thought assigning the rvalue reference to the lvalue reference in the LazyAddition constructor might expand the lifetime, but it doesn't. is there any way to achieve this, or a better way to not copy rvalues?
| Because the rvalues are bound to the parameters of the constructor firstly, and bounding them to the class members later does not further extend their lifetime.
You can define your LazyAddition class as an aggregate to avoid binding the rvalues to parameters of constructor:
struct LazyAddition
{
const Number& lhs;
const Number& rhs;
};
But be careful. After C++20, you should use list-initialization syntax to initialize such a LazyAddition aggregate, like LazyAddition { Number(3), Number(4) }, otherwise the lifetime will still not be extended.
|
69,342,182 | 69,342,585 | How can I give two compatible names to a C++ class template with deduction guides? | If I have a widely-used class template called Foo that I want to rename to Bar without having to update all of its users atomically, then up until C++17 I could simply use a type alias:
template <typename T>
class Bar {
public:
// Create a Bar from a T value.
explicit Bar(T value);
};
// An older name for this class, for compatibility with callers that haven't
// yet been updated.
template <typename T>
using Foo = Bar<T>;
This is very useful when working in a large, distributed codebase. However as of C++17 this seems to be broken by class template argument deduction guides. For example, if this line exists:
template <typename T>
explicit Foo(T) -> Foo<T>;
then the obvious thing to do when renaming the class is to change the Foos in the deduction guide to Bars:
template <typename T>
explicit Bar(T) -> Bar<T>;
But now the expression Foo(17) in a random caller, which used to be legal, is an error:
test.cc:42:21: error: alias template 'Foo' requires template arguments; argument deduction only allowed for class templates
static_cast<void>(Foo(17));
^
test.cc:34:1: note: template is declared here
using Foo = Bar<T>;
^
Is there any easy and general way to give a class with deduction guides two simultaneous names in a fully compatible way? The best I can think of is defining the class's public API twice under two names, with conversion operators, but this is far from easy and general.
| Your problem is exactly what P1814R0: Wording for Class Template Argument Deduction for Alias Templates
wants to solve, that is to say, in C++20, you only need to add deduction guides for Bar to make the following program well-formed:
template <typename T>
class Bar {
public:
// Create a Bar from a T value.
explicit Bar(T value);
};
// An older name for this class, for compatibility with callers that haven't
// yet been updated.
template <typename T>
using Foo = Bar<T>;
template <typename T>
explicit Bar(T) -> Bar<T>;
int main() {
Bar bar(42);
Foo foo(42); // well-formed
}
Demo.
But since it is a C++20 feature, there is currently no solution in C++17.
|
69,343,060 | 69,343,139 | C++: Cannot convert string to char*? | I'm trying to print the first item (top item) of a Deque in C++ with the following piece of code:
#include <queue>
#include <deque>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
deque<string> commandHistory;
for (int i = 0; i < 2; i++) {
commandHistory.push_back("asdf");
}
printf(commandHistory.at(1));
return 0;
}
However, I get an error in the printf statement:
error: cannot convert
‘__gnu_cxx::__alloc_traitsstd::allocator<std::__cxx11::basic_string<char
, std::__cxx11::basic_string >::value_type’ {aka ‘std::__cxx11::basic_string’} to ‘const char*’
However, I cannot cast commandHistory.at(1) to a const char* like so:
printf((const char*) commandHistory.at(1));
| Eventhough your question is marked both C and C++, I'd remove the C tag since your code is more C++ than C.
The documentation for printf is here: https://en.cppreference.com/w/cpp/io/c/fprintf
The gist of that function is that it takes at least 1 param: the so called format string, which as the signature says, is a const char*.
char * and std::string are totally different types. std::string is a class and char * is just a pointer to a builtin type. Your std::deque contains std::string objects.
Conveniently, std::string offers a conversion function to const char* for exactly these cases.
A working snippet would thus be:
// looks like you were missing cstdio
#include <cstdio>
#include <deque>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
deque<string> commandHistory;
for (int i = 0; i < 2; i++) {
commandHistory.push_back("asdf");
}
// note the `c_str` method call to get a c-style string from a std::string
printf(commandHistory.at(1).c_str());
return 0;
}
Like the compiler says, you can't convert (with static_cast) a std::string to a char*, but you can obtain that desired const char* with .c_str().
As other mentioned, you could also include iostream and use std::cout which knows what to do (by overloading) with each type (const char*, std::string, int, ...) and can also be used with your own types.
EDIT: cleaner/clearer code/explanations.
|
69,343,108 | 69,343,737 | Q1 : priority_queue "come before means output last", Q2 : custom compare with sort and priority_queue | Q1
https://en.cppreference.com/w/cpp/container/priority_queue
i'm looking this webpage and in template parameters section Compare says like this.
But because the priority queue outputs largest elements first, the
elements that "come before" are actually output last.
i learned that heap realization like this.
parent node : i / 2
left child node : i * 2
right child node : i * 2 + 1
so if i make max heap then array will made like this.
https://media.vlpt.us/images/emplam27/post/4a05c33e-2caf-4b28-964c-7019c13ff34b/%ED%9E%99%20-%20%EB%B0%B0%EC%97%B4%EB%A1%9C.png
so i can't understand why come before element will output last mean. did i miss something?
Q2
i want to make custom compare object for sort and priority queue. here is my code.
struct Compare
{
bool operator()(vector<int>& l, vector<int>& r) { return r[1] < l[1]; }
};
bool compare(vector<int>& l, vector<int>& r) { return l[0] < r[0]; }
int solution(vector<vector<int>> jobs) {
sort(jobs.begin(), jobs.end(), compare);
priority_queue<vector<int>, vector<vector<int>>, Compare> jobQueue;
}
i was wanted that sort should be ascending, and priority_queue should be min heap to pop least element first. and code work right.
but i feel that code is little unpretty that similar compare were separated.
i want that compare function united to Compare class, but operator() function will be redeclared.
is it possible to unite code?
| Q1 is mostly a terminology clash; the ordering relation a < b usually says "a is ordered before b", but in a priority_queue, a < b means "a has a lower priority than b".
So b is before a in the priority order. (That is, the priority order is the opposite of the ordering relation's order.)
Here is one suggestion regarding Q2; a class template.
template<typename T, size_t index>
struct Compare
{
bool operator()(vector<int>& l, vector<int>& r) { return order(l[index], r[index]); }
T order;
};
using SortedOrder = Compare<std::less<int>, 0>;
using PriorityOrder = Compare<std::greater<int>, 1>;
int solution(vector<vector<int>> jobs) {
sort(jobs.begin(), jobs.end(), SortedOrder());
priority_queue<vector<int>, vector<vector<int>>, PriorityOrder> jobQueue;
return 0;
}
|
69,343,160 | 69,376,745 | Given an array 'a' and an integer 'x', arrange the elements of the (in place) such that all the elements <x come before all the elements >='x' | Also, preserve the original relative order of elements in both the groups (i.e elements smaller than 'x' form one group and elements equal to or greater than 'x' form another group. The relative order should be maintained in both the groups.)
Example 1:-
a={2,6,3,5,1,7}
x=5
Output : 2 3 1 6 5 7
All the elements smaller than 5 come before 5 and the relative order of the moved elements is
preserved (2,3,1) & (6,5,7)
Example 2:-
a={1,4,2,5,3}
x=4
output : 1 2 3 4 5
The original question was for a singly linked list . I wrote the algorithm for an array and I wanted to know if it can be ported to the linked list variation. Also, is there a better way of doing this?
#include <bits/stdc++.h>
using namespace std;
void swap(vector<int> &a, int i, int j)
{
int i2 = i;
int x = a[j];
int temp1 = a[i];
int temp2;
while (i < j)
{
temp2 = a[i + 1];
a[i + 1] = temp1;
temp1 = temp2;
i++;
}
a[i2] = x;
}
void solve(vector<int> &a, int num)
{
int n = a.size();
int i = 0, j = 1;
while (j < n)
{
if (a[i] < num)
i++;
if (a[i] >= num && a[j] < num)
swap(a, i, j);
j++;
}
}
int main()
{
vector<int> a = {2, 6, 3, 5, 1, 7};
int num = 5;
solve(a, num);
for (auto el : a)
cout << el << " ";
return 0;
}
| When working with linked lists, the concept of swapping is not really useful for linked lists. Instead you would move nodes.
Here is a possible implementation:
#include <iostream>
class Node {
public:
int value;
Node * next;
Node(int value, Node * next) {
this->value = value;
this->next = next;
}
Node(int value) {
this->value = value;
this->next = nullptr;
}
void print() {
Node * node = this;
while (node != nullptr) {
std::cout << node->value << " -> ";
node = node->next;
}
std::cout << "NULL\n";
}
Node * partition(int pivot) {
if (this->next == nullptr) return this; // Quick exit
Node * preHead = new Node(0); // Dummy
Node * preMid = new Node(0, this); // Dummy
Node * lessTail = preHead;
Node * prev = preMid;
while (prev->next) {
Node * curr = prev->next;
if (curr->value < pivot) {
prev->next = curr->next; // remove curr
lessTail->next = curr; // insert curr
lessTail = curr;
} else {
prev = curr; // keep curr where it is
}
}
lessTail->next = preMid->next;
delete preMid;
Node * head = preHead->next;
delete preHead;
return head;
}
};
int main() {
// Construct the list from example #2
Node * head = new Node(1,
new Node(4,
new Node(2,
new Node(5,
new Node(3)))));
head->print(); // 1 -> 4 -> 2 -> 5 -> 3 -> NULL
head = head->partition(4);
head->print(); // 1 -> 2 -> 3 -> 4 -> 5 -> NULL
// ...
}
This code uses two temporary node instances, because that makes the code a bit easier. But it is also possible to do it without those dummy nodes. In that case you must perform some nullpointer checks to see when to assign to a next property or to a head variable.
|
69,343,172 | 69,344,066 | Throwing data member's destructor | I have a class that holds an object which destructor's can throw (it is actually a tbb::task_group, but I named it MyObject for simplicity here).
The code is like this:
#include <stdexcept>
class MyObject {
public:
MyObject() {}
~MyObject() noexcept(false) {}
};
class A {
public:
A() {}
virtual ~A() {}
};
class B : public A {
public:
B() : A() {}
~B() {}
private:
MyObject _object;
};
And the compiler raises the following error:
exception specification of overriding function is more lax than base version
I do not like the idea of spreading noexcept(false) all over the code so I was thinking about using raw pointers to MyObject, and deleting them outside of the destructor (e.g. in a Close function).
What is the best way to handle that kind of scenario?
| Based on a suggestion from @463035818_is_not_a_number, it is possible to wrap the throwing class into a custom one that does not throw.
In my case, for tbb::task_group, it could be like this:
class TaskGroup {
public:
TaskGroup() {
_task = new tbb::task_group();
}
// This destructor will not throw.
// Not very pleased with "catch (...)" but not much choice due to TBB's implementation.
~TaskGroup() {
try {
delete _task;
} catch (...) {}
}
// Wrap any other needed method here.
private:
tbb::task_group* _task;
};
|
69,343,832 | 69,388,472 | Why g++ tries to link against the wrong libstdc++.so library? | I am trying to write a very simple test application that uses Matlab C++ interface. My machine is running CentOs7 that comes with the default gcc 4.8.5. But for my application, I need gcc 7+, so I have installed gcc 7.3.1 as well. For compiling this mini-app, I use this command:
g++ -o matlab_test matlab_test.cpp -I/home/matlab/lnx_x64/R2017B/release/inc -L/home/matlab/R2017B/release/lib -lMatlabEngine -lpthread -Wl,-v
but I am facing this issue:
collect2 version 7.3.1 20180303 (Red Hat 7.3.1-5)
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld -plugin /opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/liblto_plugin.so -plugin-opt=/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/lto-wrapper -plugin-opt=-fresolution=/tmp/ccDdzXBy.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --no-add-needed --eh-frame-hdr --hash-style=gnu -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o matlab_cpp_test /lib/../lib64/crt1.o /lib/../lib64/crti.o /opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/crtbegin.o -L/home/matlab/lnx_x64/R2017B/release/lib -L/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7 -L/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/../../.. /tmp/ccsqA2N9.o -lpthread -lMatlabEngine -lstdc++ -v -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/crtend.o /lib/../lib64/crtn.o
GNU ld version 2.28-11.el7
/home/matlb/lnx_x64/R2017B/release/lib/libMatlabEngine.so: undefined reference to `__cxa_throw_bad_array_new_length@CXXABI_1.3.8'
collect2: error: ld returned 1 exit status
I checked the error message in some other SO questions like this. According to the answer, I am linking against the wrong version of libstdc++. But when I check my LD_LIBRARY_PATH variable, it contains the path for the new libstdc++.so at the beginning:
[giant@centos-machine test]$ echo $LD_LIBRARY_PATH
/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7:/opt/rh/devtoolset-7/root/usr/lib64:/opt/rh/devtoolset-7/root/usr/lib:/opt/rh/devtoolset-7/root/usr/lib64/dyninst:/opt/rh/devtoolset-7/root/usr/lib/dyninst:/opt/rh/devtoolset-7/root/usr/lib64:/opt/rh/devtoolset-7/root/usr/lib
Can anyone give me some pointers how I should fix this issue?
|
/opt/rh/devtoolset-7
devtoolset-7 :
/opt/rh/devtoolset-7/root/usr/lib/gcc/x86_64-redhat-linux/7/libstdc++.so
...... is a 210B text file :
/* GNU ld script
Use the shared library, but some functions are only in
the static library, so try that secondarily. */
OUTPUT_FORMAT(elf64-x86-64)
INPUT ( /usr/lib64/libstdc++.so.6 -lstdc++_nonshared )
/usr/lib64/libstdc++.so.6 will be used.
"Other extra gcc/g++" for EL7 : how to install gcc 4.9.2 on RHEL 7.4
|
69,345,094 | 69,345,564 | How do I convert my point light into an oval/ellipse? | I am looking to turn my current circular light into an ellipse by having a vec2 radius which can have different x and y values. Is there any way to do this based on my current code in the fragment shader?
uniform struct Light
{
vec4 colour;
vec3 position;
vec2 radius;
float intensity;
} allLights[MAX_LIGHTS];
vec4 calculateLight(Light light)
{
vec2 lightDir = fragmentPosition.xy - light.position.xy;
float lightDistance = length(lightDir);
if (lightDistance >= light.radius.x)
{
return vec4(0, 0, 0, 1); //outside of radius make it black
}
return light.intensity * (1 - lightDistance / light.radius.x) * light.colour;
}
| Divide the vector to the light source with the semi-axis of the ellipse and check whether the length of the vector is greater than 1.0:
if (length(lightDir / light.radius) >= 1.0)
return vec4(0, 0, 0, 1); //outside of radius make it black
return light.intensity * (1 - length(lightDir / light.radius)) * light.colour;
|
69,345,625 | 69,345,711 | Constructor delegation with std::array<> | I have a class which receives a std::array in the constructor. For the life of me I can't write a correct and simple delegation from std::initializer_list - only the awkward lambda which I have commented out. Can someone show me a clean and sensible way without ad-hoc code?
#include <array>
class foo
{
std::array<int,5> t_;
public:
foo(): foo{{}}
{ }
foo(std::initializer_list<int> il = {}): foo{ std::array<int,5>(il) }
// foo { [il]() {
// std::array<int,5> tmp;
// std::size_t i = 0;
// for (auto ile: il)
// if (i >= tmp.size()) break;
// else tmp[i++]=ile;
// return tmp;
// }()}
{ }
foo(std::array<int,5> t): t_(t)
{ }
};
This gives:
g++ -std=c++17 -pedantic -Wall -Wextra -c -o t.o t.cpp
t.cpp: In constructor 'foo::foo(std::initializer_list<int>)':
t.cpp:12:69: error: no matching function for call to 'std::array<int, 5>::array(std::initializer_list<int>&)'
12 | foo(std::initializer_list<int> il = {}): foo{ std::array<int,5>(il) }
| ^
In file included from t.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/10/include/c++/array:94:12: note: candidate: 'std::array<int, 5>::array()'
94 | struct array
| ^~~~~
/usr/lib/gcc/x86_64-pc-cygwin/10/include/c++/array:94:12: note: candidate expects 0 arguments, 1 provided
/usr/lib/gcc/x86_64-pc-cygwin/10/include/c++/array:94:12: note: candidate: 'constexpr std::array<int, 5>::array(const std::array<int, 5>&)'
/usr/lib/gcc/x86_64-pc-cygwin/10/include/c++/array:94:12: note: no known conversion for argument 1 from 'std::initializer_list<int>' to 'const std::array<int, 5>&'
/usr/lib/gcc/x86_64-pc-cygwin/10/include/c++/array:94:12: note: candidate: 'constexpr std::array<int, 5>::array(std::array<int, 5>&&)'
/usr/lib/gcc/x86_64-pc-cygwin/10/include/c++/array:94:12: note: no known conversion for argument 1 from 'std::initializer_list<int>' to 'std::array<int, 5>&&'
t.cpp:12:71: error: no matching function for call to 'foo::foo(<brace-enclosed initializer list>)'
12 | foo(std::initializer_list<int> il = {}): foo{ std::array<int,5>(il) }
| ^
t.cpp:23:3: note: candidate: 'foo::foo(std::array<int, 5>)'
23 | foo(std::array<int,5> t): t_(t)
| ^~~
t.cpp:23:3: note: conversion of argument 1 would be ill-formed:
t.cpp:12:3: note: candidate: 'foo::foo(std::initializer_list<int>)'
12 | foo(std::initializer_list<int> il = {}): foo{ std::array<int,5>(il) }
| ^~~
t.cpp:12:3: note: conversion of argument 1 would be ill-formed:
t.cpp:9:3: note: candidate: 'foo::foo()'
9 | foo(): foo{{}}
| ^~~
t.cpp:9:3: note: candidate expects 0 arguments, 1 provided
t.cpp:3:7: note: candidate: 'constexpr foo::foo(const foo&)'
3 | class foo
| ^~~
t.cpp:3:7: note: conversion of argument 1 would be ill-formed:
t.cpp:3:7: note: candidate: 'constexpr foo::foo(foo&&)'
t.cpp:3:7: note: conversion of argument 1 would be ill-formed:
| std::array has no (any) explicitly declared constructors and so, it has no constructor from initializer list, so you cant just forward initializer list to array.
As a workaround, you can use variadic template constructor
template <typename ... Args>
foo(Args && ... args) : foo(std::array<int, 5>({args ...}))
|
69,346,153 | 69,511,030 | Disable CPU package idle states in Windows from C++ code | I am successfully disabling CPU core C-states using this code (I’m working on Win10 and use Qt):
#include <QCoreApplication>
#include <QDebug>
#include "Windows.h"
extern "C" {
#include "powrprof.h"
}
#pragma comment(lib, "powrprof.lib")
int main()
{
const DWORD DISABLED = 1;
const DWORD ENABLED = 0;
GUID *scheme;
int error;
error = PowerGetActiveScheme(NULL, &scheme);
qDebug() << "PowerGetActiveScheme error code = " << error;
error = PowerWriteACValueIndex(NULL, scheme, &GUID_PROCESSOR_SETTINGS_SUBGROUP, &GUID_PROCESSOR_IDLE_DISABLE, DISABLED);
qDebug() << "PowerWriteACValueIndex error code = " << error;
error = PowerWriteDCValueIndex(NULL, scheme, &GUID_PROCESSOR_SETTINGS_SUBGROUP, &GUID_PROCESSOR_IDLE_DISABLE, DISABLED);
qDebug() << "PowerWriteDCValueIndex error code = " << error;
error = PowerSetActiveScheme(NULL, scheme);
qDebug() << "PowerSetActiveScheme error code = " << error;
return 0;
}
The reason behind this is that I am running an USB camera and figured out that I’m losing data packets when the processor enters idle modes. The code above works fine and overcomes this issue successfully. But it’s actually a bit too much (disabling all C states appears to be unnecessary). I made some tests with the vendor software of the camera and found out that during acquisition not the core C-states stop, but the package C-states (if it is of any interest, I posted the analysis of this problem in the answer here https://superuser.com/questions/1648849/monitor-used-usb-bandwidth-in-win10).
So my question is: Can I adapt the above code to only disable package idle states? In case that’s not possible, can I selectively disable core C-states?
Update:
Based on the suggestion of @1201ProgramAlarm I tried to use SetThreadPriority() as in the minimal example below:
#include <QDebug>
#include <windows.h>
#include <conio.h>
#include "processthreadsapi.h"
int main()
{
bool ok = false;
ok = SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
qDebug() << "SetPriorityClass ok = " << ok;
ok = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
qDebug() << "SetThreadPriority ok = " << ok;
for (int i=1;i<100;i++) {
qDebug() << "Here I am in some dummy loop...";
if (_kbhit()) {
break;
}
Sleep(1000);
}
return 0;
}
Unfortunately, this doesn't help and when monitoring the cpu package idle states (using HWiNFO64) I see no effect (package goes still idle as before).
| The system is shutting down the USB device to save power.
This link provides the solution USB system power issue.
Open the Device manager as administrator.
Find the camera.
On the "Power Management" tab, deselect "Allow the computer to turn off this device to save power".
This can be done programmatically if the device ID is known.
|
69,346,522 | 69,348,572 | How can I set the initial index for Shift + click selection in Qt QTableView? | My issue is that after Ctrl + click deselect of an item. It became the initial index of the following Shift + click select.
What I would like to happen is set the initial index of the Shift selection to index 0.
For example:
#include <QApplication>
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStringListModel model({"1", "2", "3", "4", "5", "6", "7", "8", "9"});
QTableView view;
view.horizontalHeader()->setVisible(false);
view.setSelectionBehavior(QAbstractItemView::SelectRows);
view.setSelectionMode(QAbstractItemView::ExtendedSelection);
view.setModel(&model);
view.show();
return a.exec();
}
Select row header 2
Deselect row header 2 using Ctrl + click
Shift + click row header 5
Expected result:
Row 1, 2, 3, 4, and 5 are selected.
Actual result:
Rows 2, 3, 4, and 5 are selected.
Is there any way to produce the expected result?
| You should subclass QTableView for this purpose. Here is small example tested for Qt4. For Qt5 it should be pretty similar.
Header:
#ifndef CUSTOMTABLEWIDGET_H
#define CUSTOMTABLEWIDGET_H
#include <QTableView>
class CustomTableWidget : public QTableView
{
Q_OBJECT
public:
explicit CustomTableWidget(QWidget *parent = 0);
protected:
void mousePressEvent(QMouseEvent *event);
};
#endif // CUSTOMTABLEWIDGET_H
Cpp:
#include "customtablewidget.h"
#include <QMouseEvent>
#include <QItemSelectionModel>
CustomTableWidget::CustomTableWidget(QWidget *parent) :
QTableView(parent)
{
}
void CustomTableWidget::mousePressEvent(QMouseEvent *event)
{
QModelIndex clickedIndex = this->indexAt(QPoint(event->x(), event->y()));
bool isShiftClicked = Qt::LeftButton == event->button() && (event->modifiers() & Qt::ShiftModifier);
if (clickedIndex.isValid() && isShiftClicked)
{
bool isRowSelected = this->selectionModel()->isRowSelected(clickedIndex.row(),
clickedIndex.parent());
if (!isRowSelected)
{
QModelIndex initialIndex = this->model()->index(0, 0);
this->selectionModel()->clear();
this->selectionModel()->select(QItemSelection(initialIndex, clickedIndex),
QItemSelectionModel::Select);
event->accept();
return;
}
}
QTableView::mousePressEvent(event);
}
|
69,346,632 | 69,347,341 | define constants in a struct | I'm trying to create a struct with some constants in it like this:
#include <CoreAudio/CoreAudio.h>
...
struct properties {
//Volume control
const AudioObjectPropertyAddress volume = {
kAudioDevicePropertyVolumeScalar, //mSelector
kAudioDevicePropertyScopeOutput, //mScope
0 //mElement
};
//Mute control
const AudioObjectPropertyAddress mute = {
kAudioDevicePropertyMute,
kAudioDevicePropertyScopeOutput,
0
};
};
However, I cannot access the constants in this class;
//Function used to for example set volume level or set mute status
//bool setProperty(UInt32 data_to_write, AudioObjectPropertyAddress addr_to_write_to);
//Following line should mute the system audio
setProperty(1, properties::mute);
This will make the compiler return the following error:
error: invalid use of non-static data member 'mute'
So, I tried making the constants static like this:
const static AudioObjectPropertyAddress volume = { ...
But now, I get a different error:
error: in-class initializer for static data member of type 'const AudioObjectPropertyAddress' requires 'constexpr' specifier
The last thing I tried is changing const static to static constexpr, however again, I cannot access the constants. Every time I try to access them, the compiler show this error:
Undefined symbols for architecture x86_64:
"properties::mute", referenced from:
_main in main-fefb9f.o
ld: symbol(s) not found for architecture x86_64
I'm not really sure what's going on here, I tried converting my struct into a class, but I ended up getting the same Undefined symbols error.
I know I could just define the two constants as global variables, but I thought putting them into a struct/class would make the code look "nicer" or just more organized.
Could someone please explain what's wrong here and provide a possible solution?
|
struct properties {
//Volume control
const AudioObjectPropertyAddress volume = {
kAudioDevicePropertyVolumeScalar, //mSelector
kAudioDevicePropertyScopeOutput, //mScope
0 //mElement
};
};
is valid, but volume is not a static member, so usage requires an instance:
setProperty(1, properties{}.volume);
With static const, it would be:
struct properties {
//Volume control
static const AudioObjectPropertyAddress volume;
};
const properties::AudioObjectPropertyAddress volume {
kAudioDevicePropertyVolumeScalar, //mSelector
kAudioDevicePropertyScopeOutput, //mScope
0 //mElement
};
and usage might be the expected:
setProperty(1, properties::volume);
with static constexpr in C++11/C++14:
struct properties {
//Volume control
static constexpr AudioObjectPropertyAddress volume{
kAudioDevicePropertyVolumeScalar, //mSelector
kAudioDevicePropertyScopeOutput, //mScope
0 //mElement
};
};
const properties::AudioObjectPropertyAddress volume; // Definition when ODR-used
with static /*inline*/ constexpr since C++17:
struct properties {
//Volume control
static /*inline*/ constexpr AudioObjectPropertyAddress volume{
kAudioDevicePropertyVolumeScalar, //mSelector
kAudioDevicePropertyScopeOutput, //mScope
0 //mElement
};
};
|
69,346,803 | 69,368,861 | How to configure and export function that should return char array? | I'm trying to create a function that can be called from e.g. Python through a .dll.
I'm working on byte arrays.
This is the original function I'm trying to wrap:
QByteArray getKeys(const QByteArray data, const QByteArray info);
What should the C style interface and implementation look like? Do I have to pass char* arrays and array sizes?
My idea is something along these lines:
__declspec(dllexport) int getKeys(const char* data, int dataSize, const char* info, int infoSize, const char** result);
The function would return the result as a side-effect and the return value is the size of the result.
| Listing [Python.Docs]: ctypes - A foreign function library for Python.
@Jarod42's suggestion wasn't to use std::pair, but to emulate it via a C (compatible) struct. Here's an example (my dummy getKeys implementation is to simply return the concatenation the 2 QByteArray arguments):
dll00.cpp:
#include <QtCore/QByteArray>
#include <cstdio>
#include <cstring>
#if defined(_WIN32)
# define DLL00_EXPORT_API __declspec(dllexport)
#else
# define DLL00_EXPORT_API
#endif
typedef struct {
size_t size = 0;
char *data = nullptr;
} CBuffer;
#if defined(__cplusplus)
extern "C" {
#endif
DLL00_EXPORT_API CBuffer getKeysWrapper(const CBuffer data, const CBuffer info);
DLL00_EXPORT_API void freeBuffer(CBuffer *pBuf);
#if defined(__cplusplus)
}
#endif
static QByteArray getKeys(const QByteArray &data, const QByteArray &info)
{
printf("C++ - data[%d]: %s\n", data.size(), data.constData());
printf("C++ - info[%d]: %s\n", info.size(), info.constData());
QByteArray ret(data);
ret += info;
printf("C++ - ret[%d]: %s\n", ret.size(), ret.constData());
return ret;
}
CBuffer getKeysWrapper(const CBuffer data, const CBuffer info)
{
QByteArray keys = getKeys(QByteArray(data.data, data.size), QByteArray(info.data, info.size));
CBuffer buf = { static_cast<size_t>(keys.size()), new char[keys.size()] };
memcpy(buf.data, keys.constData(), buf.size);
return buf;
}
void freeBuffer(CBuffer *pBuf)
{
if (!pBuf)
return;
delete[] pBuf->data;
pBuf->data = nullptr;
pBuf->size = 0;
}
code00.py:
#!/usr/bin/env python
import sys
import ctypes as ct
DLL_NAME = "./dll00.{:s}".format("dll" if sys.platform[:3].lower() == "win" else "so")
CharPtr = ct.POINTER(ct.c_char)
class CBuffer(ct.Structure):
_fields_ = [
("size", ct.c_size_t),
("data", CharPtr),
]
def main(*argv):
dll00 = ct.CDLL(DLL_NAME)
getKeysWrapper = dll00.getKeysWrapper
getKeysWrapper.argtypes = (CBuffer, CBuffer)
getKeysWrapper.restype = CBuffer
freeBuffer = dll00.freeBuffer
freeBuffer.argtypes = (ct.POINTER(CBuffer),)
freeBuffer.restype = None
data_b = b"123456"
data_b_len = len(data_b)
info_b = b"abcd\0ef"
info_b_len = len(info_b)
data = CBuffer(data_b_len, (ct.c_char * data_b_len)(*data_b))
info = CBuffer(info_b_len, (ct.c_char * info_b_len)(*info_b))
keys = getKeysWrapper(data, info)
print("PY - keys:", keys.size, bool(keys.data), " ".join(str(keys.data[i]) for i in range(keys.size)))
freeBuffer(ct.byref(keys))
print("PY - keys(freed):", keys.size, bool(keys.data))
if __name__ == "__main__":
print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
64 if sys.maxsize > 0x100000000 else 32, sys.platform))
rc = main(*sys.argv[1:])
print("\nDone.")
sys.exit(rc)
Output:
[cfati@cfati-5510-0:/mnt/e/Work/Dev/StackOverflow/q069346803]> ~/sopr.sh
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###
[064bit prompt]> ls
code00.py dll00.cpp
[064bit prompt]> g++ -fPIC -DQT_NO_VERSION_TAGGING -I/home/cfati/Install/Qt/Qt/5.12.11/gcc_64/include -shared -o dll00.so -L/home/cfati/Install/Qt/Qt/5.12.11/gcc_64/lib dll00.cpp -lQt5Core
[064bit prompt]> ls
code00.py dll00.cpp dll00.so
[064bit prompt]>
[064bit prompt]> LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/cfati/Install/Qt/Qt/5.12.11/gcc_64/lib python code00.py
Python 3.8.10 (default, Jun 2 2021, 10:49:15) [GCC 9.4.0] 064bit on linux
C++ - data[6]: 123456
C++ - info[7]: abcd
C++ - ret[13]: 123456abcd
PY - keys: 13 True b'1' b'2' b'3' b'4' b'5' b'6' b'a' b'b' b'c' b'd' b'\x00' b'e' b'f'
PY - keys(freed): 0 False
Done.
|
69,346,955 | 69,347,033 | C++ uniform declaration is not working in class | I am trying to have a member array in a class with its length specified by the const static int variable for future needs.
My compiler throws an error with it, and I am not sure this is an error about a uniform initialization or array initialization, or both.
Here is the header file:
#ifndef SOUECE_H
#define SOURCE_H
class Test
{
public:
Test();
static const int array_length{2};
double array[array_length];
};
#endif
This is the source file.
#include "source.h"
Test::Test()
:array_length{0} //Typo of array{0}
{
}
These are the problem messages.
[enter image description here][1]
[1]: https://i.stack.imgur.com/IQ2Mk.png
This is the CMake file.
cmake_minimum_required(VERSION 3.0.0)
project(temp VERSION 0.1.0)
include(CTest)
enable_testing()
add_executable(temp main.cpp)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
Finally, these are what the compiler is complaining about when I try to build the project.
[main] Building folder: temp
[build] Starting build
[proc] Executing command: /usr/local/bin/cmake --build /Users/USERNAME/Desktop/temp/build --config Debug --target all -j 14 --
[build] [1/2 50% :: 0.066] Building CXX object CMakeFiles/temp.dir/main.cpp.o
[build] FAILED: CMakeFiles/temp.dir/main.cpp.o
[build] /usr/bin/clang++ -g -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX11.3.sdk -MD -MT CMakeFiles/temp.dir/main.cpp.o -MF CMakeFiles/temp.dir/main.cpp.o.d -o CMakeFiles/temp.dir/main.cpp.o -c ../main.cpp
[build] In file included from ../main.cpp:1:
[build] ../source.h:8:22: error: function definition does not declare parameters
[build] static const int array_length{2};
[build] ^
[build] ../source.h:9:18: error: use of undeclared identifier 'array_length'
[build] double array[array_length];
[build] ^
[build] 2 errors generated.
[build] ninja: build stopped: subcommand failed.
[build] Build finished with exit code 1
I am using macOS 12.0 beta, with VS Code 1.60.2, clang 13.0.0, CMake 3.20.2.
Please let me know if you see any wrong or have any suggestions.
| Since array_length is static const you have to initialize it like this:
source.h
#ifndef SOUECE_H
#define SOURCE_H
class Test
{
public:
Test();
static const int array_length = 2;
//static const int array_length{2}; this will also work just note that we cannot use constructor initializer list to initialize static data members
double array[array_length];
};
#endif
source.cpp
#include "source.h"
Test::Test()//we cannot use constructor initializer list to initialize array_length
{
}
Note that static const int array_length{2}; will also work but the thing is that in the constructor we cannot use constructor initializer list to initialize static data member.
EDIT:
If you decide to use static const int array_length{2}; then make sure that you have C++11(or later) enabled in your CMakeLists.txt. For this you can add
set (CMAKE_CXX_STANDARD 11)
to your CMakeLists.txt.
Alternatively, you could instead add
target_compile_features(targetname PUBLIC cxx_std_11)
in your CMakeLists.txt. In your case replace targetname with temp since that is the targetname that you have. Check this out for more how to active C++11 in CMake .
|
69,346,969 | 69,347,050 | using an initializer list where the values contain unique_ptr member variables | I have a class that contains a unique_ptr. I want to place instances of this class inside a container (specifically std::map). This works using std::move and .emplace however, I would like to perform all this initialization within the container's initializer list. Is this possible?
I suspect Foo gets initialized in the initializer list then copied which is causing the problem. I've tried added a std::move in the initializer list but that hasn't solved the problem.
class Foo
{
public:
std::unique_ptr<std::string> my_str_ptrs;
}
Compilation Fails "attempting to access a deleted function". This is an example of what I want to do
std::map<std::string, Foo> my_map{
{"a", Foo{}}
};
Compilation Succeeds
std::map<std::string, Foo> my_map;
my_map.emplace("a", Foo{});
| It's fault of std::initializer_list, if you look at it's begin/end member functions, they return const T*, which means it will force std::map to try use the copy constructor of your Foo, which is deleted as std::unique_ptr can not be copied.
This issue is not unique to std::map, any container which allows you to initialize it with std::initializer_list will really copy the arguments from an initializer list.
The C++ standard requires that during such initialization there's a temporary const T[N] array, which the std::initializer_list points to, const disables moves from it.
|
69,347,069 | 69,347,591 | Json::Value as private class member | I'm writing a C++ class for Reading/Writing strings from/to a json file using the jsoncpp lib.
My question is if it's possible to create a Json::Value private member for my class and use this every time I need to read/write instead of creating a new Json::Value inside every function?
If so, how can I initialize it in the constructor and access it inside every function?
| You don't need any special initialization for the Json::Value. You can make it a private member variable and use it like any other member variable.
Here's an example where I've added support for streaming from/to istream/ostream objects and a few member functions to demonstrate access to specific fields:
#include "json/json.h"
#include <fstream>
#include <iostream>
class YourClass {
public:
// two public accessors:
double getTemp() const { return json_value["Temp"].asDouble(); }
void setTemp(double value) { json_value["Temp"] = value; }
private:
Json::Value json_value;
friend std::istream& operator>>(std::istream& is, YourClass& yc) {
return is >> yc.json_value;
}
friend std::ostream& operator<<(std::ostream& os, const YourClass& yc) {
return os << yc.json_value;
}
};
int main() {
YourClass yc;
if(std::ifstream file("some_file.json"); file) {
file >> yc; // read file
std::cout << yc; // print result to screen
// use public member functions
std::cout << yc.getTemp() << '\n';
yc.setTemp(6.12);
std::cout << yc.getTemp() << '\n';
}
}
Edit: I was asked to explain the if statement and it means if( init-statement ; condition ) (added in C++17) which becomes approximately the same as this:
{ // scope of `file`
std::ifstream file("some_file.json");
if(file) { // test that `file` is in a good state
// ...
}
} // end of scope of `file`
|
69,347,072 | 69,347,590 | The input is a three-digit number. Print the arithmetic mean of its digits | I have a homework assignment. The input is a three-digit number. Print the arithmetic mean of its digits. I am new to C++ and cannot write the code so that it takes 1 number as input to a string. I succeed, only in a column.
#include <iostream>
int main()
{
int a,b,c;
std::cin >> a >> b >> c;
std::cout << (a+b+c)/3. << std::endl;
return 0;
}
If you write it in Python it looks like this. But I don't know how to write the same thing in C ++ :(
number = int(input())
digital3 = number % 10
digital2 = (number//10)%10
digital1 = number//100
summ = (digital1+digital2+digital3)/3
print(summ)
| The most direct translation from Python differs mostly in punctuation and the addition of types:
#include <iostream>
int main()
{
int number;
std::cin >> number;
int digital3 = number % 10;
int digital2 = (number/10)%10;
int digital1 = number/100;
int summ = (digital1+digital2+digital3)/3;
std::cout << summ << std::endl;
}
|
69,347,666 | 69,360,909 | Setting type of an outer variable using auto lambda parameters | I am using a C++ web framework that heavily uses callback lambda functions. As you may guess, parameters to lambdas are usually specified as auto due to the must to declare very long declarations.
Now I use decltype() operator to find the right type deduced by auto so that I can declare a vector of the same type. When the vector declaration happens inside the lambda, everything is fine.
Where my problem starts is this vector needs to be declared in an outer scope using lambdas auto parameters' type information. Below is a simple example:
std::vector<T> vec; // I want the type information to be inferred just like vec2 from lambda below
auto func = [](auto parameter){
std::vector<decltype(parameter)> vec2; // No problem here.
};
Is this possible?
UPDATE:
The framework I am using is uWebSockets. Here is the example code :
using DataType = std::string;
// I had to go get type information from the source code.
static std::vector<uWS::WebSocket<false, true, DataType> *> users;
uWS::App app {};
app.ws<DataType>("/*", {
.open = [](auto * ws){
// This is also doable
// But not accessible in other lambdas.
static std::vector<decltype(ws)> users2;
// users2.push_back(ws);
users.push_back(ws);
ws->subscribe("sensors/+/house");
},
.close = [](auto *ws, int code, std::string_view message){
users.erase(std::remove(users.begin(), users.end(), ws), users.end());
// Not possible because not accessible.
//users2.erase(std::remove(users2.begin(), users2.end(), ws), users2.end());
std::cout << "Client disconnected!" << std::endl;
},
.message = [](auto *ws, std::string_view message, uWS::OpCode opCode){
try{
std::string message2 = std::string(message) + std::string(" ACK");
for(const auto & ws2 : users)
if(ws != ws2)
ws2->send(message2, opCode);
}catch(std::exception& e){
std::cout << e.what() << std::endl;
}
},
});
Now, nowhere in the main.cpp, there is a need to pass a parameter to lambda functions. That's where the main problem comes from.
| You have to manually look at the type that you are initialising.
A generic lambda creates an object with a template operator(). There's not much stopping there from being multiple instantiations of that template.
If that's the case then there isn't a type that is the type of auto parameter.
You are relatively lucky here, in that the object you are initialising with all these functor members puts the arguments right in it's definition:
MoveOnlyFunction<void(WebSocket<SSL, true, UserData> *)> open = nullptr;
If you don't want to look at the definitions again, you could write a trait
template<typename Signature>
struct MoveOnlyFunctionTraits;
template <typename R, typename... Arguments>
struct MoveOnlyFunctionTraits<MoveOnlyFunctionTraits<R(Arguments...)> {
using result_type = R;
static constexpr auto arity = sizeof...(Arguments);
template <std::size_t I>
using argument = std::tuple_element_t<std::tuple<Arguments...>, I>;
}
template<typename Signature, std::size_t I>
using argument_t = typename MoveOnlyFunctionTraits<Signature>::template argument<I>;
That allows you to pull out the type
using websocket_type = argument_t<decltype(uWS::App::WebSocketBehaviour<DataType>::open), 0>;
std::vector<websocket_type> users;
Or you could submit a pull request to the library, that exposes type aliases you are interested in
template <bool SSL>
struct TemplatedApp {
// existing members ...
public:
template <typename DataType>
using websocket_type = WebSocket<SSL, true, DataType>;
};
Then
std::vector<uWS::App::template websocket_type<DataType> *> users;
|
69,348,036 | 69,348,499 | How to std::forward class template parameter | I'm getting compiler error when using std::forward on a class template parameter, but not on a function template parameter. I'd like to know how to std::forward a class template parameter. This is my code:
#include <iostream>
#include <vector>
template<typename T>
class Data_List {
std::vector<T> data_list;
public:
Data_List() = default;
~Data_List() = default;
std::size_t get_list_size() {
return data_list.size();
}
void add_to_list(T&& data) {
std::cout << "\nbefore inside add_to_list: " << data.size() << std::endl;
data_list.push_back(std::forward<T>(data));
std::cout << "after inside add_to_list: " << data.size() << std::endl;
}
};
template<typename T>
void print(T&& t) {
}
int main() {
Data_List<std::vector<int>> list_of_data;
std::vector<int> data(100, 2);
std::cout << "\n1. before size: " << data.size() << std::endl;
std::cout << "1. before Data_List size: " << list_of_data.get_list_size() << std::endl;
print(data);
// list_of_data.add_to_list(data); // gives compiler error here
std::cout << "\n1. after size: " << data.size() << std::endl;
std::cout << "1. after Data_List size: " << list_of_data.get_list_size() << std::endl;
std::cout << "--------------------------------------------------------------------------\n" << std::endl;
std::cout << "\n2. before size: " << data.size() << std::endl;
std::cout << "2. before Data_List size: " << list_of_data.get_list_size() << std::endl;
print(std::move(data));
list_of_data.add_to_list(std::move(data));
std::cout << "\n2. after size: " << data.size() << std::endl;
std::cout << "2. after Data_List size: " << list_of_data.get_list_size() << std::endl;
std::cout << "--------------------------------------------------------------------------\n" << std::endl;
}
This is the error I'm getting cannot bind rvalue reference of type ‘std::vector<int>&&’ to lvalue of type ‘std::vector<int>’
| In here:
void add_to_list(T&& data) {
std::cout << "\nbefore inside add_to_list: " << data.size() << std::endl;
data_list.push_back(std::forward<T>(data));
std::cout << "after inside add_to_list: " << data.size() << std::endl;
}
data isn't a forwarding reference, it's an rvalue reference, so you can't do something like list_of_data.add_to_list(data); because data is an lvalue.
To create a forwarding reference, the type must exist as a template parameter of the same function template (Give a reading to the forwarding references part of this cppreference.com page and look specifically at the first example):
function parameter of a function template declared as rvalue reference to cv-unqualified type template parameter of that same function template.
Basically, what you want to do is this:
// ...
template <typename U>
void add_to_list(U&& data) {
std::cout << "\nbefore inside add_to_list: " << data.size() << std::endl;
data_list.push_back(std::forward<U>(data));
std::cout << "after inside add_to_list: " << data.size() << std::endl;
}
// ...
Then data becomes a forwarding reference and does what is intended.
Demo
|
69,348,217 | 69,348,339 | How can I std::bind a user-provided function to a member variable of type std::function? | I have a class with a member variable std::function customCallback, and I need to let the user customize its behavior. customCallback should take as input a const std::array<int, N>& and a int, and return a std::array<int, N> (where N is a template parameter).
I am currently using std::bind to achieve this, but I can't understand why the compilation fails. What am I missing?
Since the original code involves inheritance and templates, I am including inheritance and templates in my minimal reproducible example (live code here) as well.
The user should be able to use both the constructor OR a member function to set the custom behavior.
base.h:
#include <array>
#include <functional>
template <std::size_t N>
class BaseClass {
public:
virtual std::array<int, N> CustomBehavior(const std::array<int, N>& user_array, int user_number) = 0;
protected:
std::array<int, N> my_array = {0, 0};
};
derived.h:
#include <base.h>
#include <cstddef>
template <std::size_t N>
class DerivedClass : public BaseClass<N> {
public:
DerivedClass() = default;
DerivedClass(std::function<std::array<int, N>(const std::array<int, N>&, int)> custom_f)
: customCallback(std::bind(custom_f, std::ref(std::placeholders::_1), std::placeholders::_2)) {}
void SetCustomBehavior(std::function<std::array<int, N>(const std::array<int>&, int)> custom_f) {
customCallback = std::bind(custom_f, std::ref(std::placeholders::_1), std::placeholders::_2);
}
std::array<int, N> CustomBehavior(const std::array<int, N>& user_array, int user_number) override {
if (customCallback)
this->my_array = customCallback(user_array, user_number);
return this->my_array;
}
private:
std::function<std::array<int, N>(const std::array<int, N>&, int)> customCallback;
};
main.cpp:
#include <derived.h>
#include <cassert>
static constexpr std::size_t MySize = 2;
std::array<int, MySize> my_behavior(const std::array<int, MySize>& input_array, int a) {
return {a * input_array[0], a * input_array[1]};
}
int main() {
std::array<int, MySize> my_array = {1, 1};
// Default constructor (COMPILES)
DerivedClass<MySize> foo_1; // OK
std::array<int, MySize> bar_1 = foo_1.CustomBehavior(my_array, 2);
assert(bar_1[0] == 0 && bar_1[1] == 0);
// Custom constructor (ERROR)
DerivedClass<MySize> foo_2(my_behavior); // COMPILATION ERROR
std::array<int, MySize> bar_2 = foo_2.CustomBehavior(my_array, 2);
assert(bar_2[0] == 2 && bar_2[1] == 2);
// Custom behavior set later on (ERROR)
DerivedClass<MySize> foo_3; // OK
foo_3.SetCustomBehavior(my_behavior); // COMPILATION ERROR
std::array<int, MySize> bar_3 = foo_3.CustomBehavior(my_array, 2);
assert(bar_3[0] == 2 && bar_3[1] == 2);
return 0;
}
I am not including the whole compilation error since it's fairly long, but it can be seen live code here.
| Well, for starters, the first error you are getting is an error on std::array<int> in Derived::SetCustomBehavior():
error: wrong number of template arguments (1, should be 2)
You also have an error on std::ref(std::placeholders::_1), it should be just std::placeholders::_1.
Fixing those two mistakes, the code then compiles and runs (using corrected asserts):
Online Demo
That being said, you don't actually need std::bind() at all in this situation. Your custom_f parameter is the same type as your customCallback member, so simply assign custom_f as-is to customCallback.
And do yourself a favor - create type aliases for your std::function and std::array types to make your code more readable.
Try this:
base.h
#include <array>
#include <functional>
#include <cstddef>
template<std::size_t N>
using intArray = std::array<int, N>;
template<std::size_t N>
using callbackType =
std::function<intArray<N>(const intArray<N>&, int)>;
template <std::size_t N>
class BaseClass {
public:
virtual intArray<N> CustomBehavior(const intArray<N>& user_array, int user_number) = 0;
protected:
intArray<N> my_array = {0, 0};
};
derived.h:
#include "base.h"
template <std::size_t N>
class DerivedClass : public BaseClass<N> {
public:
DerivedClass() = default;
DerivedClass(callbackType<N> custom_f)
: customCallback(std::move(custom_f))
{}
void SetCustomBehavior(callbackType<N> custom_f) {
customCallback = std::move(custom_f);
}
intArray<N> CustomBehavior(const intArray<N>& user_array, int user_number) override {
if (customCallback)
this->my_array = customCallback(user_array, user_number);
return this->my_array;
}
private:
callbackType<N> customCallback;
};
main.cpp:
#include "derived.h"
#include <cassert>
static constexpr std::size_t MySize = 2;
using myIntArray = intArray<MySize>;
myIntArray my_behavior(const myIntArray& input_array, int a) {
return {a * input_array[0], a * input_array[1]};
}
int main() {
myIntArray my_array = {1, 1};
// Default constructor
DerivedClass<MySize> foo_1;
myIntArray bar_1 = foo_1.CustomBehavior(my_array, 2);
assert(bar_1[0] == 0 && bar_1[1] == 0);
// Custom constructor
DerivedClass<MySize> foo_2(my_behavior);
myIntArray bar_2 = foo_2.CustomBehavior(my_array, 2);
assert(bar_2[0] == 2 && bar_2[1] == 2);
// Custom behavior set later on
DerivedClass<MySize> foo_3;
foo_3.SetCustomBehavior(my_behavior);
myIntArray bar_3 = foo_3.CustomBehavior(my_array, 2);
assert(bar_3[0] == 2 && bar_3[1] == 2);
return 0;
}
Online Demo
|
69,348,731 | 69,359,676 | Parallel vs Sequential naïve quick sort | I am trying to implement quicksort which runs partition sorting in parallel as given below:
// Returns patition points as pair
template<typename ExPo, std::random_access_iterator I, std::sentinel_for<I> S,
class Comp = std::ranges::less, class Proj = std::identity >
requires std::sortable<I, Comp, Proj>
std::pair<I, I> parition_points(ExPo policy, I first, S last, Comp comp = {}, Proj proj = {})
{
auto val = *std::next(first, std::distance(first, last) / 2);
auto mid1 = std::partition(policy, first, last, [&](const auto& cur) { return std::invoke(comp, std::invoke(proj, cur), std::invoke(proj, val)); }); // a < b
auto mid2 = std::partition(policy, mid1, last, [&](const auto& cur) { return !std::invoke(comp, std::invoke(proj, val), std::invoke(proj, cur)); }); // !(b < a)-> b >=a
return { mid1, mid2 };
}
// Quick sort
template<typename ExPo, std::random_access_iterator I, std::sentinel_for<I> S,
class Comp = std::ranges::less, class Proj = std::identity >
requires std::sortable<I, Comp, Proj>
void quicksort(ExPo policy, I first, S last, Comp comp = {}, Proj proj = {})
{
if (first == last) return;
const auto& [mid1, mid2] = parition_points(policy, first, last, std::ref(comp), std::ref(proj));
quicksort(policy, first, mid1, std::ref(comp), std::ref(proj));
quicksort(policy, mid2, last, std::ref(comp), std::ref(proj));
}
int main()
{
auto rv1 = getRandomVector(100000);
auto rv2 = rv1;
auto rv3 = rv1;
// std::sort parallel
auto sort1 = [&rv1]() { std::sort(std::execution::par, rv1.begin(), rv1.end());};
execute(sort1);
// quicksort in parallel
auto sort2 = [&rv2]() {quicksort(std::execution::par, rv2.begin(), rv2.end()); };
execute(sort2);
// quicksort in sequential
auto sort3 = [&rv3]() {quicksort(std::execution::seq, rv3.begin(), rv3.end()); };
execute(sort3);
return 0;
}
Here is godbolt compiler explorer link to my example.
I was expecting better performance when calling std::partition with parallel execution policy but instead it was more or less similar or in some cases worse.
What am I doing wrong?
| First, you cannot use godbolt to demonstrate speedup (or slowdown) due to parallelism. Last time I checked, the service was giving each program one hardware thread.
Second, by default gcc does not do any parallelisation. There are two parallelism backends there, and the one that is used by default is called, surprisingly, "serial backend". The one that does real parallelisation is called "TBB backend" and you need to have Intel TBB library installed in order to use it.
Last but not least, this particular implementation of "parallel quicksort" is no good at all. It only tries to run std::partition in parallel, which doesn't do much, if anything. A real parallel quicksort will run the two recursive calls to quicksort in parallel, and of course it would not create any more threads than the hardware can support, because it's just pure overhead with zero gain.
I was able to quickly-and-dirty tweak your code such that the parallel version is actually faster. This involves something like
static std::atomic<int> tc = 1;
if (!std::is_same_v<ExPo,std::execution::parallel_policy> || last-first<32 || tc >= 8)
{
const auto& [mid1, mid2] = parition_points(std::execution::seq, first, last, std::ref(comp), std::ref(proj));
quicksort(std::execution::seq, first, mid1, std::ref(comp), std::ref(proj));
quicksort(std::execution::seq, mid2, last, std::ref(comp), std::ref(proj));
}
else
{
++tc;
const auto& [mid1, mid2] = parition_points(policy, first, last, std::ref(comp), std::ref(proj));
auto fut = std::async(std::launch::async, [&](){quicksort(policy, first, mid1, std::ref(comp), std::ref(proj));});
quicksort(policy, mid2, last, std::ref(comp), std::ref(proj));
fut.wait();
--tc;
}
The performance is still quite abysmal but some gain from parallelism can be demonstrated.
|
69,348,894 | 69,349,704 | Remove Pair from TJsonObject | {
"Test":{
"A":{
"ins":{
"type":"pac",
"id":{
"values":{
"test_number":"156764589",
"val":"abcde",
"val_2":"gggg",
"val_3":"jjjj"
},
"verif":{
},
"bool":"INSTR"
}
}
},
"resp":{
"image":"include"
},
"op":{
"id":{
"meth":"def"
}
}
}
}
I am logging a http request been sent & need to remove an element from a TJsonObject for privacy. However when I attempt to remove key and log it still persists
TJSONObject *obj = (TJSONObject*) TJSONObject::ParseJSONValue(TEncoding::UTF8->GetString(id_http_wrap.msg));
obj->RemovePair("Test.A.ins.type.id.values.test_number");
| First, your path is wrong. type is not in the path down to test_number. The correct one would have been:
obj->RemovePair("Test.A.ins.id.values.test_number");
But as far as I know, that can't be parsed by RemovePair. You'll have to use FindValue:
// Cast helper:
TJSONObject* ToTJSONObject(TJSONValue* v) {
auto obj = dynamic_cast<TJSONObject*>(v);
if(!obj) throw Exception("v is not a TJSONObject");
return obj;
}
auto obj = ToTJSONObject(TJSONObject::ParseJSONValue(...));
TJSONPair* removed =
ToTJSONObject(obj->FindValue("Test.A.ins.id.values"))->RemovePair("test_number");
if(removed) {
// successfully removed: removed->ToString()
// the resulting JSON document: obj->ToString()
}
|
69,348,948 | 69,350,424 | Absolute Value of the DFT with OpenCV in C++ | I am trying to compute the DFT in C++ with OpenCV. I want the absolute value of the DFT. To compute it I do:
vector<float> areas, X_mag;
cv::Mat X;
...
cv::dft(areas, X, cv::DFT_COMPLEX_OUTPUT);
areas is a 50x1 vector, and I want to store the absolute value of the DFT of areas in X_mag
The problem, is that I think there is no way to compute directly the absolute value, and I didn't find any function that computes directly the absolute.
I tried to use absdiff: cv::absdiff(X, cv::Scalar::all(0), X_mag);, but it only works if I use a std::vector instead of the cv::Mat.
If I don't use the DFT_COMPLEX_OUTPUT, I get only the real part, so is not what I need.
I was thinking on computing manually the absolute value (sqrt(Re(X)^2 + Im(X)^2), but I think it would be too slow, and I don't think that cv::Mat was thought to be iterated this way.
How could I get my 50x1 DFT's absolute value vector?
| As @Christoph Rackwitz said, we can use split and magnitude.
vector<float> areas, X_abs;
Mat X;
Mat X_mag[2];
...
cv::dft(areas, X, cv::DFT_COMPLEX_OUTPUT);
cv::split(X, X_mag);
cv::magnitude(X_mag[0], X_mag[1], X_abs);
And we will have the absolute value vector in X_abs.
|
69,350,094 | 69,350,136 | The type returned by 'operator|' does not always match the type you passed it | Some code called a templated function, but it did not call the specialisation I expected. Turned out the culprit was this: I or-ed some uint16_t constants and passed them as an argument like this: foo(uint16_bar | uint16_baz);. My expectation was it would call the foo<uint16_t>, but it did not. I can easily evade the problem with a cast, but I really wonder what the reason for this might be. Especially since not every integral type you pass it will return type int.
Case 1:
uint16_t a = 2;
uint16_t b = 4;
auto x = (a|b); // x is of type 'int': Surprize!
Case 2:
uint a = 2;
uint b = 4;
auto x = (a|b); // x is of type unsigned_int: What I would expect
Why does (a|b) in case 1 not return a value of type uint16_t ?
| The usual arithmetic conversions are applied to operands of the bitwise operator |. That means that integer objects of types with rank less than the rank of the type int are converted either to int or unsigned int due to the integral promotions that are a part of the usual arithmetic conversions..
From the C++ 14 Standard ( 5.13 Bitwise inclusive OR operator)
1 The usual arithmetic conversions are performed; the result is the
bitwise inclusive OR function of its operands. The operator applies
only to integral or unscoped enumeration operands.
and (4.5 Integral promotions)
1 A prvalue of an integer type other than bool, char16_t, char32_t, or
wchar_t whose integer conversion rank (4.13) is less than the rank of
int can be converted to a prvalue of type int if int can represent all
the values of the source type; otherwise, the source prvalue can be
converted to a prvalue of type unsigned int
|
69,350,142 | 69,351,942 | Using unique_ptr with an interface requiring pointer-pointer, to an abstract class | I'm using RocksDB which requires a pointer to a pointer to open:
rocksdb::DB* db{nullptr};
const rocksdb::Status status = rocksdb::DB::Open(options, path, &db);
As expected, I'd like to use a unique_ptr. However, unfortunately if I do this:
std::unique_ptr<rocksdb::DB> db;
const rocksdb::Status status = rocksdb::DB::Open(options, fileFullPath, &(db.get()));
I get:
error: lvalue required as unary ‘&’ operand
and if I use a raw pointer and then create a unique_ptr:
std::unique_ptr<rocksdb::DB> _db; // Class member
rocksdb::DB* db;
const rocksdb::Status status = rocksdb::DB::Open(options, fileFullPath, &db));
_db = std::make_unique<rocksdb::DB>(db);
I get:
error: invalid new-expression of abstract class type ‘rocksdb::DB’
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
How can I use unique_ptr with this?
| Using a raw pointer to accept the value from Open() is the correct solution, since that is what the function is expecting.
However, the way you are creating the unique_ptr afterwards is not correct.
Use this instead:
std::unique_ptr<rocksdb::DB> _db; // Class member
...
rocksdb::DB* db;
const rocksdb::Status status = rocksdb::DB::Open(options, fileFullPath, &db);
_db = std::unique_ptr<rocksdb::DB>(db);
Online Demo
Alternatively:
std::unique_ptr<rocksdb::DB> _db; // Class member
...
rocksdb::DB* db;
const rocksdb::Status status = rocksdb::DB::Open(options, fileFullPath, &db);
_db.reset(db);
Online Demo
std::make_unique() creates a new object of the specified type, and then wraps the raw pointer inside of a new std::unique_ptr.
On the other hand, unique_ptr::operator= and unique_ptr::reset() merely update an existing std::unique_ptr with a new raw pointer (destroying the object pointed by the old raw pointer that is being replaced).
Since rocksdb::DB is an abstract type, you can't directly create instances of it, which is why your std::make_unique() calls fails to compile. But even if you could create DB objects directly, std::make_unique<rocksdb::DB>(db) would be passing db as a parameter to the rocksdb::DB constructor, which is not what you want in this situation anyway. You just want the _db smart pointer to take ownership of the db raw pointer.
|
69,350,818 | 69,367,814 | How to add noexcept specifier to already defined function type? | For example I have type:
typedef DWORD WINAPI HANDLER_FUNCTION_EX (DWORD);
And I want:
static as_noexcept<HANDLER_FUNCTION_EX>::type my_func; // forward declaration
static_assert(noexcept(my_func(0)));
I got something like:
template<typename>
struct noexcept_trait;
// specialization to infer signature
template<typename Result, typename... Args>
struct noexcept_trait<Result(Args...)>
{
using as_noexcept = Result(Args...) noexcept;
using as_throwing = Result(Args...);
};
// since C++17 noexcept-specification is a part of the function type
// so first specialization won't match
template<typename Result, typename... Args>
struct noexcept_trait<Result(Args...) noexcept>
{
using as_noexcept = Result(Args...) noexcept;
using as_throwing = Result(Args...);
};
template<typename T>
using add_noexcept_t = typename noexcept_trait<T>::as_noexcept;
template<typename T>
using remove_noexcept_t = typename noexcept_trait<T>::as_throwing;
But this code creates totally new type and drops all additional info (calling convention, attributes e.g. [[deprecated]]). So it's not safe. How can I fix it?
| Add
template<typename Result, typename... Args>
struct noexcept_trait<Result __stdcall(Args...)>
{
using as_noexcept = Result __stdcall(Args...) noexcept;
using as_throwing = Result __stdcall(Args...);
};
and similar elsewhere. But you should only do this if !is_same_v< void(*)(), void(__stdcall *)() >. If __stdcall does nothing on your platform, you'll get a conflict here.
Attributes are explicitly not part of the type system. [[deprecated]] applies to the type definition itself, not the thing being defined. The very use of that type to create the alias is [[deprecated]].
|
69,350,834 | 69,350,935 | C++ Templates - The Complete Guide: Understanding footnote comment about decltype and return type | The 2nd edition of C++ Templates - The Complete Guide features the following code at page 435
#include <string>
#include <type_traits>
template<typename T, typename = void>
struct HasBeginT : std::false_type {};
template<typename T>
struct HasBeginT<T, std::void_t<decltype(std::declval<T>().begin())>>
: std::true_type {};
and comments that decltype(std::declval<T>().begin()) is used to test whether it is valid to call .begin() on a T.
This all makes sense, I think...
What staggers me is the comment in the footnote:
Except that decltype(call-expression) does not require a nonreference, non-void return type to be complete, unlike call expressions in other contexts. Using decltype(std::declval<T>().begin(), 0) instead does add the requirement that the return type of the call is complete, because the returned value is no longer the result of the decltype operand.
I don't really understand it.
In an attempt to play with it, I tried to see what it behaves with a void member begin, with the following code
struct A {
void begin() const;
};
struct B {
};
static_assert(HasBeginT<A>::value, "");
static_assert(!HasBeginT<B>::value, "");
but both assertions pass with or without the , 0.
| Your demo uses void begin() const; to test the following
... instead does add the requirement that the return type of the call is complete ...
But a void return type is not the same as an incomplete return type. For that you could try
struct X;
struct A {
X begin() const;
};
Here, X is indeed incomplete, and now the , 0 matters. With it, the first static_assert won't pass, but it passes without the , 0.
demo
|
69,351,000 | 69,353,899 | C++ I don't want to ignore white spaces in folder paths (MAC) how can I do that? | I am currently working on a project which runs pretty well, and I get a file path from the user, if the path has no white spaces it works pretty well! but if it includes white spaces the system ignores and doesn't continue reading the path. For Ex; if the path says Desktop/School Projects/C++
System reads only the Desktop/School part and ignores the rest of it. how can I fix that!
I am pretty sure its because I used char directory[256]; instead of string directory; to get the path, but string doesn't work for the rest of the code because system(command); function works only with const char* and if I even use string var it translates string to char! so I donno what to do right now. I cant just ask user to create folders without spaces...
| Use getline(cin, directory); instead of cin >> directory; in order to store more than one words in a string, and don't forget to use cin.ignore(); before getline.
|
69,351,083 | 69,351,665 | Understanding User-Defined Conversions for Unrelated Types | I have a class, UDataChunk, which is a wrapper class for all my data types (actor info like location, stats, etc).UDataChunk holds a Value() method which is hidden by derived classes in order to return the type they hold (as the data types they hold can vary, I believe that means I shouldn't use a template on UDataChunk?).
I have an interface, IDataMapInterface, which is applied to any class which can hold a Map<TSubclassOf<UDataChunk>, UDataChunk*>(in Unreal Engine, I believe TSubclassOf is the equivalent of std::is_base_of). The template method here is TObjectPtr<T> DataChunk().
Currently, in order to get the proper data I need, I call DataChunk<DataChunkDerivedClass>()->Value() which is the hidden method that returns the proper data type I actually want to use (such as an actor pointer, int, vector, etc).
I'm in the middle of refactoring, and was wondering if I could do an operator overload which converts the TObjectPtr<T> DataChunk() implicitly to the value type it holds?
class USenseComponent;
UCLASS(BlueprintType, EditInlineNew)
class USenseComponentChunk : public UActorComponentChunk
{
GENERATED_BODY()
public:
USenseComponentChunk()
{
}
TObjectPtr<USenseComponent> Value() const { return Cast<USenseComponent>(component.Get()); } //Component is a UActorComponent*, which USenseComponent derives from
operator TObjectPtr<USenseComponent>() const { return Cast<USenseComponent>(component.Get()); } //Component is a UActorComponent*, which USenseComponent derives from
operator USenseComponent*() const { return Cast<USenseComponent>(component.Get()); }
};
As I understand it, USenseComponentChunk* should be implicitly converted in a situation like TObjectPtr<USenseComponent> comp = DataChunk<USenseComponentChunk>();, yet I receive an error:
No User-Defined Conversion
I also experimented to try and further grasp user-defined conversions by USenseComponent* comp = DataChunk<USenseComponentChunk>().Get(), where .Get() returns USenseComponentChunk*, and this results in an error:
A Value of type USenseComponentChunk* cannot be used to initialize Type USenseComponent*
So, what am I misunderstanding, or missing entirely?
| In the first case, you are trying to assign a TObjectPtr<USenseComponentChunk> object to a TObjectPtr<USenseComponent> object. Your conversion operator for that purpose is implemented in USenseComponentChunk, not in TObjectPtr. So, unless TObjectPtr<T> uses CRTP to derive from T, the compiler is correct to fail the conversion.
In the second case, you are trying to assign a pointer type USenseComponentChunk* to an unrelated pointer type USenseComponent*. So the compiler is correct to fail this conversion, too. Since conversion operators apply to objects, not pointers, you would have to dereference the USenseComponentChunk* pointer in order for the compiler to invoke the USenseComponent* conversion operator on the USenseComponentChunk object, eg:
USenseComponent* comp = *(DataChunk<USenseComponentChunk>().Get());
|
69,351,180 | 69,351,260 | "/usr/bin/ld: cannot find -llibopencv_calib3d" when compiling an opencv project in Ubuntu 20.04 | I have installed opencv in Ubuntu 20.04 following the instructions in OpenCV Installation in Linux. As per the instructions, sudo make install copies all the .so files to /usr/local/lib.
However, when compiling a program, using the command g++ --std c++17 -g opencv/Basic.cpp -o output -I/usr/local/include/opencv4 -L/usr/local/lib/ -llibopencv_calib3d -llibopencv_core -llibopencv_dnn -llibopencv_features2d -llibopencv_flann -llibopencv_highgui -llibopencv_imgcodecs -llibopencv_imgproc -llibopencv_ml -llibopencv_objdetect -llibopencv_photo -llibopencv_stitching -llibopencv_video -llibopencv_videoio I get the following error.
/usr/bin/ld: cannot find -llibopencv_calib3d
/usr/bin/ld: cannot find -llibopencv_core
/usr/bin/ld: cannot find -llibopencv_dnn
/usr/bin/ld: cannot find -llibopencv_features2d
/usr/bin/ld: cannot find -llibopencv_flann
/usr/bin/ld: cannot find -llibopencv_highgui
/usr/bin/ld: cannot find -llibopencv_imgcodecs
/usr/bin/ld: cannot find -llibopencv_imgproc
/usr/bin/ld: cannot find -llibopencv_ml
/usr/bin/ld: cannot find -llibopencv_objdetect
/usr/bin/ld: cannot find -llibopencv_photo
/usr/bin/ld: cannot find -llibopencv_stitching
/usr/bin/ld: cannot find -llibopencv_video
/usr/bin/ld: cannot find -llibopencv_videoio
collect2: error: ld returned 1 exit status
I have also added a .conf file in /etc/ld.so.conf.d/opencv.conf with the line /usr/local/lib/ and issued the command sudo ldconfig. However, the issue remains.
I'd be grateful for any ideas or suggestions to resolve this issue.
|
-llibopencv_calib3d
make it
-lopencv_calib3d
etc. the lib part in front of it is simply wrong
|
69,351,364 | 69,351,900 | How to get validate result Qt? | For quick skip the gui code, and go straight to method validate, i dont know, next step to get validate result when login button click. full code in here https://pastecode.io/s/ut3cuq3p
class MainWindow: public QWidget
{
Q_OBJECT
public:
MainWindow(){ ... }
public slots:
void validate(QLineEdit* pUserInput)
{
QRegularExpression rx("^[^_\\W]+$");
QValidator* validator = new QRegularExpressionValidator(rx, this);
pUserInput->setValidator(validator);
// what property to get the validate result?
// i need to pass to QMessageBox
QMessageBox message;
message.setText(validateResult);
message.exec();
}
}
| When using a validator on a QLineEdit, you want to look at the value of pUserInput->hasAcceptableInput() but you can set it up better. You only need to assign the validator to your QLineEdit when it is created (unless your validation regex is changing every time), then you can use the signals QLineEdit::editingFinished and QLineEdit::inputRejected to determine whether the user's input was acceptable - see QLineEdit documentation
MainWindow::MainWindow()
{
...
QValidator* validator = new QRegularExpressionValidator(rx, this);
pUserInput->setValidator(validator);
connect(pUserInput, &QLineEdit::editingFinished, this, &MainWindow::validText);
connect(pUserInput, &QLineEdit::inputRejected, this, &MainWindow::invalidText);
...
}
void MainWindow::validText()
{
// pUserInput has valid input text
...
}
void MainWindow::invalidText()
{
// pUserInput has invalid input text
...
}
|
69,351,650 | 69,352,997 | C++ erasing section of vector with a size_t as start point | I want to erase a section of a std::vector e.g ith element through end. Where i is a std::size_t that is calculated beforehand.
auto i = vec.size();
for (auto pos = vec.size(); pos > 0; --pos) {
auto& elem = vec.at(pos - 1);
if (*magic_condition*) {
--i;
}
}
vec.erase(vec.begin() + i, vec.end());
I get a Conversion may change the sign of the result warning
I tried using std::next but that still results in the same warning
The only why I found that gets rid of the warning, but I think is very unelegant is
const auto begin = typename decltype(vec)::const_iterator{vec.data() + i};
vec.erase(begin, vec.end());
Is there any good solution to get rid if this warning?
EDIT:
void update(const delta_type delta) {
auto size = handlers.size();
for(auto itr = handlers.rbegin(); itr != handlers.rend(); ++itr) {
auto& handler = *itr;
if(const auto dead = handler.update(handler, delta); dead) {
std::swap(handler, handlers.at(--size));
}
}
handlers.erase(handlers.begin() + size, handlers.end());
}
Results in following error
../ecs/scheduler.hpp: In instantiation of ‘void sbx::scheduler<Delta>::update(sbx::scheduler<Delta>::delta_type) [with Delta = float; sbx::scheduler<Delta>::delta_type = float]’:
/home/kabelitzj/Dev/sandbox/sandbox/core/engine.cpp:39:29: required from here
../ecs/scheduler.hpp:64:39: warning: conversion to ‘__gnu_cxx::__normal_iterator<sbx::scheduler<float>::process_handler*, std::vector<sbx::scheduler<float>::process_handler, std::allocator<sbx::scheduler<float>::process_handler> > >::difference_type’ {aka ‘long int’} from ‘long unsigned int’ may change the sign of the result [-Wsign-conversion]
64 | handlers.erase(handlers.begin() + size, handlers.end());
|
Compiled with g++ version 9.3.0 and c++17
| The code shown is perfectly fine, AFAICS. The warning implies that the vector's implementation is in the wrong, not you. A vector::iterator can be incremented by an index, and your index variable is the same type that vector uses for its indexes. So there should be no conversion. But there is, because the difference_type of the iterator is not the same type as the size_type of the vector.
In any case, this kind of code is unnecessary anyway. You could just use the Erase-Remove idiom via std::remove_if()+vector::erase(), or std::erase_if() in C++20. Then there would be no need to handle these kinds of loops and swaps manually at all. For example:
vec.erase(
std::remove_if(vec.begin, vec.end(),
[](auto &elem){ return *magic_condition*; }
),
vec.end()
);
std::erase_if(vec, [](auto &elem){ return *magic_condition*; });
void update(const delta_type delta) {
handlers.erase(
std::remove_if(handlers.begin(), handlers.end(),
[&](auto &handler){ return (bool) handler.update(handler, delta); }
),
handlers.end()
);
}
void update(const delta_type delta) {
std::erase_if(handlers, [&](auto &handler){ return (bool) handler.update(handler, delta); });
}
|
69,351,795 | 69,470,453 | DLL's dependency cannot be found when DLL moved to another location | I'm on Windows 10, Visual Studio 2017, x64 build . . .
I have a DLL that I'm using in an exe project. We'll call it, myLibrary.dll. It comes with a .lib companion file as well. The myLibrary.dll has some other DLL dependencies that it is using. We'll call that one theDependency.dll.
I've linked the companion myLibrary.lib file in my project through Linker --> General --> Additional Library Dependencies properties. Added myLibrary.lib to the Additional Dependencies.
When I build my project, I use post build event to copy the myLibrary.dll to the Release/Debug directory of my project.
This works fine.
My issue is when I try to use myLibrary.dll in a different exe project. I get an error that it cannot find the theDependency.dll. I've used all the same property setup as the first exe project. As a test, I moved the build directory of the first exe project to another location (on the same computer) and I get the same error. "Cannot find theDependency.dll"
How is myLibrary.dll targeting it's dependencies? Not sure why the 2nd project gets this error? Also, not sure why moving the files gets this error?
Any ideas? Thanks.
| Adding the path of the dll to the PATH environment variable worked for me.
|
69,352,240 | 69,352,477 | What should I send after STARTLS? | I am using smtp.gmail.com and port 587. After a successful connection, I send EHLO and receive the following:
250-smtp.gmail.com at your service, [62.16.4.123]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF
I choose STARTTLS and after that, I don't know what to send to the server and to login and send email.
If I will send something like AUTH LOGIN or base64-encrypted login with password, the connection is broken.
Can someone explain what my client should send to successfully finish the STARTTLS negotiation?
Or, should I start over with a new SSL connection?
| After you send an (unencrypted) STARTTLS command, if the server returns any reply other than 220, handle it has a failure and move on with other SMTP commands as needed (though, at this point, the only one that really makes sense is QUIT).
If the server returns 220 to STARTTLS, you then need to perform the actual TLS handshake over the existing TCP connection, starting with a TLS CLIENT HELLO. Whatever TLS library you are using with your socket should be able to handle this for you, do not implement this from scratch.
If the TLS handshake is successful, then you can send further SMTP commands (through the TLS-encrypted channel), starting with a new EHLO (as the server's capabilities may and likely will change, most notably the available AUTH schemes), then followed by AUTH, MAIL FROM, RCPT TO, DATA/BDAT, etc and finally QUIT, as needed.
If the TLS handshake fails, the TCP connection is left in an unknown state, so further SMTP communication is not possible. All you can do at that point is close the TCP connection and start over.
|
69,352,249 | 69,352,327 | To remove the Duplicates from the given string (without sorting it) | The question is asking to remove duplicates from the string, I came up with a solution to remove duplicates but for that, I sorted the string.
So I wanted to know is there a way of removing duplicates from a string without sorting the string.
Test Cases :
"allcbcd" -> "alcbd"
My Code (the one in which string has to be sorted) :
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeDup(string s)
{
if (s.length() == 0)
{
return "";
}
sort(s.begin(), s.end());
char ch = s[0];
string ans = removeDup(s.substr(1));
if (ch == ans[0])
{
return ans;
}
return (ch + ans);
}
int main()
{
cout << removeDup("allcbbcd") << endl;
return 0;
}
| Here is one way to do it without sorting (or using a recursive loop):
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string removeDup(string s)
{
string::size_type index = 0;
string::iterator end = s.end();
while (index < s.size()) {
end = remove(s.begin()+index+1, end, s[index]);
++index;
}
s.erase(end, s.end());
return s;
}
int main()
{
cout << removeDup("allcbbcd") << endl;
return 0;
}
Online Demo
|
69,352,573 | 69,353,345 | cpp-httplib https server not working on Linux | I am trying to create a HTTPS Server running on linux with cpp-httplib in C++. (https://github.com/yhirose/cpp-httplib)
Everything worked when I used Windows. But on linux only the HTTP Server works.
It seems like the HTTPS Server does not open a port which I do not understand...
When typing: sudo netstat -tuplen in Terminal the expected port 8080 only shows up when running the HTTP Server not when running the HTTPS Server.
My firewall also seems to be inactive: sudo ufw status gives Status: inactive
Maybe I have linked something wrong, but everything seems to run fine.
I am new to C++ and Linux, so it is likely I have just made a silly mistake.
I just run this code in Clion if that matters..
this is the Code for the HTTP Server (working and running as expected):
#include <iostream>
#include "./httplib.h"
int main(void) {
httplib::Server svr;
svr.Get("/hi", [](const auto&, auto& res) {
res.set_content("This is a test response", "text/plain");
});
std::cout << "start server..." << std::endl;
svr.listen("192.158.1.38", 8080);
std::cin.get();
}
this is the Code for the HTTPS Server (running but not opening a port):
#pragma comment (lib, "crypt32")
#define CPPHTTPLIB_OPENSSL_SUPPORT
#include <iostream>
#include "./httplib.h"
// These are shown by Clion that they are not used...
#include </usr/include/openssl/conf.h>
#include </usr/include/openssl/evp.h>
#include </usr/include/openssl/err.h>
int main(void) {
/// behind svr there have to be keys can not be self signed keys like in
httplib::SSLServer svr("./keys/localhost.crt", "./keys/localhost.key");
svr.Get("/hi", [](const auto&, auto& res) {
res.set_header("Access-Control-Allow-Origin", "*");
res.set_content("This is a test response", "text/plain");
});
std::cout << "start server..." << std::endl;
svr.listen("192.158.1.38", 8080);
std::cin.get();
}
My CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.20)
project(TLS_Server)
set(CMAKE_CXX_STANDARD 17)
add_executable(TLS_Server main.cpp)
find_package(OpenSSL REQUIRED)
find_package(Threads REQUIRED)
target_link_libraries(TLS_Server PRIVATE OpenSSL::SSL PRIVATE Threads::Threads)
| Ok as mentioned in the comments the problem was that the certs could not be found. I have given the absolute path for now and it works fine.
Thanks!
PS: As I said: "probably a silly mistake"..
|
69,353,433 | 69,353,527 | How do I multiply vector integers | so basically I want to multiply a vector by 60 from seconds to minutes and hours 3 times using a for loop. I also want to add 3 more values inside that vector that should store a value 60 times greater than the last integer before it.
This is what I have come up so far but it only prints out 2 times so what am I doing wrong?
#include <iostream>
#include <vector>
int main() {
std::vector <int> seconds = { 1 };
for (int i = 0; i <= 3; i++) {
i = seconds.at(i) * 60;
seconds.push_back(i);
}
for (int i = 0; i < seconds.size(); i++) {
std::cout << seconds[i] << std::endl;
}
return 0;
}
| This for loop iterates exactly once.
std::vector <int> seconds = { 1 };
for (int i = 0; i <= 3; i++) {
i = seconds.at(i) * 60;
seconds.push_back(i);
}
i is set to 60, and the loop condition i <= 3 then fails.
Use a different variable to hold this value.
std::vector <int> seconds = { 1 };
for (int i = 0; i <= 3; i++) {
auto x = seconds.at(i) * 60;
seconds.push_back(x);
}
Or don't use a variable at all.
std::vector <int> seconds = { 1 };
for (int i = 0; i <= 3; i++) {
seconds.push_back( seconds.at(i) * 60 );
}
|
69,353,505 | 69,353,758 | Doubly linked list not taking input after calling a delete function | Greetings stack overflow. My program is supposed to take a user inputted line of characters and append them to a list. The program is also supposed to delete the most recent character appended if a hashtag is read in the input.
My program mostly works, but I run into errors when I try to break it by adding too many hashtags. Upon doing this the list stops accepting appends will display nothing if one too many hashtags are used.
I hope I only included what I thought was useful code, sorry if the main function was not necessary.
#include <iostream>
using namespace std;
class doubleList
{
public:
doubleList() { first = NULL; } // constructor
void append(char); // adds entry to the end of the list
void remove_last(); // removes the last item from a list
friend ostream& operator<<(ostream& out, const doubleList& l); // outputs in forward order
private:
struct Node
{
char data;
Node *next;
Node *prev;
};
Node *first;
Node *last;
};
void doubleList::append(char entry)
{
Node* temp = new Node();
temp -> data = entry;
temp -> next = NULL;
if (first == NULL)
{
first = temp;
last = temp;
}
else
{
last -> next = temp;
temp -> prev = last;
last = temp;
}
}
void doubleList::remove_last()
{
if (first -> next == NULL)
{
delete first;
}
else if (first != NULL)
{
last = last -> prev;
delete last -> next;
last -> next = NULL;
}
}
ostream& operator<<(ostream& out, const doubleList& l)
{
doubleList::Node* q;
q = l.first;
while (q != NULL)
{
out << q -> data;
q = q -> next;
}
return out;
}
int main()
{
doubleList list;
char ch[100];
cout << "Enter a line of characters; # will delete the most recent character." << endl;
for (int i = 0; i < 100; i++)
{
cin.get(ch[i]);
list.append(ch[i]);
if (ch[i] == '#')
{
list.remove_last();
list.remove_last(); // called twice becaue it removes the hashtag from the list
} // and i was too lazy to make it so it doesnt do that so this
// is simply an easier fix
if (ch[i] == '\n') // exits the loop when enter is clicked
break;
}
cout << list;
return 0;
}
A successful run of my program would look like:
Enter a line of characters; # will delete the most recent character.
abcd##fg
abfg
My program when too many hashtags are added:
Enter a line of characters; # will delete the most recent character.
ab#####efgh
Nothing is shown after user input is taken. Thanks in advance.
| You should also set the pointer last to nullptr in the constructor
doubleList() { first = nullptr; last = nullptr; }
The function append is incorrect because it does not set the data member prev of the first node appended to the list. It should be written like
void doubleList::append(char entry)
{
Node* temp = new Node();
temp -> data = entry;
temp -> next = nullptr;
temp -> prev = last;
if (first == NULL)
{
first = temp;
}
else
{
last -> next = temp;
}
last = temp;
}
The function removeList can invoke undefined behavior because in the very beginning of the function it does not check whether the pointer first is equal to nullptr. And after deleting the node pointed to by the pointer first it does not set the pointers first and last to nullptr. The function can be defined the following way.
void doubleList::remove_last()
{
if ( last )
{
Node *tmp = last;
last = last->prev;
if ( last != nullptr )
{
last->next = nullptr;
}
else
{
first = nullptr;
}
delete temp;
}
}
|
69,353,507 | 69,359,725 | choose a constexpr based on a runtime value and use it inside a hot loop | I need to traverse a vector, read each element, and map to the modulo division value. Modulo division is fast for divisors of power2. So, I need to choose between a mod and mod_power2 during the runtime. Following is a rough outline. Please assume that I am using templates to visit the vector.
Bit manipulation tricks were taken from https://graphics.stanford.edu/~seander/bithacks.html
static inline constexpr bool if_power2(int v) {
return v && !(v & (v - 1));
}
static inline constexpr int mod_power2(int val, int num_partitions) {
return val & (num_partitions - 1);
}
static inline constexpr int mod(int val, int num_partitions) {
return val % num_partitions;
}
template<typename Func>
void visit(const std::vector<int> &data, Func &&func) {
for (size_t i = 0; i < data.size(); i++) {
func(i, data[i]);
}
}
void run1(const std::vector<int> &v1, int num_partitions, std::vector<int> &v2) {
if (if_power2(num_partitions)) {
visit(v1,
[&](size_t i, int v) {
v2[i] = mod_power2(v, num_partitions);
});
} else {
visit(v1,
[&](size_t i, int v) {
v2[i] = mod(v, num_partitions);
});
}
}
void run2(const std::vector<int> &v1, int num_partitions, std::vector<int> &v2) {
const auto part = if_power2(num_partitions) ? mod_power2 : mod;
visit(v1, [&](size_t i, int v) {
v2[i] = part(v, num_partitions);
});
}
My question is, run1 vs run2. I prefer run2 because it is easy to read and no code duplication. But when when I check both in godbolt (https://godbolt.org/z/3ov59rb5s), AFAIU, run1 is inlined better than run2.
So, is there a better way to write a run function without compromising on the perf?
FOLLOW UP:
I ran a quickbench on this.
https://quick-bench.com/q/zO5YJtDMbnd10pk53SauOT6Bu0g
It looks like for clang, there's no difference. But for GCC (10.3) there's a 2x perf gain for run1.
| "Issue" with cond ? mod_power2 : mod is that it is a function pointer, which is harder to inline.
Different lambdas have no common type. Using type-erasure such as std::function has overhead, and devirtualization is even harder to optimize.
So, only option I see is to be able to write run1 in a "nicer" way:
Factorize the creation of the lambda; you need to turn mod/mod_power2 into functors (else we have same issue than run2 Demo):
void run3(const std::vector<int> &v1, int num_partitions, std::vector<int> &v2) {
auto make_lambda = [&](auto&& f){
return [&](std::size_t i, int v){ v2[i] = f(v, num_partitions); };
};
if (if_power2(num_partitions)) {
visit(v1, make_lambda(mod_power2));
} else {
visit(v1, make_lambda(mod));
}
}
Demo
If you cannot change mod/mod_power2 into functors, then create a functor instead of the lambda to got their address at compile time:
template <int (*f)(int val, int num_partitions)>
struct Functor
{
std::vector<int> &v2;
int num_partitions;
void operator ()(size_t i, int v) const
{
v2[i] = f(v, num_partitions);
}
};
void run4(const std::vector<int> &v1, int num_partitions, std::vector<int> &v2) {
if (if_power2(num_partitions)) {
visit(v1, Functor<mod_power2>{v2, num_partitions});
} else {
visit(v1, Functor<mod>{v2, num_partitions});
}
}
Demo
|
69,353,512 | 69,353,817 | How can I dynamically pick a member from two similar C++ structures while avoiding code duplication? | Having the following structures:
class XY
{
private:
int test;
};
class XYZ
{
private:
short extra;
int test;
};
I want to use XY::test and XYZ::test depending on a runtime variable. Like:
if (x == 1)
{
reinterpret_cast<XY*>(object)->test = 1;
}
else if (x == 2)
{
reinterpret_cast<XYZ*>(object)->test = 1;
}
Is it possible to make this into a nice one-liner? (using templates, macros, etc...?)
What should I do about &object->test depending on a different type of object? What if the object is passed into a function like the following?
void Function(void* object)
{
if (x == 1)
{
reinterpret_cast<XY*>(object)->test = 1;
}
else if (x == 2)
{
reinterpret_cast<XYZ*>(object)->test = 1;
}
}
How can I properly deal with this? I have so much code like this, so I can't write an if condition every time. Also, I am unable to change the structures' layout in any way, shape, or form.
| #define FlexibleOffset(class1, class2, member) (x == 1 ? offsetof(class1, member) : offsetof(class2, member))
#define FlexibleMember(object, member) *reinterpret_cast<decltype(XY::member)*>(reinterpret_cast<uintptr_t>(object) + FlexibleOffset(XY, XYZ, member))
FlexibleMember(object, test) = 1;
void* addressTo = &FlexibleMember(object, test);
If you want to keep the syntax of ->, there is no way but to use this method and declare each of your class members in XYZWrapper:
struct XYZWrapper
{
XYZWrapper(void* ptr)
{
if (x == 1)
{
extra = nullptr; // doesn't exist in x == 1
test = reinterpret_cast<XY*>(ptr)->test;
}
else if (x == 2)
{
extra = reinterpret_cast<XYZ*>(ptr)->extra;
test = reinterpret_cast<XYZ*>(ptr)->test;
}
}
XYZWrapper* operator->() { return this; }
short* extra;
int* test;
}
*XYZWrapper(object)->test = 1;
void* addressTo = XYZWrapper(object)->test;
void SomeFunction(XYZWrapper object)
{
*object->test = 1;
if (x == 2) *object->extra = 4;
}
|
69,353,615 | 69,456,756 | Perfect forwaring of auto&& in generic lambda | The next generic lambda is used to protect any operation which shares resource between threads:
auto mutexed = [mtx(std::mutex{})](auto &&fn, auto &&...args) mutable {
std::unique_lock lo(mtx);
return fn(args...);
//return std::forward<decltype(fn)>(fn)(std::forward<decltype(args)>(args)...);
};
decltype(fn) is not valid for perfect forwarding. It is good for values and rvalues references. But not for lvalue refs.
Writing decltype((fn)) will work with lvalue references but not with rvalues.
So the question.
How to make it to perfectly forward both reference and rvalue reference?
Example to make threads do not corrupt stdout: https://gcc.godbolt.org/z/KsWM6Pq6x
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
using namespace std::chrono_literals;
using std::cout, std::clog, std::cerr, std::endl;
int main() {
cout << "Hello, World!" << endl;
auto mutexed = [mtx(std::mutex{})](auto &&fn, auto &&...args) mutable {
std::unique_lock lo(mtx);
//return fn(args...);
return std::forward<decltype(fn)>(fn)(std::forward<decltype(args)>(args)...);
};
int counter = 0;
auto t1 = std::thread( [&](){
while(1){
std::this_thread::sleep_for(10ms);
// mutexed( [](int&&cnt){ cout << cnt++ << endl; }, std::move(counter) ); //FAILS HERE
mutexed( [](int&cnt){ cout << cnt++ << endl; }, counter ); //lval ref works fine
}
});
auto t2 = std::thread([&]{
while(1){
std::this_thread::sleep_for(10ms);
mutexed( []{ cout << "done long_operation_2" << endl;});}
});
t1.join();
t2.join();
}
Working solution in C++11,14,17 and C++20,23
int main() {
auto lambda20 = []<class F, class...Ts>(F &&fn, Ts &&...args) {
return std::forward<F>(fn)(std::forward<Ts>(args)...);
};
auto lambda14 = [](auto &&fn, auto &&...args) {
return std::forward<
std::conditional_t<
std::is_rvalue_reference_v<decltype(fn)>,
typename std::remove_reference_t<decltype(fn)>,
decltype(fn)>
>(fn)(
std::forward<
std::conditional_t<std::is_rvalue_reference<decltype(args)>::value,
typename std::remove_reference<decltype(args)>::type,
decltype(args)
>>(args)...);
};
int inter = 20;
lambda20([](int x) { cout << "asdf20 x" << endl; }, inter);
lambda20([](int &x) { cout << "asdf20 &x" << endl; }, inter);
lambda20([](int &&x) { cout << "asdf20 &&x" << endl; }, std::move(inter));
lambda14([](int x) { cout << "asdf14 x" << endl; }, inter);
lambda14([](int &x) { cout << "asdf14 &x" << endl; }, inter);
lambda14([](int &&x) { cout << "asdf14 &&x" << endl; }, std::move(inter));
return 0;
}
C++ pre-20 solution 8 years old by Scott Meyers https://scottmeyers.blogspot.com/2013/05/c14-lambdas-and-perfect-forwarding.html
| In C++20 and later
auto lambda20 = []<class F, class...Ts>(F &&fn, Ts &&...args) {
return std::forward<F>(fn)(std::forward<Ts>(args)...);
};
In C++pre20 : C++11,14,17
auto lambda14 = [](auto &&fn, auto &&...args) {
return std::forward<
std::conditional_t<
std::is_rvalue_reference_v<decltype(fn)>,
typename std::remove_reference_t<decltype(fn)>,
decltype(fn)>
>(fn)(
std::forward<
std::conditional_t<std::is_rvalue_reference<decltype(args)>::value,
typename std::remove_reference<decltype(args)>::type,
decltype(args)
>>(args)...);
};
Example
#include <iostream>
using namespace std;
int main() {
auto lambda20 = []<class F, class...Ts>(F &&fn, Ts &&...args) {
return std::forward<F>(fn)(std::forward<Ts>(args)...);
};
auto lambda14 = [](auto &&fn, auto &&...args) {
return std::forward<
std::conditional_t<
std::is_rvalue_reference_v<decltype(fn)>,
typename std::remove_reference_t<decltype(fn)>,
decltype(fn)>
>(fn)(
std::forward<
std::conditional_t<std::is_rvalue_reference<decltype(args)>::value,
typename std::remove_reference<decltype(args)>::type,
decltype(args)
>>(args)...);
};
int inter = 20;
lambda20([](int x) { cout << "asdf20 x" << endl; }, inter);
lambda20([](int &x) { cout << "asdf20 &x" << endl; }, inter);
lambda20([](int &&x) { cout << "asdf20 &&x" << endl; }, std::move(inter));
lambda14([](int x) { cout << "asdf14 x" << endl; }, inter);
lambda14([](int &x) { cout << "asdf14 &x" << endl; }, inter);
lambda14([](int &&x) { cout << "asdf14 &&x" << endl; }, std::move(inter));
return 0;
}
C++ pre-20 solution 8 years old by Scott Meyers https://scottmeyers.blogspot.com/2013/05/c14-lambdas-and-perfect-forwarding.html
|
69,354,120 | 69,354,161 | Trying to iterate through an array using pointers but I get float pointer error / it won't compile | I am learning how pointers work in C++, and am trying to iterate through an array using pointers and that confusing pointer arithmetic stuff.
#include <iostream>
int main()
{
float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
float *ptr1 = arr;
for (int i = 0; i < 5; *ptr1 + 1)
{
std::cout << *ptr1 << std::endl;
}
}
I declare an array of type float called arr[5]. Then I initialize a pointer variable *ptr1 holding the memory address of arr. I try to iterate it using *ptr1+1 (which gives no error), but then when I do std::cout << *ptr1 + 1 << std::endl I get an error:
operator of * must be a pointer but is of type float
Please help me fix this.
| In your loop, after each iteration, *ptr1 + 1 is dereferencing ptr1 to read the float it is currently pointing at, adding 1 to that value, and then discarding the result. You are not incrementing ptr1 itself by 1 to move to the next float in the array. You likely meant to use ptr1 += 1 instead of *ptr1 + 1.
More importantly, you are not incrementing i, so the loop will not terminate after 5 iterations. It will run forever.
The rest of the code is fine (though your terminology describing it needs some work).
Try this:
#include <iostream>
int main()
{
float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
float *ptr1 = arr;
for (int i = 0; i < 5; ++i, ++ptr1)
{
std::cout << *ptr1 << std::endl;
}
}
Online Demo
Though, a simpler way to write this would be to not use manual pointer arithmetic at all, just use normal array indexing notation instead:
#include <iostream>
int main()
{
float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
for (int i = 0; i < 5; ++i)
{
std::cout << arr[i] << std::endl;
}
}
Online Demo
Or better, use a range-based for loop instead, and let the compiler do all the work for you:
#include <iostream>
int main()
{
float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
for (float f : arr)
{
std::cout << f << std::endl;
}
}
Online Demo
|
69,354,129 | 69,354,250 | Real Applications of internal linkage in C++ | This sounds like a duplicate version of What is the point of internal linkage in C++ and probably is. There was only one post with some code that didn't look like a practical example. C++ISO draft says:
When a name has internal linkage, the entity it denotes can be
referred to by names from other scopes in the same translation unit.
It looks a good punctual definition for me, but I couldn't find any reasonable application of that, something like: "look this code, the internal linkage here makes a great difference to implement it". Furthermore based on the definition provided above,it looks that global variables fulfils the internal linkage duty. Could you provide some examples?
| Internal linkage is a practical way to comply with the One Definition Rule.
One might find the need to define functions or objects with plain names, like sum, or total, or collection, or any one of other common terms, more than once. In different translation units they might serve different purposes, specific purposes that are particular to that, particular, translation unit.
If only external linkage existed you'd have to make sure that the same name will not be repeated in different translation units, i.e. little_sum, big_sum, red_sum, etc... At some point this will get real old, real fast.
Internal linkage solves this problem. And unnamed namespaces effectively results in internal linkage for entire classes and templates. With an unnamed namespace: if a translation unit has a need for its own private little template, with a practical name of trampoline it can go ahead and use it, safely, without worrying about violating the ODR.
|
69,354,267 | 69,355,853 | What is the best method for compiling a project with multiple directories in vscode? | The problem is simple. Say you have 3 files in a project and I want to compile them all.
src/proj-runner/main.cpp
#include <iostream>
using namespace std;
int main () {
string line;
Greeting *hello = new Greeting();
cout << hello->hello() << endl;
return 0;
}
src/proj-class/class.cpp
#include "class.h"
Greeting::Greeting() {
}
string Greeting::hello() {
return "Hello World!";
}
src/proj-class/class.h
#include <iostream>
using namespace std;
class Greeting {
public:
Greeting();
string hello();
};
How do I do it without typing g++ proj-runner/main.cpp proj-class/class.cpp every time? I'm using VSCode on linux.
| You can create a vscode build task to run the command for you. To do that, create a .vscode directory in your workspace root and in that directory create a file called tasks.json. Add the following to that file:
{
"version": "2.0.0",
"tasks": [
{
"label": "build_main_and_class",
"type": "shell",
"command": "g++ proj-runner/main.cpp proj-class/class.cpp",
"problemMatcher": [],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Then you can just do any of the following:
Command+Shift+B
Command+Shift+P and select Tasks: Run Build Task
Click Terminal > Run Build Task...
You can read more about tasks in the vscode docs here: https://code.visualstudio.com/docs/editor/tasks#_typescript-hello-world
|
69,354,553 | 69,354,783 | Dialog window procedure as a member function of a class | Based on this post, I'm trying to create a simple Win32 application, in which the window procedure/callback function of a dialog window is a member function of a class. My code looks like this:
H file:
class MyClass
{
public:
HINSTANCE hInstance;
HWND hWnd;
int APIENTRY WinMainProc(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow);
static LRESULT CALLBACK WinProcWraper(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
LRESULT CALLBACK WinProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
ATOM MyClassRegisterClass(HINSTANCE hInstance);
};
CPP file:
LRESULT CALLBACK MyClass::WinProcWraper(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam)
{
if (WM_NCCREATE == message)
{
SetWindowLong (hWnd, GWL_USERDATA, (long)((CREATESTRUCT*) lParam)->lpCreateParams);
return TRUE;
}
return ((MyClass*) GetWindowLong (hWnd, GWL_USERDATA))->WinProc (hWnd, message, wParam, lParam);
}
int APIENTRY MyClass::WinMainProc(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
MyClass.hInstance=hInstance;
MyClass.MyClassRegisterClass(hInstance);
//MY PROBLEM IS HERE: cannot convert parameter 4 to int
HWND hWnd = CreateDialog(hInstance,MAKEINTRESOURCE(IDD_MAIN_DIALOG), 0, (DLGPROC)MyClass::WinProc);
ShowWindow(hWnd,nCmdShow);
UpdateWindow(hWnd);
while (GetMessage(&msg, NULL, 0, 0))
{
if (!IsWindow(hWnd) || !IsDialogMessage(hWnd,&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return static_cast<int>(msg.wParam);
}
LRESULT CALLBACK MyClass::WinProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam)
{
(...)
}
When calling CreateDialog(), I get the following error:
cannot convert from 'long (__stdcall MyClass::*)(struct HWND__ *,unsigned int,unsigned int,long)'
to 'long (__stdcall *)(struct HWND__ *,unsigned int,unsigned int,long)'
How can I make the correct type conversion in this case?
| Lets start with the error message. You are trying to use a non-static class method, WinProc(), as your CreateDialog() callback. That will not work. You went to the trouble of implementing a static class method, WinProcWraper(), which calls WinProc(), but you are not actually using it. You need to use WinProcWraper() as the actual window procedure for CreateDialog().
Also, there is no need to type-cast WinProcWraper when passing it to CreateDialog(), if its signature is correct to begin with (which yours is not).
After fixing that, you still have other problems:
the other code you are modeling after was designed for a window procedure for CreateWindow/Ex(), but you are using CreateDialog() instead, which has different requirements.
Since you are using CreateDialog() instead of CreateWindow/Ex(), WinProcWraper() and WinProc() need to return a BOOL instead of an LRESULT. If an actual LRESULT value needs to be returned to the system, WinProc() will need to use SetWindowLong(DWL_MSGRESULT) for that purpose.
WinProcWraper() is expecting to receive a WM_NCCREATE message to deliver it a MyClass* pointer, which it will then assign to the HWND. But, since you are using CreateDialog(), WinProcWraper() will not receive any WM_(NC)CREATE messages, it will receive a WM_INITDIALOG message instead. And even then, CreateDialog() does not allow you to pass any user-defined value to the window procedure, so you can't pass in the MyClass* pointer that WinProcWraper() requires. You need to use CreateDialogParam() instead for that.
WM_INITDIALOG may not be the first message a window receives, just the first message that can give you access to the MyClass* pointer that you pass to CreateDialogParam(). WinProcWraper() needs to handle the possibility that it can receive messages before it has received access to the MyClass* pointer.
You are using SetWindowLong(). Your code will not work if it is ever compiled for 64bit. Use SetWindowLongPtr() instead, even for 32bit code.
With that said, try this:
class MyClass
{
public:
HINSTANCE hInstance;
HWND hWnd;
int APIENTRY WinMainProc(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow);
BOOL CALLBACK WinProc(UINT uMsg, WPARAM wParam, LPARAM lParam);
ATOM MyClassRegisterClass(HINSTANCE hInstance);
private:
static BOOL CALLBACK WinProcWraper(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
};
BOOL CALLBACK MyClass::WinProcWraper(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
MyClass *cls;
if (WM_INITDIALOG == uMsg)
{
cls = reinterpret_cast<MyClass*>(lParam);
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(cls));
}
else
cls = reinterpret_cast<MyClass*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if (cls)
return cls->WinProc(uMsg, wParam, lParam);
return FALSE;
}
int APIENTRY MyClass::WinMainProc(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
MyClass.hInstance = hInstance;
MyClass.MyClassRegisterClass(hInstance);
HWND hWnd = CreateDialogParam(hInstance, MAKEINTRESOURCE(IDD_MAIN_DIALOG), NULL, MyClass::WinProcWraper, reinterpret_cast<LPARAM>(this));
if (!hWnd)
return -1;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
while (GetMessage(&msg, NULL, 0, 0))
{
if (!IsWindow(hWnd) || !IsDialogMessage(hWnd, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return static_cast<int>(msg.wParam);
}
BOOL CALLBACK MyClass::WinProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
...
if (needed)
SetWindowLongPtr(hWnd, DWLP_MSGRESULT, ...);
return ...; // TRUE or FALSE as needed...
}
|
69,354,607 | 69,418,832 | Is there a difference between SVML vs. normal intrinsic square root functions? | Is there any sort of difference in precision or performance between normal sqrtps/pd or the SVML version:
__m128d _mm_sqrt_pd (__m128d a) [SSE2]
__m128d _mm_svml_sqrt_pd (__m128d a) [SSE?]
__m128 _mm_sqrt_ps (__m128 a) [SSE]
__m128 _mm_svml_sqrt_ps (__m128 a) [SSE?]
I know that SVML Intrinsics like _mm_sin_ps are actually functions consisting of potentially multiple asm instructions, thus they should be slower than any single multiply or even divide. However, I'm curious as to why these function exist if there are hardware-level Intrinsics available.
Were these SVML functions created before SSE2? Or is there a difference in precision?
| I've inspected the code gen in MSVC.
_mm_svml_sqrt_pd compiles into a function call; the called function consists of a single sqrtpd followed by ret
_mm_svml_sqrt_ps compiles into a function call; the called function consists of a single sqrtps followed by ret
_mm_sqrt_pd and _mm_sqrt_ps intrinsics compile to inlined sqrtpd and sqrtps
A possible explanation (just guess):
SVML intended to have CPU dispatch, but the version compiled for MSVC has this CPU dispatch disabled. The goal may be to implement it differently for Xeon Phi, the Xeon Phi version may be not included in MSVC build of SVML.
Screenshot:
When using Intel compiler, it is using svml_dispmd.dll, and there's actual dispatch function (real indirect jump ff 25 42 08 00 00), which ends up in vsqrtpd for me
|
69,355,139 | 69,370,764 | Make can't find .hpp file in Boost | I'm using an Ubuntu virtual machine and am encountering the following error message when running the 'make' command:
Scanning dependencies of target AIToolboxMDP
[ 1%] Building CXX object src/CMakeFiles/AIToolboxMDP.dir/Impl/Seeder.cpp.o
[ 1%] Building CXX object src/CMakeFiles/AIToolboxMDP.dir/Impl/CassandraParser.cpp.o
In file included from /home/ben/AI/AI-Toolbox-master/include/AIToolbox/Impl/CassandraParser.hpp:4,
from /home/ben/AI/AI-Toolbox-master/src/Impl/CassandraParser.cpp:1:
/home/ben/AI/AI-Toolbox-master/include/AIToolbox/Types.hpp:7:10: fatal error: boost/multi_array.hpp: No such file or directory
7 | #include <boost/multi_array.hpp>
| ^~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [src/CMakeFiles/AIToolboxMDP.dir/build.make:76: src/CMakeFiles/AIToolboxMDP.dir/Impl/CassandraParser.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:1140: src/CMakeFiles/AIToolboxMDP.dir/all] Error 2
make: *** [Makefile:95: all] Error 2
I ran cmake right before make, and cmake was able to find Boost; I can also see that the multi_array.hpp file is in the folder /home/ben/AI/boost_1_77_0/boost, so I'm not sure why make can't find the file. I tried adding variations of the line target_link_libraries(program ${Boost_LIBRARIES}) into the CMakeLists.txt file and using variations of the -L/-l options with the make call, and neither method worked (although I wasn't sure which program name to use with target_link_libraries so I tried a bunch of guesses but maybe I didn't use the right one; I'm trying to build AI-Toolbox if that helps).
I also have to add several options to the cmake command I run right before make in order to get rid of any errors with that; here's what I enter in case that would do anything or if I need to add something else in there:
cmake .. -DBOOST_ROOT=/home/ben/AI/boost_1_77_0 -DLPSOLVE_INCLUDE_PATH=/home/ben/AI/lpsolve -DVCPKG_TARGET_TRIPLET=x64-linux -DCMAKE_TOOLCHAIN_FILE=/home/ben/AI/vcpkg/scripts/buildsystems/vcpkg.cmake
My CMakeLists.txt file contains the following lines (among others, but these seem like the most relevant) just in case that helps as well:
find_package(Boost ${BOOST_VERSION_REQUIRED} REQUIRED)
include_directories(SYSTEM ${Boost_INCLUDE_DIRS})
Would anyone have any ideas as to how I can get past the make error?
| I ended up solving it by deleting my Boost folder and reinstalling it using the command sudo apt-get install libboost-all-dev; I just reran cmake and took out all the options I had been using except for the lpsolve one, and then when I ran make afterward I encountered no issues.
|
69,355,295 | 69,355,344 | How to remove preceding '0' from numbers 10 and above? | How can I remove the preceding '0' from number 10 above? Only numbers 1-9 should have preceding '0'.
SAMPLE INPUT:
40
SAMPLE OUTPUT:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
21.22.23.24.25.26.27.28.29.30
31.32.33.34.35.36.37.38.39.40
MY CODE'S OUTPUT:
01.02.03.04.05.06.07.08.09.010
011.012.013.014.015.016.017.018.019.020
021.022.023.024.025.026.027.028.029.030
031.032.033.034.035.036.037.038.039.040
Can you help me, please? I tried different ways but still won't work. I'm new in programming btw, that's why I don't know much.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> b;
if (b > 100){
cout << "OUT OF RANGE";
}
else {
for (int a = 1; a <= b; a++){
cout << "." << "0" << a;
}
}
}
| std::cout <<"." << std::setfill('0') << std::setw(2) << a;
|
69,357,059 | 69,357,617 | C++: Backspace characters not showing in stdout? | I am implementing a shell that has command history. When the user presses the up or down arrow, the text in the current line is replaced with the previous or next command.
The algorithm I'm planning on implementing is fairly simple. If the current command has k characters, I output k '\b' characters to delete the k characters int he current line and then output the selected command to the line.
However, I'm trying to start out with something basic, such as seeing if outputting '\b' characters even works in deleting characters from the current stdout line:
#include <iostream>
#include <queue>
#include <deque>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
cout << "asdf";
cout << "\b\b" << endl;
return 0;
}
The output of the above piece of code is:
asdf
When I expect:
as
Important: I want to delete characters after they are outputted to stdout.
| You need ANSI escape codes. Try:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]){
cout << "asdf";
cout<<"\b\b\b\b\033[J";
return 0;
}
\033 stands for ESC and [J is a parameter to the code. ESC[J clears the screen from the cursor to the end of the screen. For more information: https://en.wikipedia.org/wiki/ANSI_escape_code#Fe_Escape_sequences
As @n. 1.8e9-where's-my-share m. mentioned, \b simply moves the cursor back one space, and does not rewrite anything, for most implementations.
|
69,357,332 | 69,357,851 | Why does string shuffle stop working after 10 characters in the string? | #include <iostream>
#include <string>
using namespace std;
string cardsShuffle(string orig_seq){
string choice;
int random = 0;
string shuffled_seq;
int orig_len = orig_seq.length();
while(orig_len > shuffled_seq.length()){
random = rand() % orig_seq.length();
while(random % 2 != 0){
random = rand() % orig_seq.length();
}
choice = orig_seq.substr(random,2);
orig_seq.erase(random,random+2);
shuffled_seq = shuffled_seq + choice;
}
return shuffled_seq;
}
int main()
{
string orig_seq;
cout << "Enter orig_seq: \n";
cin >> orig_seq;
cout << cardsShuffle(orig_seq);
return 0;
}
This works perfectly until you try it with 10 characters then nothing is ever returned and the program just exist normally after going through the function as it normally does, except I can't figure out why it just decides it's done
| I don't get a normal exit, I get "Floating point exception(core dumped)".
The erase function does not have the parameters you think it does - like substr, the second is the length, not the "one past the end" index.
(std::string has a peculiar interface, as it was created long before the standard collections were added.)
So you remove random+2 characters, and the longer the string, the greater the chance that you end up erasing too many characters, and that will lead to undefined behaviour.
Change that line to
orig_seq.erase(random, 2);
|
69,358,284 | 69,358,404 | STL generic algorithms - implicit conversion of the ranges element type to the predicates parameter type | Say I want to remove all punctuation characters within a std::string using the erase-remove idiom.
However, let str be of type std::string, this call won't compile
str.erase( std::remove_if(str.begin(), str.end(), std::ispunct), str.end() );
Now I guess, strictly speaking the std::ispunct callables parameter type is int and therefore doesn't match the ranges element type char.
However, as a char is a numeric type it should be convertible to int. I'm working with Lippman's C++ Primer book which states
The algorithms that take predicates call the predicate on the elements in the input range. [...] it must be possible to convert the element type to the parameter type in the input range.
which imo is given in the above statement.
Also std::ispunct returns an int, and thus should be usable as a condition.
So why does the compiler complain no matching function for call to 'remove_if'?
(clang++ -std=c++11 -o main main.cc)
A fix would be to use a lambda
str.erase( std::remove_if(str.begin(), str.end(),
[] ( unsigned char ch ) { return std::ispunct(ch); }),
str.end() );
still it suprised me that a lambda is necessary...
Thanks in advance!
| Consider the following code:
#include <iostream>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
bool foo(int i) { return true; }
int main() {
string str = string("");
str.erase( std::remove_if(str.begin(), str.end(), foo), str.end() );
str.erase( std::remove_if(str.begin(), str.end(), std::ispunct), str.end() );
}
This contains a call using foo, and one with std::ispunct. The former is OK, and the latter is not.
The error is
main.cpp:13:30: error: no matching function for call to 'remove_if(std::__cxx11::basic_string<char>::iterator, std::__cxx11::basic_string<char>::iterator, <unresolved overloaded function type>)'
13 | str.erase( std::remove_if(str.begin(), str.end(), std::ispunct), str.end() );)
main.cpp:13:30: error: no matching function for call to 'remove_if(std::__cxx11::basic_string<char>::iterator, std::__cxx11::basic_string<char>::iterator, <unresolved overloaded function type>)'
13 | str.erase( std::remove_if(str.begin(), str.end(), std::ispunct), str.end() );
So the problem is not with the conversion, since it works with foo. The problem is that it cannot resolve which overloading you mean. Note that there are actually two versions of ispunct (one is in <locale>).
|
69,358,555 | 69,358,596 | How to get const_iterator when the T is 'const std::map',? | I have the following struct:
template<typename T>
struct Foo
{
typename T::iterator iter;
};
The expected type:
iter is a std::map<K, V>::iterator when T is deduced as std::map<K, V>.
iter is a std::map<K, V>::const_iterator when T is deduced as const std::map<K, V>
But my code always get a std::map<K, V>::iterator.
How to achieve the expected implementation?
| You can provide a std::conditional type:
#include <type_traits> // std::conditional_t
template<typename T>
struct Foo {
using iter = std::conditional_t<std::is_const_v<T>
, typename T::const_iterator
, typename T::iterator>;
};
|
69,358,675 | 69,372,321 | How to use collate_fn in LibTorch | I'm trying to implement an image based regression using a CNN in libtorch. The problem is, that my images got different sizes, which will cause an Exception batching the images.
First things first, I create my dataset:
auto set = MyDataSet(pathToData).map(torch::data::transforms::Stack<>());
Then I create the dataLoader:
auto dataLoader = torch::data::make_data_loader(
std::move(set),
torch::data::DataLoaderOptions().batch_size(batchSize).workers(numWorkersDataLoader)
);
The exception will be thrown batching data in the train loop:
for (torch::data::Example<> &batch: *dataLoader) {
processBatch(model, optimizer, counter, batch);
}
with a batch size greater than 1 (with a batch size of 1 everything works well because there isn't any stacking involved). For example I'll get the following error using a batch size of 2:
...
what(): stack expects each tensor to be equal size, but got [3, 1264, 532] at entry 0 and [3, 299, 294] at entry 1
I read that one could for example use collate_fn in order to implement some padding (for example here), I just do not get where to implement it. For example torch::data::DataLoaderOptions does not offer such a thing.
Does anyone know how to do this?
| I've got a solution now. In summary, I'm split my CNN in Conv- and Denselayers and use the output of a torch::nn::AdaptiveMaxPool2d in the batch construction.
In order to do so, I have to modify my Dataset, Net and train/val/test-methods. In my Net I added two additional forward-functions. The first one passes data through all Conv-Layers and returns the output of an AdaptiveMaxPool2d-Layer. The second one passes the data through all Dense-Layers. In practice this looks like:
torch::Tensor forwardConLayer(torch::Tensor x) {
x = torch::relu(conv1(x));
x = torch::relu(conv2(x));
x = torch::relu(conv3(x));
x = torch::relu(ada1(x));
x = torch::flatten(x);
return x;
}
torch::Tensor forwardDenseLayer(torch::Tensor x) {
x = torch::relu(lin1(x));
x = lin2(x);
return x;
}
Then I override the get_batch method and use forwardConLayer to compute every batch entry. In order to train (correctly), I call zero_grad() before I construct a batch. All in all this looks like:
std::vector<ExampleType> get_batch(at::ArrayRef<size_t> indices) override {
// impl from bash.h
this->net.zero_grad();
std::vector<ExampleType> batch;
batch.reserve(indices.size());
for (const auto i : indices) {
ExampleType batchEntry = get(i);
auto batchEntryData = (batchEntry.data).unsqueeze(0);
auto newBatchEntryData = this->net.forwardConLayer(batchEntryData);
batchEntry.data = newBatchEntryData;
batch.push_back(batchEntry);
}
return batch;
}
Lastly I call forwardDenseLayer at all places where I normally would call forward, e.g.:
for (torch::data::Example<> &batch: *dataLoader) {
auto data = batch.data;
auto target = batch.target.squeeze();
auto output = model.forwardDenseLayer(data);
auto loss = torch::mse_loss(output, target);
LOG(INFO) << "Batch loss: " << loss.item<double>();
loss.backward();
optimizer.step();
}
Update
This solution seems to cause an error if the number of the dataloader's workers isn't 0. The error is:
terminate called after thro9wing an instance of 'std::runtime_error'
what(): one of the variables needed for gradient computation has been modified by an inplace operation: [CPUFloatType [3, 12, 3, 3]] is at version 2; expected version 1 instead. ...
This error does make sense because the data is passing the CNN's head during the batching process. The solution to this "problem" is to set the number of workers to 0.
|
69,358,695 | 69,836,645 | Eclipse CDT Indexer not including header from same project | After a recent upgrade (only SSD capacity change), Eclipse CDT Indexer has been giving me a tough time. My project folder structure is as shown below.
LinEmLibrary
└─ test
├─ TestNumParam.cpp
├─ TestNumParam.h
├─ TestPMS.cpp
├─ TestPMS.h
├─ TestSerial.cpp
├─ TestSerial.h
├─ TestWindow.cpp
└─ TestWindow.h
TestWindow.h has the class implementing the top level window and the other three are instantiated by the class CTestWindow.
After the upgrade (until which things were running perfectly), Codan (code analysis) started highlighting the declarations of all of my class instances (CTestNUmParam, CTestPMS and CTestSerial) in red saying Type X could not be resolved. However I am able to perform code completion (CTRL+SPACE) and resolve all members of the class though it takes a painfully long amount of time. The code builds and executes properly.
I have tried
rebuilding the index
Increased the Indexer cache limits (Window > Preferences > C/C++ > Indexer - Cache limits) to,
Limit relative to the maximum heap size: 75%
Absolute limit: 1024 MB
Set the initial and maximum heap size in eclipse.ini to
Xms2048m
Xmx4096m
adding absolute path to this folder in the Project Settings > C/C++ General > Paths and Symbols and even include my header using <> instead of ""
create a new project and manually copy the files to the new project
export the project and open in another computer having same build tools
But in all cases the result is the same.
When I create a parse log for TestWIndow.h (right click on the header file in project explorer, Index > Create Parser Log File) I get the following output (first ~12,000 lines removed).
Unresolved includes (from headers in index):
file:/home/mohith/eclipse_workspace/LinEmLibrary/test/TestNumParam.h is not indexed
file:/home/mohith/eclipse_workspace/LinEmLibrary/test/TestPMS.h is not indexed
file:/home/mohith/eclipse_workspace/LinEmLibrary/test/TestSerial.h is not indexed
Unresolved names:
Attempt to use symbol failed: CTestNumParam in file /home/mohith/eclipse_workspace/LinEmLibrary/test/TestWindow.h:76
Attempt to use symbol failed: CTestPMS in file /home/mohith/eclipse_workspace/LinEmLibrary/test/TestWindow.h:77
Attempt to use symbol failed: CTestSerial in file /home/mohith/eclipse_workspace/LinEmLibrary/test/TestWindow.h:78
A template id provides illegal arguments for the instantiation: map in file /home/mohith/eclipse_workspace/LinEmLibrary/test/TestWindow.h:80
Attempt to use symbol failed: EGridType in file /home/mohith/eclipse_workspace/LinEmLibrary/test/TestWindow.h:80
The reason for the semantic highlighting is now understood from this but why the indexer is not including my own header files leaves me clueless.
Would be a great help if someone can shed some light.
My system information
Eclipse
Version: 2021-09 (4.21.0)
Build id: 20210910-1417
CDT: 10.4.0.202109080104
OS Ubuntu 20.04 x86-64
RAM: 16 GiB
CPU: Intel® Core™ i5-8265U CPU @ 1.60GHz
| After a month of struggle I have finally broght things back to normal.
The issue appears to be the preferences I would import after creating a new workspace. I have exported preferences once after setting up the environment for code style, editor font / color etc. I don't remember exactly but I might have created it while running Eclipse 2021-03.
This time I created a new workspace and added the project from SVN without importing preferences and viola... all my headers are indexed! Later I individually exported the code style and other templates and brought it into my new workspace without any issues.
I was also facing issue with Log4CPlus where all its macros were marked as 'symbol not resolved'. Upon inspecting the parser log file I saw that the symbol __cplusplus was set to 201402 even though I had selected c++20 as the dialect in build settings. Then I added the symbol __cplusplus manully in Project Settings > C/C++ General > Paths and Symbols > Symbols > GNU C++ while settings it to 202002. That fixed the issue with Log4CPlus as well.
|
69,358,836 | 69,360,677 | Conan packages migration from official repo to local private repo | I would like to know if it is possible to upload a package from official "conan-center" repo and all its dependencies into a local private repository (who does not have internet access)
Example:
In "conan-center" repo there is a package A.
Package A has some dependencies: B and C.
I wanto to upload A (and automatically B and C) in a private artifactory repo using the "conan upload" command.
What is the best way to do this?
| The best to do it is using the Artifactory feature Remote Repository, where Artifactory will download it for you when a package is not available in your Local Remote.
However, if you don't have internet connection, it will be more complicated, you will need to download which packages do you need and upload them manually.
For instance, you can use conan download command and after that conan upload
For instance:
conan download openssl/1.1.1@ -r conancenter
conan user -p mypassword -r mylocalremote username
conan upload "*" -r mylocalremote --all --confirm --parallel
In my opinion you should try to solve the connection limitation, because using Artifactory Remote Repository will save a lot of your time.
|
69,360,721 | 69,405,074 | Can't compile with extern library | I've installed the jsoncpp library via vcpkg into my project directory. Since the compiler looks for header files mostly in predefined include directories how can I add the library to those directories so that the compiler can recognize it?
Error:
fatal error: 'json.h' file not found
| I found the issue: The package wasn't installed properly due to a homebrew error. I had a shallowed version of homebrew. I had to unshallow and upgrade it and then download the package again, now it works.
|
69,360,822 | 69,361,078 | How to modernize memalign in a C++ codebase? | I am modernizing/updating some old code that was originally written in C but is now used in a C++ codebase (no need to be backwards compatible). A bunch of this code is memory optimized with memalign with which I am very inexperienced with so my question is how one would update this code (or just leave it like it is) and whether there's even still any point to having it there at all:
The declaration:
float *table_pf;
And how it's initialized in the constructor:
table_pf = (float*)memalign(32, sizeof(float) * TALBLE_SIZE);
I was unable to find any equivalent for modern C++ but I may also have just missed it. Usually I would simply convert the pointer to a std::vector or std::array but this does not work when using memalign.
| If std::array is an option for you, it's easy to align (same applies to bare arrays):
alignas(32) std::array<TALBLE_SIZE, float> table;
The standard function for dynamically allocating over-aligned memory inherited from C is std::aligned_alloc. It's nearly identical to the non-standard memalign; only difference is that it's stricter in requiring the size to be a multiple of the alignment. A pure C++ option is to use the operator new with std::align_val_t operand which will by default use std::aligned_alloc.
It's not a good idea to use the bare pointer returned by the allocation function though: You should use RAII. One option is to use std::vector with an allocator that uses over-aligned allocation function. Standard library doesn't provide such allocator though, so a custom one needs to be used. A more straightforward but less flexible option is to use std::unique_ptr with a deleter that calls std::free (or operator delete in case you had used operator new).
|
69,362,208 | 69,362,246 | Remove '0' from numbers less than and equal 9 | How can I have an output of
Sample Input No.1:
9
Sample Output No.1:
1.2.3.4.5.6.7.8.9
If you input numbers less than or equal to 9, the output should be (1.2.3.4.5.6.7.8.9)
And if you input numbers greater than 9, for example:
Sample Input No.2:
20
Sample Output No.2:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
My code below is for Sample Input & Output No.2. I tried adding another for loop for SAMPLE NO.1 but it still reads Sample No.2 code. What should I do?
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int a, num;
cin >> num;
if (num > 100 || num <= 1){
cout << "OUT OF RANGE";
}
else {
for (int a = 1; a < num; a++){
cout << setfill('0') << setw(2) << a << ".";
}
cout << num;
}
}
kind of new to programming, don't know much
| As a possible solution, you could read the input as a string, then convert it to an integer.
Use the string length as the field width for the setw manipulator.
This should be able to handle values of (theoretically) arbitrary length.
|
69,362,554 | 69,362,614 | Why can't I deduce the function signature for a mutable lambda? | I have the following code which implements a memoize function.
note The question is not about how to write a memoize function specifically but rather about the compile error I get with this implementation and the smallest change to get it to work.
The implementation.
#include <functional>
#include <map>
#include <functional>
#include <iostream>
using namespace std;
template<typename T>
struct memfun_type
{
using type = void;
};
template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...) const>
{
using type = std::function<Ret(Args...)>;
};
template<typename F>
typename memfun_type<decltype(&F::operator())>::type
FFL(F const &func)
{ // Function from lambda !
return func;
}
template <typename ReturnType, typename... Args>
std::function<ReturnType (Args...)>
memoizeImp(std::function<ReturnType (Args...)> func)
{
std::map<std::tuple<Args...>, ReturnType> cache;
return ([=](Args... args) mutable {
std::tuple<Args...> t(args...);
if (cache.find(t) == cache.end())
cache[t] = func(args...);
return cache[t];
});
}
template <typename Fn>
auto memoize(Fn && fn){
return memoizeImp(FFL(fn));
}
and test program
int main()
{
auto a = 2.;
auto foo = [a](double x){return x+a;};
auto foom = memoize(foo);
std::cout << foo(1) << std::endl;
std::cout << foom(1) << std::endl;
}
the output as expected is
3
3
However if I make a small change to the test program changing
auto foo = [a](double x){return x+a;};
to
auto foo = [a](double x)mutable{return x+a;};
I get the following compile error on gcc
Could not execute the program
Compiler returned: 1
Compiler stderr
<source>: In instantiation of 'auto memoize(Fn&&) [with Fn = main()::<lambda(double)>&]':
<source>:49:24: required from here
<source>:42:26: error: invalid use of void expression
42 | return memoizeImp(FFL(fn));
| ~~~^~~~
<source>: In instantiation of 'typename memfun_type<decltype (& F::operator())>::type FFL(const F&) [with F = main()::<lambda(double)>; typename memfun_type<decltype (& F::operator())>::type = void; decltype (& F::operator()) = double (main()::<lambda(double)>::*)(double)]':
<source>:42:26: required from 'auto memoize(Fn&&) [with Fn = main()::<lambda(double)>&]'
<source>:49:24: required from here
<source>:24:12: error: return-statement with a value, in function returning 'memfun_type<double (main()::<lambda(double)>::*)(double)>::type' {aka 'void'} [-fpermissive]
24 | return func;
| ^~~~
The failing code and compile error can be viewed and tested at https://godbolt.org/z/74PKWvqr4
I'm not sure what the fix is to make it work with mutable lambdas.
| You are lacking a specialisation.
Adding this makes it work
template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...)>
{
using type = std::function<Ret(Args...)>;
};
The operator() of the closure-type of a lambda is const qualified iff the lambda is not declared mutable
|
69,362,579 | 69,369,586 | C++: How to cross-compile from Windows to Linux? | I have a C++ module on windows which I want to compile such that I get a dynamic library for linux *.so.
Does a cross-compiler exist that can help me out?
| Several comments mentioned using Windows Subsystem for Linux. I would personally recommend this as it is far easier than trying to use a cross-compiler. It also comes with the added benefit that you can test your code in the same environment in which you compile it.
https://learn.microsoft.com/en-us/windows/wsl/about is a great resource for getting started with WSL.
|
69,363,104 | 69,363,218 | Error reporting in C++ programming in VS code | I have no problem compiling files with G++, but VS code reports an error to the C++ 11 standard syntax. I want to know how to make VS code detect the syntax normally.
a space is required between consecutive right angle brackets (use '> >')
non-aggregate type 'vector<vector >' cannot be initialized with an initializer list
| Add "C_Cpp.default.cppStandard": "c++11" to settings.json. (F1 -> Open Settings (JSON) or Open Workspace Settings (JSON))
|
69,363,344 | 69,370,263 | Cppyy cmake build unable to find LibClang | I've been trying to use cppyy to build some python bindings for a C++ library. At the moment I am using the cookiecutter recipe from here: https://github.com/camillescott/cookiecutter-cppyy-cmake
But the package is having trouble finding LibClang_LIBRARY and LibClang_PYTHON_EXECUTABLE. This is the same case if I install cppyy with conda or pip, and importing cppyy in python works fine.
I have tried manually defining the paths with cmake -DLibClang_LIBRARY=<path/to/libclang> -DLibClang_PYTHON_EXECUTABLE=<path/to/executable> .. and although it then finds LibClang_LIBRARY, it is unable to find LibClang_PYTHON_EXECUTABLE.
It appears to be a problem with cmake finding the appropriate paths, the full error is
CMake Error at /usr/local/Cellar/cmake/3.21.3/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
Could NOT find LibClang (missing: LibClang_LIBRARY
LibClang_PYTHON_EXECUTABLE)
Call Stack (most recent call first):
/usr/local/Cellar/cmake/3.21.3/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:594 (_FPHSA_FAILURE_MESSAGE)
cmake/FindLibClang.cmake:47 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
cmake/FindCppyy.cmake:286 (find_package)
CMakeLists.txt:71 (cppyy_add_bindings)
Has anyone else found this problem or even better a solution to it?
| The cmake fragments in the cookie cutter example seem to be older than the ones in cppyy-cling: https://github.com/wlav/cppyy-backend/tree/master/cling/python/cppyy_backend/cmake
(These are the ones installed under cppyy_backend/cmake in the Python site-packages directory.)
The newer version protects the searches with a predicate in case the variables are explicitly defined as you do with the -D... option, which I suspect will then solve most of the issues you encountered.
It also uses llvm-config if available, which is more robust than trying likely directories.
|
69,363,387 | 69,363,657 | string stream vs direct string | I'm attempting to send a STOMP frame to a server. I first tried to create the message directly using std::string, but the server kept complaining I am doing it wrong. But, when I created the message using stringstream, it works. Anyone can spot my mistake? The code is as shown. It complains it can't find the terminating \0 at the end of the message (parsingmissingnullinbody).
bool CheckResponse(const std::string& response)
{
// We do not parse the whole message. We only check that it contains some
// expected items.
bool ok {true};
ok &= response.find("ERROR") != std::string::npos;
ok &= response.find("ValidationInvalidAuth") != std::string::npos;
std::cout << response << "\n";
return ok;
}
BOOST_AUTO_TEST_CASE(connect_to_network_events){
// Always start with an I/O context object.
boost::asio::io_context ioc {};
// Create also a tls context
boost::asio::ssl::context ctx{boost::asio::ssl::context::tlsv12_client};
// Connection targets
const std::string url {"ltnm.learncppthroughprojects.com"};
const std::string port {"443"};
const std::string endpoint {"/network-events"};
// The class under test
WebSocketClient client {url, endpoint, port, ioc, ctx};
// MY ATTEMPT AT CREATING MESSAGE DIRECTLY, THIS FAILED
// const std::string message {"STOMP\naccept-version:1.2\nhost:transportforlondon.com\nlogin:fake_username\npasscode:fake_password\n\n\0"};
// THE FOLLOWING SUCCEEDED INSTEAD
const std::string username {"fake_username"};
const std::string password {"fake_password"};
std::stringstream ss {};
ss << "STOMP" << std::endl
<< "accept-version:1.2" << std::endl
<< "host:transportforlondon.com" << std::endl
<< "login:" << username << std::endl
<< "passcode:" << password << std::endl
<< std::endl // Headers need to be followed by a blank line.
<< '\0'; // The body (even if absent) must be followed by a NULL octet.
const std::string message {ss.str()};
std::string response;
// We use these flags to check that the connection, send, receive functions
// work as expected.
bool connected {false};
bool messageSent {false};
bool messageReceived {false};
bool messageMatches {false};
bool disconnected {false};
// Our own callbacks
auto onSend {[&messageSent](auto ec) {
messageSent = !ec;
}};
auto onConnect {[&client, &connected, &onSend, &message](auto ec) {
connected = !ec;
if (!ec) {
client.Send(message, onSend);
}
}};
auto onClose {[&disconnected](auto ec) {
disconnected = !ec;
}};
auto onReceive {[&client,
&onClose,
&messageReceived,
&messageMatches,
&message,
&response](auto ec, auto received) {
messageReceived = !ec;
response = received;
client.Close(onClose);
}};
// We must call io_context::run for asynchronous callbacks to run.
client.Connect(onConnect, onReceive);
ioc.run();
BOOST_CHECK(CheckResponse(response));
}
| Creating an std::string from const char * will ignore the terminating NULL character. You could use the char[] constructor but I think it won't fit your use case.
Example:
// Example program
#include <iostream>
#include <string>
int main()
{
std::string message1 {"STOMP\naccept-version:1.2\nhost:transportforlondon.com\nlogin:fake_username\npasscode:fake_password\n\n\0"};
std::cout << message1.length() << std::endl;
std::string message2 {"STOMP\naccept-version:1.2\nhost:transportforlondon.com\nlogin:fake_username\npasscode:fake_password\n\n"};
std::cout << message2.length() << std::endl;
message2.push_back('\0');
std::cout << message2.length() << std::endl;
}
Output:
97
97
98
So you just need to create the message without the terminating NULL character and then append \0.
Update: If you are in C++14 you may want to use string literals:
using namespace std::string_literals;
// ...
std::string message = "STOMP\naccept-version:1.2\nhost:transportforlondon.com\nlogin:fake_username\npasscode:fake_password\n\n\0"s;
Note the s at the end of the string.
|
69,363,581 | 69,364,271 | Is it valid to move away an object managed by a std::shared_ptr | Context
I am trying to forward ownership of a std::unique_ptr through a lambda. But because std::functions must always be copyable, capturing a std::unique_ptr is not possible. I am trying to use a workaround described here: https://stackoverflow.com/a/29410239/6938024
Example
Here is my example which uses the described workaround
struct DataStruct
{
/*...*/
};
class ISomeInterface
{
/*...*/
};
class SomeOtherClass
{
public:
void GetSomethingAsync(std::function<void(DataStruct)> resultHandler);
};
class MyClass
{
void Foo(
std::unique_ptr<ISomeInterface> ptr,
std::function<void(std::unique_ptr<ISomeInterface>, DataStruct)> callback)
{
// I just want to "pass through" ownership of ptr
std::shared_ptr sharedPtr =
std::make_shared<std::unique_ptr<ISomeInterface>>(std::move(ptr));
mSomeOtherClass.GetSomethingAsync(
[cb = std::move(callback), sharedPtr](DataStruct data)
{
auto unique = std::move(*sharedPtr.get());
cb(std::move(unique), data);
});
}
SomeOtherClass mSomeOtherClass;
};
Question
Does moving away the std::unique_ptr, which is managed by the std::shared_ptr cause any risk? My assumption would be, that the std::shared_ptr should try to delete the std::unique_ptr object, which is now dangling.
Is this code "safe"? Could the std::shared_ptr try to delete a dangling pointer, or can it know, that its managed object was moved away?
I would appreciate to understand the behaviour in this case more clearly. Someone please explain the specifics of what happens with the smart pointers here.
EDIT: Changed a wrong line in the example.
cb(std::move(*sharedPtr), data); was changed to cb(std::move(unique), data);
| We have our unique ptr to an interface I:
up[I]
where [] is ascii-art for the "box" we put the "I" in. We then put this in a box:
sp[up[I]]
the data is "double boxed".
We then pass this double box around. When we need to get at the unique ptr, we crack it with a std::move(*sp.get()). This leaves us with both of:
sp[up[nullptr]]
up[I]
a up[nullptr] is a perfectly ok smart pointer. It just has nothing inside the box. You can destroy such an empty box without a problem.
We then pass the up[I] into the callback.
|
69,364,273 | 69,369,034 | ncurses WINDOW* disappears after console resize | So, let's say we have a
WINDOW *main_win=newwin(50, 80, 1, 0); // 50 rows, 80 columns
WINDOW *status_win=newwin(3, 100, 51, 0); // Status bar
WINDOW *interaction_bar=newwin(1, 200, 0, 0);
I have a function that prints strings onto it (mvwaddstr) and it works as planned. But after resizing the terminal to particularly <50 columns and resize it back to >53 columns, the status_win just magically disappears. wclear and wrefresh doesn't render anything onto it.
I've tested something like
delwin(main_win);
delwin(status_win);
delwin(interaciton_bar);
main_win=newwin(50, 80, 1, 0);
status_win=newwin(3, 100, 51, 0);
interaction_bar=newwin(1, 200, 0, 0);
Surprisingly, the status_win gets rendered back. But there's a problem.
I use int ch = wgetch(main_win); to get my keyboard input. Somehow it can read keys like 'w', 'a', 's', 'd', but when it comes to keys like KEY_LEFT and KEY_RIGHT, my console just starts to jitter and seems like it isn't being processed.
| Regarding the disappearing window (likely reduced to 1x1, which is not "magically disappears"). ncurses will attempt to keep a window which has the same width (or height) as stdscr preserve that relationship when resizing, as mentioned in the manual page:
When resizing windows, resize_term recursively adjusts subwindows,
keeping them within the updated parent window's limits. If a top-level
window happens to extend to the screen's limits, then on resizing the
window, resize_term will keep the window extending to the corresponding
limit, regardless of whether the screen has shrunk or grown.
Regarding "starts to jitter", if your window did not enable keypad (as in the given fragment of code), then the cursor keys will be seen as a sequence of characters rather than as a single code:
The keypad option enables the keypad of the user's terminal. If enabled (bf is TRUE), the user can press a function key (such as an arrow
key) and wgetch(3x) returns a single value representing the function
key, as in KEY_LEFT. If disabled (bf is FALSE), curses does not treat
function keys specially and the program has to interpret the escape sequences itself. If the keypad in the terminal can be turned on (made
to transmit) and off (made to work locally), turning on this option
causes the terminal keypad to be turned on when wgetch(3x) is called.
The default value for keypad is FALSE.
|
69,364,614 | 69,364,657 | Variable passed-by-reference is changed in function scope but not in main scope | I'm trying to alter a given grid of vectors into a heightmap, which I do by passing a vector of vertices by reference to a function which should calculate the height for each vertex and change it. However, when printing the height of the new vertices in the main scope, all are 0, whereas if I print the height of the vertices just after I calculate them, I get the correct result.
int main(){
std::vector<glm::vec3> vertinfo = generate_grid(4, 4, 2.0f, 2.0f); //generates the grid
generate_randomheightmap(vertinfo); //SHOULD modify the height of the vertices
//printing the y value of any of the vertices here will result in 0 (the unchanged value)
...
}
void generate_randomheightmap(std::vector<glm::vec3>& base, uint32_t layers){
for (glm::vec3 vertex : base){
vertex.y += vertex.x * vertex.z;
//printing the y value of the vertex here will result in the correct calculated value
}
}
Does this not work because the vec3 objects themselves are instead copied while the vector isn't?
It would be incredibly annoying if I had to change the vec3's to vec3 pointers
| The problem is not in pass-by-reference into the function, but in the for loop. It should use a reference to the vector elements:
for (glm::vec3& vertex : base)
|
69,365,044 | 69,365,426 | Recreating swapchain vs using dynamic state on resize | I have a vulkan application that uses GLFW as its window manager.
Upon the window resize event, vulkan needs to update its drawable area. I have seen 2 ways that this is possible. One is to recreate the swapchain alongside all of the other objects that are tied to it and the other is to use dynamic state for the viewport so that recreation is not needed.
What is the difference between these two and when should I prefer one over the other?
| If the window is resized to a smaller size, the display engine may not force you to change your swapchain image sizes. It may inform you of this through the VK_SUBOPTIMAL_KHR error code (though it may not give you even that if performance of presenting is not affected). However, if the window is resized to be larger, the display engine may throw VK_ERROR_OUT_OF_DATE_KHR. That is not something you can ignore. Nor is it something a display engine can promise to never give you.
This means your code must be able to do swapchain rebuilding. Since you have to make allowances for this regardless, the only question is whether you do it whenever the window is resized or just when the display engine forces you to.
I would say that, if the display engine doesn't make you rebuild the swapchain, then it's probably faster not to. Using dynamic state isn't particularly slower than pipeline state, and its not like you're going to be changing it mid-frame. Indeed, you shouldn't rebuild all of your pipelines just because the swapchain was resized, so you should be using dynamic state for the viewport anyway.
In short: you ought to do both.
|
69,365,230 | 69,365,526 | How to set value in c++ unordered_map and return reference? | So this is silly:
Nodes[pos] = node;
return &Nodes[pos];
because I insert and then do a lookup. I tried like this:
return &Nodes.emplace(pos, node).first->second;
but it doesn't return the reference.
| You can use insert/emplace like this:
int& f1(std::unordered_map<int, int>& m) {
auto [iterator, was_inserted] = m.insert({10, 100});
return iterator->second;
}
operator[] can also create the key if it doesn't exist, so you can also do:
int& f2(std::unordered_map<int, int>& m) {
auto& node = m[10];
node = 100;
return node;
}
|
69,365,580 | 69,365,756 | My Visual Studio can't find files and so can't do basic operations. What's wrong with it? | Using C++, if I launch an 'empty project', create a new C++ file, and try to run it, I just get this error message:
Unable to run program 'C:\Users\User\source\repos\Project2\Debug\Project2.exe' The system cannot find the file specified
I go to the file it's referencing and the file IS there -- what??
Using a 'Console App' project is different: it will actually compile and run the code.
Similarly, I can't join new header files to the main file, not even in a 'Console App' project: if I write the code for doing #include "Header.h", I get a red line underneath #include, and if I hover over that it says:
cannot open source file "Header.h"
I'm new to coding, and don't know why I'm having such a seemingly absurd problem here. Help!
| From the result you described, I suspect you used File -> New file to add that cpp file, right? This does NOT add that file to a project.
Instead, you should right-click the Project file in the Solution explorer, select Add new item (or Project -> Add new item menu), and choose the C++ file type.
This works!
|
69,365,601 | 69,367,870 | CMake: check for standard library file using CheckIncludeFileCXX | I am trying to figure out if the current compiler supports std::format, however the following code is populating the variable CXX_FORMAT_SUPPORT with nothing. I assume I may need to add an include path, but I'm not sure how to get that for the compiler if that is the case.
# check std::format support
include(CheckIncludeFileCXX)
check_include_file_cxx("format" CXX_FORMAT_SUPPORT)
message(STATUS "CXX_FORMAT_SUPPORT: ${CXX_FORMAT_SUPPORT}")
How can I correctly populate CXX_FORMAT_SUPPORT?
| The documentation is less than clear but check_include_file_cxx sets the output variable to 1 if the header is found and doesn't set the variable if it is not found.
|
69,365,927 | 69,366,788 | add a new button in a QWidget in Qt5 | I am trying to add a new QPushButton to a QWidget, but it doesn't seem to have an addWiget method.
I am using the following code:
QWidget *wdg = new QWidget;
QPushButton *btn=new QPushButton(this);
btn->setText("text");
wdg->addWidget(btn)
wdg->show();
hide();
the 6th line is giving an error
| You can pass QWidget as parent to QPushButton.
QWidget *wdg = new QWidget;
QPushButton *btn=new QPushButton(wdg);
|
69,366,623 | 69,367,527 | std::scoped_lock - vector of mutexes? | How can I apply a std::scoped_lock on a std::vector<std::mutex>? I've tried:
std::vector<std::mutex> mutexes;
std::scoped_lock lock{ mutexes }; // doesn't work
std::scoped_lock lock{ ...mutexes }; // doesn't work
| A global mutex shared between the output function and sources was the best solution.
|
69,367,313 | 69,367,355 | How to check international filepath symbols on correctness? | In my c++ linux application I load a file with file list.
Every single line is a full path to some file (utf32) and can have international symbols.
Is there a way check these lines for character correctness? Maybe some library?
Need to avoid emoji or symbols like that.
These files are outside, so I cannot check each of them for availability.
Thanks in advance.
| I would say in general "yes", but your question is very vague. If international characters are allowed, that opens up thousands of character (code points, in Unicode parliance) for use.
Filtering out some set is of course possible, but it's going to be tricky to define that set in a way that works for everyone.
I would recommend against it, just let the filenames be free, don't try to validate them.
|
69,368,754 | 69,385,491 | how to use strip in conjunction with split-dwarf? | I am currently trying to use the --gsplit-dwarf gcc flag in order to automatically create and separate debug symbols from build libraries/executables. More info on DWARF Obj files. However, what I have observed is that split-dwarf still leaves a lot of unnecessary information in the remaining .o file. What I would like to do is use strip to remove that info but still have it be compatible for debugging using the .dwo/.dwp files; however, it seems that this does not work. I want to strip the release executables for space savings and for further obfuscation, and was hoping split-dwarf would allow me to do so.
Additional reference
Example app app.cpp
int main()
{
int a = 1;
std::cout << "Split DWARF test" << std::endl;
return 0;
}
Compiling:
g++ -c -gsplit-dwarf app.cpp -o app_dwarf.o
Linking:
g++ app_dwarf.o -o app_dwarf -fuse-ld=gold -Wl,--gdb-index
Examine the build artifact:
readelf -wi app_dwarf
Contents of the .debug_info section:
Compilation Unit @ offset 0x0:
Length: 0x30 (32-bit)
Version: 4
Abbrev Offset: 0x0
Pointer Size: 8
<0><b>: Abbrev Number: 1 (DW_TAG_compile_unit)
<c> DW_AT_low_pc : 0x8da
<14> DW_AT_high_pc : 0x9c
<1c> DW_AT_stmt_list : 0x0
<20> DW_AT_GNU_dwo_name: (indirect string, offset: 0x0): app_dwarf.dwo
<24> DW_AT_comp_dir : (indirect string, offset: 0xe): /home/ross/Desktop/dwarf_test
<28> DW_AT_GNU_pubnames: 1
<28> DW_AT_GNU_addr_base: 0x0
<2c> DW_AT_GNU_dwo_id : 0xdf705add23e14a0b
Can see it references the dwo... this also works in GDB and does not work when I remove the dwo file. However, if I look at the symbol table for the build artifact (the executable), the full symbol table is still there.
If I strip the executable, the table is removed and the size is reduced, but it also strips away the debug_info that references the dwo file.
Also separately, shouldn't the symbol table be included in the dwo file?
Hoping some direction can be provided here that will allow me to capture all of the debug info outside of the artifact itself to be kept for debugging at a later time.
The alternate way to do this would be a multi stage approach where we do something like:
g++ -g -o app_dwarf app.cpp
objcopy --only-keep-debug app_dwarf app_dwarf.debug
objcopy --add-gnu-debuglink=app_dwarf.debug app_dwarf
strip --strip-unneeded app_dwarf
But would need to divide that up into compile and link steps so that build times and resources are affected less. I thought that was the whole point of the single gsplit-dwarf flag, though.
|
If I strip the executable, the table is removed and the size is reduced, but it also strips away the debug_info that references the dwo file.
Correct.
The right way is to keep the unstripped copy of the executable and the .dwp file, while distributing the stripped copy to end-users.
I thought that was the whole point of the single gsplit-dwarf flag, though.
No.
The motivation is explained here. To quote: "By splitting the debug information into two parts at compile time -- one part that remains in the .o file and another part that is written to a parallel .dwo ("DWARF object") file -- we can reduce the total size of the object files processed by the linker."
If the total size of object files processed by the linker isn't a problem for you (it rarely is for binaries under 1 GiB), then you don't really need fission (though it may still speed up your link a bit).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.