question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,882,694 | 72,901,511 | How to pass [[Int]] into MTLBuffer in Swift and receive it in Metal? | What I'm trying to do
I have an [[Int]] in Swift and I'm trying to pass it into Metal through a buffer. Basically, I'm trying to use Metal to add two matrices multithreaded and give them back to Swift. So far, this is more difficult than expected.
The problem
Metal tells me that my graph isn't a pointer and I suspect I'm passing it into Metal wrong.
import MetalKit
let graph: [[Int]] = [
[0, 1, 2, 999, 999, 999],
[1, 0, 999, 5, 1, 999],
[2, 999, 0, 2, 3, 999],
[999, 5, 2, 0, 2, 2],
[999, 1, 3, 2, 0, 1],
[999, 999, 999, 2, 1, 0]]
func fooFunc(gra: [[Int]]) {
let count = gra.count
let device = MTLCreateSystemDefaultDevice()
let commandQueue = device?.makeCommandQueue()
let gpuFunctionLibrary = device?.makeDefaultLibrary()
let funcGPUFunction = gpuFunctionLibrary?.makeFunction(name: "MetalFunc")
var funcPipelineState: MTLComputePipelineState!
do {
funcPipelineState = try device?.makeComputePipelineState(function: funcGPUFunction!)
} catch {
print(error)
}
let graphBuff = device?.makeBuffer(bytes: gra,
length: MemoryLayout<Int>.size * count * count,
options: .storageModeShared)
let resultBuff = device?.makeBuffer(length: MemoryLayout<Int>.size * count,
options: .storageModeShared)
let commandBuffer = commandQueue?.makeCommandBuffer()
let commandEncoder = commandBuffer?.makeComputeCommandEncoder()
commandEncoder?.setComputePipelineState(additionComputePipelineState)
commandEncoder?.setBuffer(graphBuff, offset: 0, index: 0)
commandEncoder?.setBuffer(resultBuff, offset: 0, index: 1)
let threadsPerGrid = MTLSize(width: count, height: 1, depth: 1)
let maxThreadsPerThreadgroup = additionComputePipelineState.maxTotalThreadsPerThreadgroup // 1024
let threadsPerThreadgroup = MTLSize(width: maxThreadsPerThreadgroup, height: 1, depth: 1)
commandEncoder?.dispatchThreads(threadsPerGrid,
threadsPerThreadgroup: threadsPerThreadgroup)
commandEncoder?.endEncoding()
commandBuffer?.commit()
commandBuffer?.waitUntilCompleted()
let resultBufferPointer = resultBuff?.contents().bindMemory(to: Int.self,
capacity: MemoryLayout<Int>.size * count)
print("Result: \(Int(resultBufferPointer!.pointee) as Any)")
}
gpuDijkstra(gra: graph)
#include <metal_stdlib>
using namespace metal;
kernel void MetalFunc(constant int *graph [[ buffer(0) ]],
constant int *result [[ buffer(1) ]],
uint index [[ thread_position_in_grid ]]
{
const int size = sizeof(*graph);
int result[size][size];
for(int k = 0; k<size; k++){
result[index][k]=graph[index][k]+graph[index][k]; //ERROR: Subscripted value is not an array, pointer, or vector
}
}
| I don't know about the Swift implementation but your kernel function is wrong.
If you want to write to and read from the same buffer you should use Device address space attribute.
The device address space name refers to buffer memory objects
allocated from the device memory pool that are both readable and
writeable.
device int *result /* write and read */
constant int *graph /* read only */
This is the correct implementation:
#include <metal_stdlib>
using namespace metal;
kernel void MetalFunc(constant int *graph [[ buffer(0) ]],
device int *result [[ buffer(1) ]],
uint index [[ thread_position_in_grid ]]
{
/* Point to an array (graph buffer) */
constant int(*r)[6][6] = (constant int(*)[6][6])graph;
/* Point to an array (result buffer) */
device int(*w)[6][6] = (device int(*)[6][6])result;
/* Read the first element */
int i = (*r)[0][0];
(*w)[0][0] = 777; /* Write to the first element */
(*w)[5][5] = 999; /* Write to the last element */
}
|
72,882,815 | 72,882,884 | How to remove the end space in this for loop in c++/cpp? | int n;
cin >> n; cin.ignore();
for(int i = 1; i < 11; i++){
cout << i * n << " ";// stop printing space at the end number
}
Desired output-> "1 2 3 4 5 6 7 8 9 10"
| A simple approach is the following
for( int i = 0; i < 10; i++){
if ( i ) cout << ' ';
cout << ( i + 1 ) * n;
}
or
for( int i = 1; i < 11; i++){
if ( i != 1 ) cout << ' ';
cout << i * n;
}
|
72,884,093 | 72,910,535 | Fold expression: Replacing specific type but forwarding all others, how to correctly specialise `std::forward`? | I've trying to replace a specific type within a fold expression while simply forwarding all other types, but failed miserably.
A simulation of std::forward; actually copied GCC's implementation of and just added a bit of output to see what's going on:
namespace test
{
template<typename T>
T&& fw(typename std::remove_reference<T>::type& t) noexcept
{
std::cout << "standard" << std::endl;
return static_cast<T&&>(t);
}
template<typename T>
T&& fw(typename std::remove_reference<T>::type&& t) noexcept
{
std::cout << "standard (r-value)" << std::endl;
static_assert
(
!std::is_lvalue_reference<T>::value,
"template argument substituting T is an lvalue reference type"
);
return static_cast<T&&>(t);
}
}
As std::forward requires explicit template specialisation I tried providing another set of templated overloads for, but these haven't been considered for overload resolution and would, if that had worked, have led to ambiguous function calls anyway.
So I tried specialising the forwarding templates (well aware that specialising std::forward itself would, as in a header, have lead to replacements where they shouldn't occur) – let's say for std::string. Still, out of pure curiosity (I discovered actually not needing the variadic template thus could work with constexpr if's inside the function instead, so no XY-problem – any more), how would I do so?
This attempt, trying to give an overload for every possible reference type (ambiguities might be solved by dropping one of) failed miserably:
namespace test
{
template<>
std::string const& fw<std::string const>(std::string const& t) noexcept
{
std::cout << "specialised const" << std::endl;
return t;
}
#if 0
template<>
std::string& fw<std::string>(std::string& t) noexcept
{
std::cout << "specialised non-const" << std::endl;
return t;
}
#endif
template<>
std::string && fw<std::string>(std::string&& t) noexcept
{
std::cout << "specialised r-value" << std::endl;
return std::move(t);
}
}
Test code for:
int main()
{
test::fw<int>(7);
int n;
test::fw<int>(n);
test::fw<std::string>(std::string("alda"));
std::string s("daal");
test::fw<std::string>(s);
return 0;
}
should provide output
standard
standard
specialised r-value
specialised non-const
Just one single overload for l-value references would be just as fine.
Instead compilation fails with error
<source>:27:20: error: template-id 'fw<const std::string>' for 'const std::string& test::fw(const std::string&)' does not match any template declaration
27 | std::string const& fw<std::string const>(std::string const& t) noexcept
| ^~~~~~~~~~~~~~~~~~~~~
<source>:15:5: note: candidates are: 'template<class T> T&& test::fw(typename std::remove_reference<_Tp>::type&&)'
15 | T&& fw(typename std::remove_reference<T>::type&& t) noexcept
| ^~
<source>:8:5: note: 'template<class T> T&& test::fw(typename std::remove_reference<_Tp>::type&)'
8 | T&& fw(typename std::remove_reference<T>::type& t) noexcept
| ^~
Template declaration doesn't match (see godbolt as well) – obviously only for the l-value reference overload, though, but I cannot tell why, as there is a generic overload for typename std::remove_reference<T>::type&.
Provided I could specialise accordingly, then I could just re-implement std::forward within my own namespace, provide the specialisations and then use all these – leading to the final question: How can I achieve this without re-implementing std::forward from scratch? (Please follow the link).
| To be noted in advance: This attempt is entirely illegal since C++ 20 and illegal for the given use case (replacing std::string) as well as template specialisations for standard types have been illegal even before C++20 (thanks @Nimrod for the hint and reference to the standard).
Note, too, that even for custom types (before C++20) there are better approaches to replace one specific type (see e.g. here), so this approach should not be followed anyway (I personally only attempted to complete it out of curiosity).
The actual problem (that I missed) is that in template argument deduction in case of l-value references T is decuced to a reference type. Thus for l-value references the template parameter must be turned into a reference as well:
template<>
std::string const& fw<std::string const&>(std::string const& t) noexcept;
// ^ (!)
template<>
std::string& fw<std::string&>(std::string& t) noexcept;
// ^ (!)
Et voilà, code compiles and for the test code as presented prints the desired output provided one selects the appropriate overloads as well:
int n = 7;
test::fw<int&>(n);
// ^ (!)
std::string s("alda");
test::fw<std::string&>(s); // alternatively const overload
// ^ (!)
An interesting fact is that these overloads apparently don't seem to work within the following demo:
template <typename ... T>
void demo(T&&... t)
{
using test::fw;
( fw<T>(t), ... );
std::cout << std::endl;
( fw<T>(std::forward<T>(t)), ... );
}
prints
standard l-value
standard l-value
standard l-value
specialised non-const
standard r-value
standard l-value
specialised r-value
specialised non-const
seeming to require another std::forward – but in fact, all function arguments within demo are indeed l-values and thus the standard version needs to be called. In case of r-values T is deduced to non-reference, though, and resulting return type gets T&&, i. e. the r-value reference just as desired. However the standard version getting called for r-value std::string reveals that for replacing that type entirely one overload is yet lacking:
template<>
std::string&& fw<std::string>(std::string& t) noexcept
{
std::cout << "specialised r-value" << std::endl;
return std::move(t);
}
While the r-value reference overload remains valid for cases where an intermediate function call returns such one (like the std::forward in second test call).
|
72,884,111 | 72,885,119 | Fold expression: Replacing specific type but forwarding all others: How to achieve this? | I've trying to replace a specific type within a fold expression while simply forwarding all other types, but failed miserably.
As std::forward requires explicit template specialisation I tried providing another set of templated overloads for, but these haven't been considered for overload resolution and would, if that had worked, have led to ambiguous function calls anyway.
Second attempt was specialising std::forward but already failed in the attempt...
A simulation of std::forward; actually copied GCC's implementation of and just added a bit of output to see what's going on:
namespace test
{
template<typename T>
constexpr T&&
fw(typename std::remove_reference<T>::type& t) noexcept
{
std::cout << "standard" << std::endl;
return static_cast<T&&>(t);
}
template<typename T>
constexpr T&&
fw(typename std::remove_reference<T>::type&& t) noexcept
{
std::cout << "standard (r-value)" << std::endl;
static_assert
(
!std::is_lvalue_reference<T>::value,
"template argument substituting T is an lvalue reference type"
);
return static_cast<T&&>(t);
}
}
My test is as follows:
class Test
{
public:
template <typename ... T>
void test(T&& ... t)
{
using test::fw;
///////////////////////////////////////////////////
( g(fw<T>(t)), ... );
///////////////////////////////////////////////////
}
private:
template <typename T>
T&& g(T&& t)
{
std::cout << "g: r-value: " << t << '\n' << std::endl;
return std::move(t);
}
template <typename T>
T& g(T& t)
{
std::cout << "g: l-value " << t << '\n' << std::endl;
return t;
}
};
int main()
{
int nn = 10;
Test t;
std::string s("daal");
t.test(12, nn, std::string("alda"), s);
return 0;
}
As is (and with my failed attempts, see linked questions) the output is:
standard
g: r-value: 12
standard
g: l-value 10
standard
g: r-value: alda
standard
g: l-value daal
Desired output would be something like:
standard
g: r-value: 12
standard
g: l-value 10
specialised (r-value)
g: r-value: alda
specialised (l-value)
g: l-value daal
(Reference type is optional.)
How could I achieve this?
Intention is to retain the fold-expression – I could solve the issue with recursive templates and appropriate overloads, but that's not the intention here. This is a question out of pure curiosity as I already solved my actual problem already (by discovering actually not needing the variadic template at all thus could work with if constexpr inside the function instead, and thus no XY-problem either – any more).
| if constexpr within a wrapper is the key to the solution (thanks @user17732522 for the hint), however it needs to be combined with a second std::forward and for not receiving only r-value[s| references] decltype(auto) as well. Such a function can even be included within the Test class, additionally desired but optional feature (a lambda within the test function might look like...).
A solution might look like:
class Test
{
template <typename T>
///////////////////////////////////////////////////
// note: decltype(auto)!
///////////////////////////////////////////////////
static decltype(auto) fw(T&& t)
{
if constexpr(std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, std::string>)
{
std::cout << "std::string: ";
if constexpr(std::is_lvalue_reference_v<decltype(t)>)
{
std::cout << "l-value\n";
std::string s;
s.reserve(t.length() + 2);
s += '\'';
s += t;
s += '\'';
return s;
}
else
{
std::cout << "r-value\n";
t.reserve(t.length() + 2);
t.insert(t.begin(), '\'');
t.push_back('\'');
return t;
}
}
else
{
std::cout << "default\n";
return std::forward<T>(t);
}
}
public:
template <typename ... T>
void test(T&& ... t)
{
///////////////////////////////////////////////////
// note: yet another call to std::forward!
///////////////////////////////////////////////////
( g(fw(std::forward<T>(t))), ... );
}
private:
template <typename T>
T&& g(T&& t)
{
std::cout << "g: r-value: " << t << '\n' << std::endl;
return std::move(t);
}
template <typename T>
T& g(T& t)
{
std::cout << "g: l-value " << t << '\n' << std::endl;
return t;
}
};
int main()
{
int n = 10;
Test t;
std::string s("daal");
t.test(12, n, std::string("alda"), s);
std::cout << std::endl;
return 0;
}
(Modifying the strings simulates conversion to another type...)
Received output (as desired):
default
g: r-value: 12
default
g: l-value 10
std::string: r-value
g: l-value 'alda'
std::string: l-value
g: r-value: 'daal'
(auto instead of decltype(auto) prints g: r-value four times!)
|
72,884,815 | 72,889,919 | How to stream frames from OpenCV C++ code to Video4Linux or ffmpeg? | I am experimenting with OpenCV to process frames from a video stream. The goal is to fetch a frame from a stream, process it and then put the processed frame to a new / fresh stream.
I have been able to successfully read streams using OpenCV video capture functionality. But do not know how I can create an output stream with the processed frames.
In order to do some basic tests, I created a stream from a local video file using ffmpeg like so:
ffmpeg -i sample.mp4 -v 0 -vcodec mpeg4 -f mpegts \
"udp://@127.0.0.1:23000?overrun_nonfatal=1&fifo_size=50000000"
And in my C++ code using the VideoCapture functionality of the OpenCV library, I am able to capture the above created stream. A basic layout of what I am trying to achieve is attached below:
cv::VideoCapture capture("udp://@127.0.0.1:23000?overrun_nonfatal=1&fifo_size=50000000", cv::CAP_FFMPEG);
cv::Mat frame;
while (true)
{
// use the above stream to capture a frame
capture >> frame;
// process the frame (not relevant here)
...
// finally, after all the processing is done I
// want to put this frame on a new stream say at
// udp://@127.0.0.1:25000, I don't know how to do
// this, ideally would like to use Video4Linux but
// solutions with ffmpeg are appreciated as well
}
As you can see from comment in above code, I don't have any idea how I should even begin handling this, I tried searching for similar questions but all I could find was how to do VideoCapture using streams, nothing related to outputting to a stream.
I am relatively new to this and this might seem like a very basic question to many of you, please do excuse me.
| We may use the same technique as in my following Python code sample.
Execute FFmpeg as sub-process, open stdin pipe for writing
FILE *pipeout = popen(ffmpeg_cmd.c_str(), "w")
Write frame.data to stdin pipe of FFmpeg sub-process (in a loop)
fwrite(frame.data, 1, width*height*3, pipeout);
Close the pipe at the end (it is going to close the sub-process)
pclose(pipeout);
The following sample is a generic example - building numbered frames, and writing the encoded video to an MKV output file.
The example uses the following equivalent command line:
ffmpeg -y -f rawvideo -r 10 -video_size 320x240 -pixel_format bgr24 -i pipe: -vcodec libx264 -crf 24 -pix_fmt yuv420p output.mkv
You may adjust the arguments for your specific requirements (replace output.mkv with udp://@127.0.0.1:25000).
Replace the numbered frame with capture >> frame, and adjust the size and framerate.
Code sample:
#include <stdio.h>
#include <chrono>
#include <thread>
#include "opencv2/opencv.hpp"
int main()
{
int width = 320;
int height = 240;
int n_frames = 100;
int fps = 10;
//Use a "generic" example (write the output video in output.mkv video file).
//ffmpeg -y -f rawvideo -r 10 -video_size 320x240 -pixel_format bgr24 -i pipe: -vcodec libx264 -crf 24 -pix_fmt yuv420p output.mkv
std::string ffmpeg_cmd = std::string("ffmpeg -y -f rawvideo -r ") + std::to_string(fps) +
" -video_size " + std::to_string(width) + "x" + std::to_string(height) +
" -pixel_format bgr24 -i pipe: -vcodec libx264 -crf 24 -pix_fmt yuv420p output.mkv";
//Execute FFmpeg as sub-process, open stdin pipe (of FFmpeg sub-process) for writing.
//In Windows we need to use _popen and in Linux popen
#ifdef _MSC_VER
FILE *pipeout = _popen(ffmpeg_cmd.c_str(), "wb"); //Windows (ffmpeg.exe must be in the execution path)
#else
//https://batchloaf.wordpress.com/2017/02/12/a-simple-way-to-read-and-write-audio-and-video-files-in-c-using-ffmpeg-part-2-video/
FILE *pipeout = popen(ffmpeg_cmd.c_str(), "w"); //Linux (assume ffmpeg exist in /usr/bin/ffmpeg (and in path).
#endif
for (int i = 0; i < n_frames; i++)
{
cv::Mat frame = cv::Mat(height, width, CV_8UC3);
frame = cv::Scalar(60, 60, 60); //Fill background with dark gray
cv::putText(frame, std::to_string(i+1), cv::Point(width/2-50*(int)(std::to_string(i+1).length()), height/2+50), cv::FONT_HERSHEY_DUPLEX, 5, cv::Scalar(30, 255, 30), 10); // Draw a green number
cv::imshow("frame", frame);cv::waitKey(1); //Show the frame for testing
//Write width*height*3 bytes to stdin pipe of FFmpeg sub-process (assume frame data is continuous in the RAM).
fwrite(frame.data, 1, width*height*3, pipeout);
}
// Flush and close input and output pipes
fflush(pipeout);
#ifdef _MSC_VER
_pclose(pipeout); //Windows
#else
pclose(pipeout); //Linux
#endif
//It looks like we need to wait one more second at the end. //https://stackoverflow.com/a/62804585/4926757
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // sleep for 1 second
return 0;
}
|
72,885,072 | 72,885,790 | How conversion of pointer-to-base to void is better than pointer-to-derived to void conversion | [over.ics.rank]/4:
[..]
(4.3) If class B is derived directly or indirectly from class A, conversion of B* to A* is better than conversion of B* to void*, and conversion of A* to void* is better than conversion of B* to void*.
So if I have:
struct A {};
struct M : A {};
struct B : M {};
void f(A*);
void f(void*);
int main()
{
B *bptr = new B();
f(bptr);
}
The call f(bptr) would prefer the overload f(A*) over f(void*).
But in the second case: conversion of A* to void* is better than conversion of B* to void*. How this conversion can occur? Can you give me an example that triggers this case?
For some reasons I can't finds out a case or an example in which this case is applied. It seems like comparing two unrelated things to each other. But I encounter more in the bullet 4.4.
You can check the whole thing from cppreference para 4:
If Mid is derived (directly or indirectly) from Base, and Derived
is derived (directly or indirectly) from Mid
a) Derived* to Mid* is better than Derived* to Base*
b) Derived to Mid& or Mid&& is better than Derived to Base& or Base&&
c) Base::* to Mid::* is better than Base::* to Derived::*
d) Derived to Mid is better than Derived to Base
e) Mid* to Base* is better than Derived* to Base*
f) Mid to Base& or Base&& is better than Derived to Base& or Base&&
g) Mid::* to Derived::* is better than Base::* to Derived::*
h) Mid to Base is better than Derived to Base
| The situation where you have to compare different possible source types (A* vs B* in A* -> void* and B* -> void*) can only happen in the context of overload resolution for initialization by user-defined conversion, not in the context of overload resolution for a function call. See also the note at the end of [over.ics.rank]/4.
Here is an example where the quoted phrase is relevant:
struct A {};
struct B : A {};
struct C {
operator A*();
operator B*();
};
int main() {
void* x = C{};
}
Here x is initialized by a conversion function chosen according to [over.match.conv] (see [dcl.init.general]/16.7). All conversion operators converting from C to any type which is convertible to void* by a standard conversion sequence are considered.
Then the best conversion function is chosen according to which of the standard conversion sequences following the conversion function is better (see [over.match.best.general]/2.2).
The phrase you quote tells us that A* -> void* is better than B* -> void*. So the conversion function which will be used here to initialize x is operator A*().
|
72,885,134 | 72,897,111 | Pybind11 pointer reference | I'm trying to use a c++ function, that takes a pointer as an argument, in python.
For the facade I'm using pybind11 and ctypes in python in order to create pointers.
However the adress I'm getting in python isn't equal to the one in c++.
I do need the adress of a variable later in the project and i cant get it by return, since the function is already returning something else.
c++ function
void myFunc(double* ptr, double value)
{
*ptr = value;
std::cout << "ptr value:\t\t" << *ptr << std::endl;
std::cout << "ptr adress:\t\t" << ptr << std::endl;
};
pybind code
m.def("myFunc",
[](double* ptr,
double value) {
myFunc(ptr, value);
}, "funtion to test stuff out");
python code
ptr_value = ctypes.c_double()
ptr_addressof = ctypes.addressof(ptr_value)
ptr_object_pointer = pointer(ptr_value)
ptr_pointer = ctypes.cast(ptr_object_pointer, ctypes.c_void_p).value
print(f'python ptr using addressof(ptr_value):\t\t{ptr_addressof}')
print(f'python adress using ctypes.cast:\t\t{ptr_pointer}')
print(f'python ptr object using pointer(ptr_value):\t{ptr_object_pointer}')
value = 14.0
myFunc(ptr_addressof, value)
output
python ptr using addressof(ptr_value): 2784493684616
python adress using ctypes.cast: 2784493684616
python ptr object using pointer(ptr_value): <__main__.LP_c_double object at 0x0000028850C1C8C0>
ptr value: 14
ptr adress: 000000CC2D3EE490
How do I get the same adress in c++ and python?
| I was able to fix the Issue. It was just an error in my thinking process.
Pybind now looks like this
m.def("myFunc",
[](double value) {
void *pointer;
otherValue = myFunc(&pointer, value);
return std::make_tuple(pointer, otherValue);
}, "funtion to test stuff out");
Note that this is kinda similar to something i was trying before. I was confused because the output when printing the pointer variable in python was object at adress xxx. The adress however didn't represent the c++ adress but the adress of the variable in python.
Now i can call other cpp functions that are taking a pointer as an input with the returned pointer as an argument and it works just fine.
The c++ function takes a pointer pointer as an argument and then changes the value of the adress, that the input pointer is refering to, to an object that will be used later in the program.
void myFunc(void **ptr, double value)
{
*ptr = &value;
};
|
72,887,122 | 72,888,146 | Can't send Message from Server( C++ Socket) | I'm new to C++ Socket and my Server can't send message to its client. The send() function return -1 always and it seems to have a problem with accpSocket. However Client can do that smoothly and I don't know what's wrong. Please help me thank you so much!
Server
#include<WinSock2.h>
#include<WS2tcpip.h>
#include<iostream>
#include<sdkddkver.h>
#include<winsock.h>
using namespace std;
int main() {
SOCKET serverSocket, acceptSocket = INVALID_SOCKET;
int port = 2403;
WSADATA wsaData;
int wsaerr;
//Step 1: Set up dll
WORD versionRequested = MAKEWORD(2, 2);
wsaerr = WSAStartup(versionRequested, &wsaData);
if (wsaerr)
cout << "The winsock dll not found";
else {
cout << "The winsock dll found\n";
cout << "Winsock dll status: " << wsaData.szSystemStatus << endl;
}
//Step 2: Set up server socket
serverSocket = INVALID_SOCKET;
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
cout << "Error at socket: " << WSAGetLastError();
WSACleanup();
return 0;
}
else
cout << "Server socket successfull!\n";
//Step 3: Binding socket
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.S_un.S_addr = INADDR_ANY;
service.sin_port = htons(port);
if (bind(serverSocket, (sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) {
cout << "Binding failed! " << WSAGetLastError();
return 0;
}
else
cout << "Binding complete!\n";
// Step 4: Listen to the connections
if (listen(serverSocket, 1) == SOCKET_ERROR) {
cout << "Listen failed! " << WSAGetLastError();
return 0;
}
else
cout << "Waiting for connections ...";
SOCKET accpSocket = accept(serverSocket, NULL, NULL);
if (accpSocket == INVALID_SOCKET) {
cout << "Accepting failed! " << WSAGetLastError();
WSACleanup();
return -1;
}
else
cout << "Accept connection!\n";
char recvMess[2000];
char sendMess[2000];
int byterecv = recv(accpSocket, recvMess, sizeof(recvMess), 0);
cout << "Client: " << recvMess << endl;
cout << "Server: ";
cin.getline(sendMess, 2000);
int bytesend = send(acceptSocket, sendMess, 2000, 0);
if (bytesend <= 0)
cout << "Unsent";
return 0;
}
Client
#include<iostream>
#include<WinSock2.h>
#include<WS2tcpip.h>
using namespace std;
int main() {
int port = 2403;
WSADATA wsaData;
int wsaerr;
SOCKET clientSocket;
WORD versionRequested = MAKEWORD(2, 2);
wsaerr = WSAStartup(versionRequested, &wsaData);
if (wsaerr)
cout << "Winsock dll not found!";
else {
cout << "Winsock dll is ok!\n";
cout << "Status: " << wsaData.szSystemStatus << endl;
}
clientSocket = INVALID_SOCKET;
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
cout << "Set up client socket failed" << WSAGetLastError();
WSACleanup();
return 0;
}
else
cout << "Set up complete!\n";
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_port = htons(port);
if (inet_pton(clientService.sin_family, "127.0.0.1", &clientService.sin_addr) <= 0) {
cout << "Invalid address!";
return -1;
}
if ((connect(clientSocket, (SOCKADDR*)&clientService, sizeof(clientService))) == SOCKET_ERROR) {
cout << "Connection failed!\n";
WSACleanup();
return 0;
}
else
cout << "Connection complete!\n";
char sendMess[2000];
char recvMess[2000];
cout << "Client: ";
cin.getline(sendMess, 2000);
int bytesend = send(clientSocket, sendMess, 2000, 0);
int byterecv = recv(clientSocket, recvMess, 2000, 0);
if (byterecv <= 0)
cout << "Nothing";
else
cout << "Server" << recvMess << endl;
return 0;
}
| int bytesend = send(acceptSocket, sendMess, 2000, 0);
is not sending to a connected socket. acceptSocket was defined at the top of main and then ignored up until the call to send
As a general rule of thumb, keep variable definition close to first use.
In the server at
SOCKET serverSocket, acceptSocket = INVALID_SOCKET;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Killlllll meeeeee!!!!
remove acceptSocket to prevent future mistakes and in
int bytesend = send(acceptSocket, sendMess, 2000, 0);
replace acceptSocket with the socket that was actually accepted, accpSocket.
Side notes:
Never ignore the return codes.
int byterecv = recv(accpSocket, recvMess, sizeof(recvMess), 0);
could fail and return -1 or return 0 if the socket was disconnected, yet the program will still
cout << "Client: " << recvMess << endl;
And worse, there's no guarantee that recvMess will be null-terminated, recv on a streaming socket gives you what the socket has available or becomes available up to the maximum number of bytes requested, so if there is any data read, make sure byterecv is a valid index in recvMess by only reading sizeof(recvMess) - 1 bytes and then forcing termination with recvMess[byterecv] = '\0'; before printing.
send(acceptSocket, sendMess, 2000, 0); sends all 2000 bytes of sendMess regardless of how many bytes were read with cin.getline(sendMess, 2000);. Use
send(acceptSocket, sendMess, cin.gcount(), 0);
instead. Add on an extra byte (cin.gcount() + 1) if you want to send the null terminator.
|
72,887,333 | 72,987,279 | Detect that a struct contains a flexible array member | Say that I have a struct like this
struct foo
{
int n;
int values[];
};
Is it possible to detect the flexible array member using SFINAE? At least, I can construct a class template that cannot be instantiated with such struct:
template<class T>
struct invalid_with_fam
{
T x;
int unused;
};
If I try to create an invalid_with_fam<foo>:
<source>:14:23: required from here
<source>:11:9: error: flexible array member 'foo::data' not at end of 'struct invalid_with_fam<foo>'
11 | int data[];
| ^~~~
<source>:5:9: note: next member 'int invalid_with_fam<foo>::unused' declared here
5 | int unused;
| ^~~~~~
<source>:2:8: note: in the definition of 'struct invalid_with_fam<foo>'
2 | struct invalid_with_fam
So now I want to use that so I can disable a template for any such struct. Since this is a non-standard feature, I should mention that I target gcc. Notice that I do not ask whether or not flexible array members are possible. I assume they are, but want to disable certain templated functions based on the fact that it contains such arrays. Example:
template<class T>
void do_stuff(T const& x)
{
//...
y = x; // Slicing would occur here!!!
//...
}
Thus, it should be a compilation error to use do_stuff with T=foo.
For this to work, I assume that there has to be a way to trigger SFINAE on an invalid type. invalid_with_fam<foo> cannot exist, because the data member after will require an undefined memory layout (is unused part of the array or not?). So if SFINAE works to detect that the class template cannot be instantiated it should work.
| There are no FAMs in C++. Any support given by the compilers to this non-standard feature is likely to be inconsistent and not integrate well with the rest of C++.
Having said that, we can pretend that a FAM is normal C++ code and try to detect it using SFINAE.
Unfortunately it doesn't work, because only errors in so-called "immediate context" are SFINAE-friendly. The standard does not give a definition to the notion of "immediate context", but it is more or less clear (in particular from this note) that innards of a class being instantiated is not it.
So the answer is no, it is not detectable using SFINAE using a template similar to invalid_with_fam. Perhaps there are other contexts in which a FAM struct cannot be used and which can be embedded into the "immediate context" of the substitution, but I am not aware of any.
|
72,887,465 | 72,901,012 | SCons: ld cannot find standard libraries | I'm developing a game with raylib using SCons for building. I'm using Clang to cross compile from Ubuntu (in WSL) to Windows. My project directory contains a lib directory with the raylib binaries and an include directory with the raylib headers. When I run SCons I get this output:
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
clang++ -o main.o -c -mwindows --target=x86_64-w64-windows-gnu -static -static-libgcc -static-libstdc++ -Iinclude main.cpp
clang: warning: argument unused during compilation: '-mwindows' [-Wunused-command-line-argument]
clang: warning: argument unused during compilation: '-static-libgcc' [-Wunused-command-line-argument]
clang: warning: argument unused during compilation: '-static-libstdc++' [-Wunused-command-line-argument]
clang++ -o tiled_test.exe main.o -Llib -lraylib -lopengl32 -lgdi32 -lwinmm
/bin/ld: cannot find -lopengl32
/bin/ld: cannot find -lgdi32
/bin/ld: cannot find -lwinmm
clang: error: linker command failed with exit code 1 (use -v to see invocation)
scons: *** [tiled_test.exe] Error 1
scons: building terminated because of errors.
ld can't find opengl32, gli32, and winmm.
My SConstruct file:
import os
LIBS=['raylib', 'opengl32', 'gdi32', 'winmm']
LIBPATH='./lib'
CCFLAGS='-mwindows --target=x86_64-w64-windows-gnu -static -static-libgcc -static-libstdc++'
env = Environment(CXX='clang++', CPPPATH='./include')
env['ENV']['TERM'] = os.environ['TERM'] # Colored output
env.Program('tiled_test.exe', 'main.cpp', LIBS=LIBS, LIBPATH=LIBPATH, CCFLAGS=CCFLAGS)
When I run Clang++ directly it works perfectly.
clang++ main.cpp -o tiled_test.exe -Iinclude -Llib -mwindows --target=x86_64-w64-windows-gnu -static -static-libgcc -static-libstdc++ -lraylib -lopengl32 -lgdi32 -lwinmm
| I found the answer to my problem. According the this by default SCons doesn't use the shell's PATH. The user needs to add it to the environment.
My fixed SConstruct file:
import os
LIBS=['raylib', 'opengl32', 'gdi32', 'winmm']
LIBPATH='./lib'
CCFLAGS='-static --target=x86_64-w64-windows-gnu'
LINKFLAGS = '-mwindows --target=x86_64-w64-windows-gnu -static-libgcc -static-libstdc++'
env = Environment(CXX='clang++', CPPPATH='./include', tools = ['mingw'], ENV = {'PATH' : os.environ['PATH']})
env['ENV']['TERM'] = os.environ['TERM'] # Colored output
env.Program('tiled_test.exe', 'main.cpp', LIBS=LIBS, LIBPATH=LIBPATH, CCFLAGS=CCFLAGS, LINKFLAGS=LINKFLAGS)
|
72,887,668 | 72,887,857 | Unable to find error in Leetcode 733.Flood Fill | I am getting the error below for this question in Leetcode, but I am unable to spot the error.
Question:
https://leetcode.com/problems/flood-fill/
class Solution {
public:
int visited[50][50]={0};
vector<vector<int>> helper(vector<vector<int>>& image, int sr, int sc, int color, int c) {
int n = image.size();
int m = image[0].size();
image[sc][sr] = color;
visited[sr][sc] = 1;
if(sr>0 and visited[sr-1][sc] == 0 and image[sr-1][sc]==c){
helper(image, sr-1, sc, color, c);
}
if(sc>0 and visited[sr][sc-1] ==0 and image[sr][sc-1]==c){
helper(image, sr, sc-1, color, c);
}
if(sc<m-1 and visited[sr][sc+1] ==0 and image[sr][sc+1]==c){
helper(image, sr, sc+1, color, c);
}
if(sr<n-1 and visited[sr+1][sc]==0 and image[sr+1][sc]==c){
helper(image, sr+1, sc, color, c);
}
return image;
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
int n = image.size();
int m = image[0].size();
return helper(image, sr, sc, color, image[sr][sc]);
}
};
Testcase:
[[0,0,0],[0,0,0]]
0
0
0
Error Message:
=================================================================
==31==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6040000000c0 at pc 0x000000346e0d bp 0x7ffdecd39d20 sp 0x7ffdecd39d18
READ of size 8 at 0x6040000000c0 thread T0
#6 0x7f8371b800b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x6040000000c0 is located 0 bytes to the right of 48-byte region [0x604000000090,0x6040000000c0)
allocated by thread T0 here:
#6 0x7f8371b800b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Shadow bytes around the buggy address:
0x0c087fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c087fff8000: fa fa fd fd fd fd fd fd fa fa 00 00 00 00 00 06
=>0x0c087fff8010: fa fa 00 00 00 00 00 00[fa]fa fa fa fa fa fa fa
0x0c087fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c087fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c087fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c087fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c087fff8060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Shadow gap: cc
==31==ABORTING
| In your code, sr represents the current row and sc represents the current column.
Therefore, this line of code:
image[sc][sr] = color;
should instead be changed to:
image[sr][sc] = color;
|
72,887,855 | 72,888,100 | boost::typeindex::type_id<>().pretty_name() differences for different systems/compilter/boost-versions? | I am trying to run a project where boost::typeindex::type_id<>().pretty_name() is used to transform the classname to a string, to register it in a factory.
For example class A should transform to "A", class B to "B", etc.
This is working in a Linux gcc environment by using boost::typeindex::type_id<A>().pretty_name().
When I try to run the project in Windows with MSVC 14 and Boost 1.78.0 however class names are transformed in this way:
class A transforms to "class A", class B transforms to "class B", and so on...
Is this because of the OS differences or the compiler differences or some boost parameters or boost version differences?
| Boost’s docs state this library is just a wrapper for std::type_info which is purely implementation-dependent, notice how the example on cppreference corresponds to your case.
|
72,888,319 | 72,888,353 | Heap corruption on deleting a pointer twice stored in different classes | Two classes A and B share pointer to a third class C and when either A or B are deleted they call delete C as well.
Issue is not observed when only either of A or B is deleted.
An exception is getting thrown in this scenario. I have specifically tried to set the class C pointer to NULL and have put in a NULL check to avoid this specific scenario but this null check is somehow not working.
I have read around that shared pointer should be used in this case but I am not sure how to implement it properly. It looks like whole code base needs to be changed to include shared_ptr everywhere as all class C objects would be updated to shared_ptr. Is there a way I can use shared_ptr just to store this pointer without changing all the code?
Edit:
I have specifically deleted assignment operator and copy constructor of C to avoid situation both have different pointers due to copying. Can anything else can be done to prevent copying as pointed in answer by john
class A{
C* c;
}
~A(){
if(C != NULL){
delete C;
C = NULL;
}
}
class B{
C* c;
}
~B(){
if(C != NULL){
delete C;
C = NULL;
}
}
| A and B have separate copies of the pointer to C. So setting one classes copy of that pointer to NULL has no effect on the other pointer and you still get a double delete.
You have basically four options
Decide that one class 'owns' the pointer, that class will delete it and the other will not. The danger here is that if the owning class deletes the pointer and then the non-owning class uses the pointer then you are going to get a different kind of error.
Use shared ownership of the pointer, so that it only gets deleted when the last object using it gets destroyed. The easy way to do that is to use std::shared_ptr
#include <memory>
class A {
std::shared_ptr<C> c;
};
class B {
std::shared_ptr<C> c;
};
Clone the pointer before copying it to the second class. Something roughly like
a.c = new C();
b.c = new C(*a.c);
this way both classes get separate (but equal) copies of the C object. But this changes the semantics of your program, maybe you actually want A and B to share the same C object.
This option (suggested by Richard Critten) has class A having a std::shared_ptr and class B having a std::weak_ptr. This means that A owns the C object, and when the last A object has been destroyed the C object will also be destroyed. Any remaining B objects do not prevent the destruction of the C object but, the B object can check whether the C object has been destroyed. In code it looks something like this
#include <memory>
class A
{
std::shared_ptr<C> c;
};
class B
{
std::weak_ptr<C> c;
};
class C
{
C(whatever);
};
A a;
B b;
// create a shared pointer
a.c = std::make_shared<C>(whatever);
// create a weak pointer referring to the same C object
b.c = a.c;
// create a shared pointer from the weak pointer in b
auto c = b.c.lock();
// check if the pointer is valid
if (c)
{
// do something with c
c->something();
}
else
{
// c object has been destroyed
}
|
72,888,329 | 72,888,869 | Idiomatic way of handling const template arguments in function templates | For a framework project I'm working on, I provide an interface for users to access objects through a handle-like interface--i.e. they do not own the objects themselves, but they need to use them.
The class the user cares about looks something like:
template <typename T>
class handle {
public:
using value_type = std::remove_const_t<T>;
using const_pointer = value_type const*;
using const_reference = value_type const&;
// Pointer-like API; const-only access
const_pointer operator->() const noexcept { return ptr_; }
const_reference operator*() const noexcept { return *ptr_; }
// See explanation in post...
template <typename U, typename V>
friend bool operator==(handle<U> u, handle<V> v)
requires std::same_as<typename handle<U>::value_type,
typename handle<V>::value_type>;
// Constructor and other member functions hidden.
private:
const_pointer ptr_;
};
The handle is constructed by the framework, and the user has only const access to the object through the handle. For an int owned by the framework, it is therefore immaterial whether a user specifies (e.g.) handle<int> or handle<int const>, as the interface will be identical for each.
The question is, how do I simply create an equality function that supports potentially const-qualified template arguments. IOW, I need:
handle<int> hi{...};
handle<int const> hic{...};
assert(hi == hic);
The closest I've come up with is to create a free function template that has access to ptr_:
template <typename U, typename V>
bool operator==(handle<U> u, handle<V> v)
requires std::same_as<typename handle<U>::value_type, typename handle<V>::value_type>
{
return u.ptr_ == v.ptr_;
}
But this is a lot of boilerplate! Is there a better way to handle this problem using modern C++?
| You can just write a member comparison:
template <class T>
struct handle {
using value_type = std::remove_const_t<T>;
using const_pointer = value_type const*;
template <class U>
friend struct handle;
template <class U>
// this can be same_as<T const, U const>, etc.
requires std::equality_comparable_with<T*, U*>
bool operator==(handle<U> rhs) const {
return ptr == rhs.ptr;
}
private:
const_pointer ptr;
};
With the new C++20 comparison rules, this is sufficient to give you both homogeneous and heterogeneous == and !=. Demo
A simpler approach would be:
template <class T>
struct handle {
using value_type = T;
using const_pointer = value_type const*;
friend bool operator==(handle, handle) = default;
private:
const_pointer ptr;
};
template <class T> struct handle<T const> : handle<T> { };
Here, handle<int const> and handle<int> are separate types (even if handle<int const> is silly), but handle<int const> is a handle<int> so the inherited comparison just works. Demo.
|
72,888,330 | 72,890,344 | Start a thread with a member function should pass a object or pointer or a reference? | I'm confused about starting a thread with a member function. I know I need to pass a class object as the second parameter. But someone passed the object to the thread(), and someone passed an address, and I had tried to pass a reference. Both of them are compiling OK. So I am confused about which one is correct.
class X
{
public:
void do_lengthy_work(){
std::cout << "1:1" << std::endl;
}
};
int main(){
X my_x;
std::thread t(&X::do_lengthy_work, std::ref(my_x)); // pass reference
std::thread t(&X::do_lengthy_work, &my_x); // pass address
std::thread t(&X::do_lengthy_work, my_x); // pass object
t.join();
return 0;
}
| The thread constructor begins executing the thread according to the rules of std::invoke. So all 3 of the lines of code you show will do something.
The first two lines (ref and pointer) are fine if you expect the lifetime of the object to be longer than the lifetime of the thread. As you can see from the link to std::invoke above, they are equivalent. Otherwise, the third line copies the object into the thread. This means that the original object now doesn't matter and can be destroyed, but also means that any results will not be visible in the the original object, only the copy.
|
72,888,504 | 72,888,572 | C++ how to declare bitwise operators for different types of flags? | First, my flags set is an enum like this:
typedef enum
{
F0 = 0,
F1 = 1,
F2 = 2,
F3 = 4
} Flags1;
In C I can do any bitwise operations on them, but not in C++.
So I have the macro:
#define BIT_FLAG_OPERATORS(flags)\
inline flags operator ~(flags a) { return static_cast<flags>(~static_cast<int>(a)); }\
inline flags operator &(flags a, flags b) { return static_cast<flags>(static_cast<int>(a) & static_cast<int>(b)); }\
inline flags& operator &=(flags& a, flags b) { return a = a & b; }\
inline flags operator |(flags a, flags b) { return static_cast<flags>(static_cast<int>(a) | static_cast<int>(b)); }\
inline flags& operator |=(flags& a, flags b) { return a = a | b; }\
inline flags operator ^(flags a, flags b) { return static_cast<flags>(static_cast<int>(a) ^ static_cast<int>(b)); }\
inline flags& operator ^=(flags& a, flags b) { return a = a ^ b; }
...and I use it like this:
#ifdef __cplusplus
BIT_FLAG_OPERATORS(Flags1);
#endif
Works.
Then I make another set of flags:
typedef enum
{
F20 = 0,
F21 = 1,
F22 = 2,
F23 = 4
} Flags2;
...and use the macro:
#ifdef __cplusplus
BIT_FLAG_OPERATORS(Flags2);
#endif
...and it doesn't work, I get "conflicting declaration of C function Flags2 operator...".
Why is that and how should I change my macro to be able to apply it for different flags types?
It would be best if it was somehow possible to apply it to ALL enums, so, somehow define the operators for all enum types, not for each type separately. But how?
EDIT:
I got it:
Where my header is included, there is indeed extern "C" {. My header file is included in many places, I just missed that one and was sure there is no extern "C" {. But it was. Thanks to suggestions in comments I found it. That was it.
| So the answer is that what you have already works. It's debatable whether it's a good idea to convert back to an enum, but if that's what you want, then there's nothing wrong with the code you show and it was just another bug, so you might consider deleting the question.
Here's a slightly cleaner working example:
#include <type_traits>
enum Flags1 {
F0 = 0,
F1 = 1,
F2 = 2,
F3 = 4
};
enum Flags2 {
F20 = 0,
F21 = 1,
F22 = 2,
F23 = 4
};
#define BIT_BINARY_OP(Type, Op) \
inline Type \
operator Op(Type a, Type b) \
{ \
return Type(int(a) Op int(b)); \
} \
inline Type& \
operator Op##=(Type &a, Type b) \
{ \
return a = Type(a Op b); \
}
#define BIT_FLAG_OPERATORS(flags) \
inline flags operator~(flags a) { return flags(~int(a)); } \
BIT_BINARY_OP(flags, &) \
BIT_BINARY_OP(flags, ^) \
BIT_BINARY_OP(flags, |)
BIT_FLAG_OPERATORS(Flags1);
BIT_FLAG_OPERATORS(Flags2);
int
main()
{
auto f1 = F1|F2;
f1 |= F3;
[[maybe_unused]] auto f2 = ~(F20|F21);
static_assert(std::is_same_v<decltype(f1), Flags1>);
static_assert(std::is_same_v<decltype(f2), Flags2>);
}
|
72,888,511 | 72,888,538 | How to log FVector in unreal engine | FVector ActorLocation = GetActorLocation();
UE_LOG(LogTemp, Log, TEXT("Actor location: %f"), ActorLocation);
| You can't log an FVector directly. You need to convert it to an FString and then use %s (not %f) and finally operator* for dereferencing.
This should work
UE_LOG(LogTemp, Log, TEXT("Actor location: %s"), *ActorLocation.ToString());
|
72,888,552 | 72,890,280 | How can I share variable values between different classes in C++? | I've created a minimal example to share a variable between classes.
In C# normally I do this by creating a public static class with a public static variable... then I can just access it from everywhere.
Main.cpp
#include <iostream>
#include "TestClass.h"
#include "Shared.h"
int main(int argc, char* argv[])
{
std::cout << "This should print 'Hello'" << std::endl;
std::cout << "Print 1 from main: " << MyNameSpace::MESSAGE << std::endl;
std::cout << "This should print 'Test message 1'" << std::endl;
TestClass test("Test message 1");
std::cout << "Print 2 from main: " << MyNameSpace::MESSAGE << std::endl;
std::cout << "This should print 'Test message 2'" << std::endl;
MyNameSpace::MESSAGE = "Test message 2";
std::cout << "Print 3 from main: " << MyNameSpace::MESSAGE << std::endl;
return 0;
}
Shared.h
#pragma once
#include <string>
namespace MyNameSpace
{
static std::string MESSAGE = "Hello";
}
TestClass.h
#pragma once
#include <string>
#include "Shared.h"
#include <iostream>
class TestClass {
public:
TestClass(const std::string& message);
};
TestClass.cpp
#include "TestClass.h"
TestClass::TestClass(const std::string& message)
{
MyNameSpace::MESSAGE = message;
std::cout << "Print 1 from TestClass: " << MyNameSpace::MESSAGE << std::endl;
}
So, if I set any value, for example MyNameSpace::MESSAGE = "Potato" from any file/class, I want to see Potato in MyNameSpace::MESSAGE from all classes
Here is the output so you can see better:
C:\Users\Adrian\RiderProjects\Test\x64\Debug\Test.exe
Hello:
Print 1 from main: Hello
This should print Test message 1:
Print 1 from TestClass: Test message 1
Print 2 from main: Hello
Test message 2:
Print 3 from main: Test message 2
Process finished with exit code 0.
| Note that in C++ you can define public static variables in classes, and they will pretty much do what you want.
That said, use of namespaces here is almost irrelevant. It essentially means that there's a :: in the name of your variable (MyNamespace::MESSAGE), but you could alternatively call your variable MyNamespace_MESSAGE, for example.
So the question, independent of namespaces, is how can you have a global variable in C++. One way do to this is to declare the variable in a header file, and define it in a single C++ file. For example:
// message.h
extern std::string message;
// message.cc
std::string message {"Hello"};
(Wrap these in a namespace if you want.) Alternatively, if you just want to put it in a header file, use:
// header.h
inline std::string message{"Hello"};
Outside of a class, static just means static linkage, meaning that you can't access the variable from other translation units. That's not what you want.
|
72,888,784 | 72,945,217 | Optimizations around atomic load stores in C++ | I have read about std::memory_order in C++ and understood partially. But I still had some doubts around it.
Explanation on std::memory_order_acquire says that, no reads or writes in the current thread can be reordered before this load. Does that mean compiler and cpu is not allowed to move any instruction present below the acquire statement, above it?
auto y = x.load(std::memory_order_acquire);
z = a; // is it leagal to execute loading of shared `b` above acquire? (I feel no)
b = 2; // is it leagal to execute storing of shared `a` above acquire? (I feel yes)
I can reason out why it is illegal for executing loads before acquire. But why it is illegal for stores?
Is it illegal to skip a useless load or store from atomic objects? Since they are not volatile, and as I know only volatile has this requirement.
auto y = x.load(std::memory_order_acquire); // `y` is never used
return;
This optimization is not happening even with relaxed memory order.
Is compiler allowed to move instructions present above acquire statement, below it?
z = a; // is it leagal to execute loading of shared `b` below acquire? (I feel yes)
b = 2; // is it leagal to execute storing of shared `a` below acquire? (I feel yes)
auto y = x.load(std::memory_order_acquire);
Can two loads or stores be reordered without crossing acquire boundary?
auto y = x.load(std::memory_order_acquire);
a = p; // can this move below the below line?
b = q; // shared `a` and `b`
Similar and corresponding 4 doubts with release semantics also.
Related to 2nd and 3rd question, why no compiler is optimizing f(), as aggressive as g() in below code?
#include <atomic>
int a, b;
void dummy(int*);
void f(std::atomic<int> &x) {
int z;
z = a; // loading shared `a` before acquire
b = 2; // storing shared `b` before acquire
auto y = x.load(std::memory_order_acquire);
z = a; // loading shared `a` after acquire
b = 2; // storing shared `b` after acquire
dummy(&z);
}
void g(int &x) {
int z;
z = a;
b = 2;
auto y = x;
z = a;
b = 2;
dummy(&z);
}
f(std::atomic<int>&):
sub rsp, 24
mov eax, DWORD PTR a[rip]
mov DWORD PTR b[rip], 2
mov DWORD PTR [rsp+12], eax
mov eax, DWORD PTR [rdi]
lea rdi, [rsp+12]
mov DWORD PTR b[rip], 2
mov eax, DWORD PTR a[rip]
mov DWORD PTR [rsp+12], eax
call dummy(int*)
add rsp, 24
ret
g(int&):
sub rsp, 24
mov eax, DWORD PTR a[rip]
mov DWORD PTR b[rip], 2
lea rdi, [rsp+12]
mov DWORD PTR [rsp+12], eax
call dummy(int*)
add rsp, 24
ret
b:
.zero 4
a:
.zero 4
| Q1
Generally, yes. Any load or store that follows (in program order) an acquire load, must not become visible before it.
Here is an example where it matters:
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> x{0};
std::atomic<bool> finished{false};
int xval;
bool good;
void reader() {
xval = x.load(std::memory_order_relaxed);
finished.store(true, std::memory_order_release);
}
void writer() {
good = finished.load(std::memory_order_acquire);
x.store(42, std::memory_order_relaxed);
}
int main() {
std::thread t1(reader);
std::thread t2(writer);
t1.join();
t2.join();
if (good) {
std::cout << xval << std::endl;
} else {
std::cout << "too soon" << std::endl;
}
return 0;
}
Try on godbolt
This program is free of UB and must print either 0 or too soon. If the writer store of 42 to x could be reordered before the load of finished, then it would be possible that the reader load of x returns 42 and the writer load of finished returns true, in which case the program would improperly print 42.
Q2
Yes, it would be okay for a compiler to delete the atomic load whose value is never used, since there is no way for a conforming program to detect whether the load was done or not. However, current compilers generally don't do such optimizations. Partly out of an abundance of caution, because optimizations on atomics are hard to get right and bugs can be very subtle. It may also be partly to support programmers writing implementation-dependent code, that is able to detect via non-standard features whether the load was done.
Q3
Yes, this reordering is perfectly legal, and real-world architectures will do it. An acquire barrier is only one way.
Q4
Yes, this is also legal. If a,b are not atomic, and some other thread is reading them concurrently, then the code has a data race and is UB, so it is okay if the other thread observes the writes having happened in the wrong order (or summons nasal demons). (If they are atomic and you are doing relaxed stores, then you can't get nasal demons, but you can still observe the stores out of order; there is no happens-before relationship mandating the contrary.)
Optimization comparison
Your f versus g examples is not really a fair comparison: in g, the load of the non-atomic variable x has no side effects and its value is not used, so the compiler omits it altogether. As mentioned above, the compiler doesn't omit the unnecessary atomic load of x in f.
As to why the compilers don't sink the first accesses to a and b past the acquire load: I believe it's simply a missed optimization. Again, most compilers deliberately don't try to do all possible legal optimizations with atomics. However, you could note that on ARM64 for instance, the load of x in f compiles to ldar, which the CPU can definitely reorder with earlier plain loads and stores
|
72,890,391 | 72,890,525 | std::find/std::find_if for custom container c++ | I'm trying to find an object with some attribute value in a custom container that contains an array of objects of another class.
MyIterator<WindowWithTitleButton> WindowList::FindTitle(string title_find)
{
auto iter = std::find(this->begin(), this->end(), title_find);
return iter;
}
"Title" is an attribute of class WindowWithTitleButton and I'm trying to find object in the container with that "title", but I can't figure out how.
I tried to do that with std::find_if
bool WindowList::ContainsTitle(string cmpr, string title)
{
int result = cmpr.compare(title);
if (result == 0)
return true;
else
return false;
}
MyIterator<WindowWithTitleButton> WindowList::FindTitle(string title_find)
{
MyIterator<WindowWithTitleButton> iter;
auto i = std::find_if(iter = begin(), iter = end(), ContainsTitle((*iter).GetTitle(),title_find));
return i;
But it gives me an error C2064 - term does not evaluate to a function taking 1 arguments.
How can I properly use this function without error?
| In this:
auto i = std::find_if(iter = begin(), iter = end(),
ContainsTitle((*iter).GetTitle(),title_find));
You've made a few mistakes:
The iterators should be sent in by value:
std::find_if(begin(),end(), ...
The UnaryPredicate functor should have the signature bool(const YourWindowsClass&) - that is, it should take one argument and return true or false. The algorithm will loop through all windows in your container and the UnaryPredicate functor will be called with a reference to each element at a time in the container - not an iterator.
The UnaryPredicate also needs something to compare with and you can solve that by capturing it in a lambda for example. That's what [&title_find] does in my example below.
MyIterator<WindowWithTitleButton> WindowList::FindTitle(std::string title_find) {
return std::find_if(begin(), end(),
[&title_find](auto&& window) {
return title_find == window.GetTitle();
});
}
window.GetTitle() is here a member function that returns something that can be compared with a std::string.
If the elements in your container are of type WindowWithTitleButton you can replace auto&& window with const WindowWithTitleButton& window to make it clearer.
|
72,891,033 | 72,893,137 | Rewrite CListBox as a CCheckListBox | I am working on a Windows application using MFC and Visual Studio C++ 17.
I have multiple tabs in the application, one of which is currently implemented using CListBox and needs to be reimplemented using CCheckListBox.
CCheckListBox is a child class of CListBox.
I have a vector of unique CString's I want to display in the box.
To start simple, I tried making the tab with CListBox and by using CListBox::AddString(), this worked exactly as I wanted it to. It sorted the strings alphabetically, and automatically added a scroll bar on the side when the vector had too many CString's to display all at once in the list.
However, when swapping the CListBox variable to a CCheckListBox variable, I have come across the error when I press run along the lines of:
Debug Assertion Failed! ..... \mfc\winctrl3.cpp Line: 588
I found this GitHub link that has the winctrl3.cpp file and on line 588, there is a function called OnLButtonDblClk which is somewhat explained here.
The trouble is I am unsure of how to swap a variable from a parent class to a child class. Is it so different for Windows classes? In the courses and programs I have taken and written in the past, switching from a parent to child variable was straightforward but this is quite the opposite !
Any help is appreciated, thank you in advance ! :D
| There is no assertion in line 588 of the source file in your link. That github upload dates back to 2014. Why not search the winctrl3.cpp source file in your own Visual Studio installation instead? In my own installation, it is in function PreSubclassWindow() and there is indeed an assertion there:
// CCheckListBoxes must be owner drawn
ASSERT(GetStyle() & (LBS_OWNERDRAWFIXED | LBS_OWNERDRAWVARIABLE));
That is the CCheckListBox must be owner-drawn. Find the CCheckListBox constructor code above, you will notice that it calls the CListBox (parent-class) constructor, applying either of the two owner-drawn styles. Instead, the CListBox constructor calls CWnd::Create() with the "LISTBOX" Windows Class-Name as a parameter. That is, it seems to be a MFC-implemented control, overriding the CListBox class, with an owner-drawn style. There is no mention of a native "Check-ListBox" class or style in the Win32 documentation either. Also the CCheckListBox documentation (in the link you posted) clearly states: CCheckListBox is only for owner-drawn controls because the list contains more than text strings.
Therefore:
If you are creating the control using a resource script, add an owner-drawn style (eg LBS_OWNERDRAWFIXED) to the control (or set the Owner-Drawn property in the property editor).
If you are creating the control programmatically make sure you are calling the CCheckListBox constructor, not the CListBox one.
Not sure what you mean about the scroll-bar (and why you mention it), doesn't the list-box display a scroll-bar automatically (WS_VSCROLL style - or property), do you have to do something on your own?
EDIT:
Forgot to mention, if you are creating the control using a resource script use the Class Wizard to add a member variable (of "Control" type, not "Value") to the dialog class. The new variable must be of type CCheckListBox (MFC class). This will subclass the control. If the old project already had a CListBox member variable change it to CCheckListBox.
|
72,891,552 | 72,892,221 | why I cant send and recv integers in a loop correctly | I have the following code in my server program:
void sendAccounts(const Database& data, int socket, int32_t user)
{
std::vector<int32_t> accounts = data.getUsersAccounts(user);
uint16_t number = accounts.size();
number = htons(number);
send(socket, reinterpret_cast<char*>(&number), sizeof(number), 0);
for (size_t i = 0; i < accounts.size(); ++i)
{
std::cout << accounts[i] << std::endl;
int32_t account = htonl(accounts[i]);
send(socket, reinterpret_cast<char*>(&account), sizeof(account), 0);
}
}
And the following code in my client program:
std::vector<int32_t> getAccounts(int socket)
{
uint16_t n_accounts;
std::vector<int32_t> accounts;
recv(socket, reinterpret_cast<char*>(&n_accounts), sizeof(n_accounts), 0);
n_accounts = ntohs(n_accounts);
for (uint16_t i = 0; i < n_accounts; ++i)
{
int32_t account = 0;
recv(socket, reinterpret_cast<char*>(account), sizeof(account), 0);
account = ntohl(account);
accounts.push_back(account);
}
return accounts;
}
For some reason the client correctly receives the number of accounts but unable to receive account numbers, each recv returns -1, when I check errno it is equal to 0. What can be wrong?
| In the recv() loop, you are casting the value of account, which is always 0, thus producing a null pointer. This is the main reason why recv() is failing.
You need to instead cast the address of account (just as you did with n_accounts above the loop). So, change this:
reinterpret_cast<char*>(account)
To this:
reinterpret_cast<char*>(&account)
That being said, on most platforms, send() and recv() take void* pointers, so you don't actually need to use reinterpret_cast at all on those platforms.
Since you mention errno, I assume you are not running this code on Windows. If you were, then send()/recv() do take char* pointers and thus would need the casts (and you should be using WSAGetLastError() instead of errno).
|
72,891,751 | 72,905,747 | How to create an asio socket with an existing fd and callback into custom code rather than read from it when data is available | I have a C++ application where I'm using a 3rd Party api. As part of that api they will handle the socket connections etc, however, they have a mode where I can select / poll on the fd and then call into the api read from the socket, decode the data and dispatch to the proper handlers; this way we can control the thread where the dispatch code runs. Now I also have extensive use of asio for my networking and I would like to handle this with that. In fact, I desire the api's dispatch code to run on in the asio thread. So, I would like an asio socket that takes the existing fd and then makes a call to what I want when there is data on the fd. This seems pretty straight forward but I can't find it in the docs / examples.
| I found what I needed, asio::posix::stream_descriptor. I can assign it the socket handle (fd) and then call async_wait and asio will notify me when there is data to be read:
descriptor_.assign(connection_.get_socket_handle());
descriptor_.async_wait(asio::posix::stream_descriptor::wait_read, [this] (const std::error_code& error) { this->handle_data(error); });
|
72,892,205 | 72,892,217 | Error while finding the running sum of an array in C++ using vectors | Why am i getting this error, while finding the running sum of an array in c++?
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x6020000000b0 overflowed to 0x6020000000ac (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34".
the code is:
class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
vector<int> temp(nums.size());
nums[0]=temp[0];
for(int i=0;i<nums.size();i++){
temp[i]=temp[i-1]+nums[i];
}
return temp;
}
};
| nums[0]=temp[0] is incorrect, since temp[0] is 0 currently. It should be the other way around.
Also, the lower bound for the for loop should be i=1.
class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
vector<int> temp(nums.size());
temp[0] = nums[0];
for(int i=1;i<nums.size();i++){
temp[i]=temp[i-1]+nums[i];
}
return temp;
}
};
|
72,892,740 | 72,893,063 | How is the value of MediaDeviceInfo.deviceId calculated in Webrtc? | I am wondering how is the value of MediaDeviceInfo.deviceId calculated in Webrtc?
MediaDeviceInfo.deviceId is a property used in web APIs of Webrtc.
I have found a document MediaDeviceInfo, but still cannot get the answer.
Is it directly from the uuid of the connected Media Devices?
I guess there may be some calculations in native codes, but I am not familiar with its native codes.
| You can find the Chrome implementation here:
https://source.chromium.org/chromium/chromium/src/+/main:content/browser/renderer_host/media/media_stream_manager.cc;l=1653;drc=917850e016efe08e27c61eaa03e6fc27200e5be1
It is a hmac of the device id with a per-origin salt that has the same lifetime as cookies (for privacy reasons). This hides any device uuid.
|
72,894,063 | 72,894,282 | How to convert Hex in string format to Hex format | So i have a code that converts binary input to hex in string format:
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
int main() {
string binary[16] = {"0000", "0001", "0010", "0011", "0100", "0101",
"0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};
char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
string binaryInput;
cin >> binaryInput;
int inputLen = binaryInput.length();
string add(4 - inputLen % 4, '0');
if (binaryInput.length() / 4 != 0) {
binaryInput = add + binaryInput;
}
inputLen = binaryInput.length();
cout << "converted input: " << binaryInput << endl;
cout << "converted input length: " << inputLen << endl;
int intInput = stoi(binaryInput);
string hexEq = "";
for (int i = 0; i < inputLen / 4; i++) {
string quad = "";
for (int k = 0; k < 4; k++) {
if (intInput % 10) {
quad = '1' + quad;
} else {
quad = '0' + quad;
}
intInput /= 10;
}
for (int j = 0; j < 16; j++) {
if (quad == binary[j]) {
hexEq = hex[j] + hexEq;
break;
}
}
}
cout << "input converted to hex: " << hexEq << endl;
}
(ex. input: 11011, output: 1B)
But i cant figure out how can i represent that in hex format(for ex. i can create hex variables using uint8_t a = 0x1b and print that using printf("%x", a) . I would appreciate if you can help me.
| To parse the input, the standard std::stoul allows to set the base as parameter. For base 2:
unsigned long input = std::stoul(str, nullptr, 2);
Than you can print it as hex using either
std::cout << std::hex << input << '\n';
or
std::printf("%lx\n", input);
See https://godbolt.org/z/5j45W9EG6.
|
72,895,618 | 72,895,949 | incorrect function call on overload operator | In the code, why is (10 != i) calling == instead of !=? The other two call !=
#include <iostream>
class Integer
{
int x;
public:
bool
operator== (const Integer &i)
{
std::cout << "==";
return x == i.x;
}
bool
operator!= (const Integer &i)
{
std::cout << "!=";
return x != i.x;
}
Integer (int t = 0) { x = t; }
};
int
main ()
{
Integer i;
std::cout << (i != i) << '\n'; // calls !=
std::cout << (i != 100) << '\n'; // calls !=
std::cout << (10 != i) << '\n'; // calls ==
}
| There are two new additions to C++20 that made this possible (note that your code doesn't compile in earlier standard versions).
Compiler will attempt to replace a != b with !(a == b) if there is no suitable != for these arguments.
If there is no suitable a == b, compiler will attempt b == a as well.
So, what happens - compiler first notices that it doesn't know how to compare 10 != i, so it tries !(10 == i). There is still no suitable comparison, so it tries !(i == 10) and it can finally be done using your implicit constructor to convert 10 to Integer.
It can be easily verified by adding more info to debug print:
bool
operator== (const Integer &i) const
{
std::cout << x << "==" << i.x << ' ';
return x == i.x;
}
will print 0==10 1 in the last line (see it online).
As noticed in comments, you don't even need operator !=, due to aforementioned behaviour C++20 compiler will automatically convert any such call to operator ==.
|
72,896,537 | 72,896,677 | c++ loop through a class private unique_ptr array from non-friend external utility function without using c-style for loop | I've got a class with:
class vector_class {
private:
std::unique_ptr<int[]> my_vector;
int size_;
public:
auto at(int) const -> int; // returns value at subscript
auto at(int) -> int&;
auto size() -> int; // returns vector size
}
I've been asked to construct an external function that takes 2 of these objects and returns the inner_product. Problem is that I have the following restrictions:
Can't add any public functions.
Shouldn't use friendship
Shouldn't use c-style for loops (i.e. should use algorithms).
Can't use any stl containers.
I can't use for_each because I don't have an iterator (since the vector is private non-friend).
I can't do for (i = 0; i < a.size(); ++i) ... (since no basic for loop).
I guess I could write a custom iterator class but this is a lot of work and wondering if I've missed an easier solution... Any suggestions?
| Iterators were designed to emulate much of the behavior of pointers, so much that all pointers can be used as iterators.
So if you have an array, and the number of elements in the array, you can use a pointer to the first element of the array as the begin iterator. And a pointer to one element beyond the last element (i.e. begin + size) as the end iterator. Then you can use these "iterators" with any normal standard function expecting an iterator pair.
For your specific case, &my_vector[0] as begin, and &my_vector[size_] as end.
Now, due to the limitations and requirements of your exercise, the simplest solution is probably to get these pointers through the public at() function. Or if the class has an overloaded operator[] you can use that instead:
inner_product(&i[0], &i[i.size()], &j[0]);
Because there are two overloads of the at function (and probably of the [] operator if it exists) we might need to specifically ask for the overload that returns a reference, if the compiler doesn't select the correct overloads to begin with.
This can be done by defining our own temporary reference variables:
auto const& first_begin = i[0];
auto const& first_end = i[i.size()];
auto const& second_begin = j[0];
auto result = inner_product(&first_begin, &first_end, &second_begin, 0);
Or, since it seems that the at function have a proper reference-returning overload, you can use that instead of []:
auto result = inner_product(&i.at(0), &i.at(i.size()), &j.at(0), 0);
|
72,896,672 | 72,897,768 | Arduino: Why same library is included multiple times | I couldn't rationalize the reason that why (dependency) library is required when this very library has already been included in the required library itself. For example:
If I want to use SD.h, in the example code, SPI.h is required:
#include <SD.h> // SPI.h is already included in SD.h
#include <SPI.h> // why include it here once more
...
however, if we go into the SD.h and related files, the SPI.h has already been included.
and this is not the only one, ILI9488.h, XPT2046_touchscreen.h, etc. all requires SPI.h when include them.
I have found someone on another topic said at arduino.cc that "if this is not included in the sketch, it (SPI.h) will not be compiled, besides, it is good to tell others that SPI.h is a dependency of the library you included" and I found the last part is especially unreasonable.
Maybe I understood him wrong, but it compiles, and they all worked great without including the SPI.h, of course, provided that I never used any of the methods from SPI.h.
However, I am sure I am missing something. I just don't know it and it haunting me ever since my code is working without including the SPI.h.
I appritiate if anyone can provide my some insight about this. Thanks in advance.
| Arduino doesn't have makefiles so the Arduino builder scans for #include directives to add the required libraries.
Old version of the build system required to list all libraries in the main ino file. That is why the examples list all the main header files of the libraries used.
|
72,896,679 | 72,897,742 | Does it risk if use c++ std::unordered_map like this? | Does it risk if use c++ std::unordered_map like this?
std::unordered_map<std::string, std::unordered_set<std::shared_ptr<SomeType>>> _some_map;
...
void init() {
auto item = std::make_shared<SomeType>();
_some_map["circle"].insert(item);
}
_some_map is a member variable. init() function can be called only once, so insert is thread-safe. After initialization, the map will be read only in multi-thread. I think it is thread-safe too.
I'm not sure if I can use insert like this. Because it will make a unordered_set and a pair when there is no val of key "circle". The code works normally. Just want to make sure it is without potential risk.
(I am not good at English writing. )
Thank you.
|
I'm not sure if I can use insert like this.
Yes, you can, because operator[]
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
Your value_type is std::unordered_set which is default constructible, so there is no problem.
After initialization, the map will be read only in multi-thread
Here also you are safe, because according to the containers documentation
All const member functions can be called concurrently by different threads on the same container.
so if you are only reading the values without modifying them, it is OK. You could even perform write operations if you could guarantee that different threads are accessing different elements in your container.
|
72,896,814 | 72,898,969 | C++20 lambda capture variadic arguments with prvalue and non-copyable lvalue | I am trying to make a function that can stage arbitrary computation with lambda. This function takes in any function and parameter pack and stages the computation in a lambda function. A conflict occurs when Args contains both non-copyable lvalue reference and prvalue. The prvalue parameter will become dangling reference if we capture by reference. If we capture by value, we will try to call copy constructor of the lvalue reference. Neither will compile.
Is there a correct way to do it in C++20? I've read many related posts. Many of them give the capture by value + forwarding approach as below.
#include <iostream>
#include <memory>
using namespace std;
void g(std::unique_ptr<int>& a, std::unique_ptr<int> b) {
if (a) {
cout << *a << " ";
}
if (b) {
cout << *b;
}
}
template <typename F, typename ... Args>
auto f(F&& func, Args&& ... args) {
// by reference
auto lamb = [func, &args...]() {
g(std::forward<Args>(args)...);
};
// by value
/*auto lamb = [func, ... args = std::forward<Args>(args)]() mutable {
g(std::forward<Args>(args)...);
};*/
return lamb;
}
int main()
{
auto ptr = std::make_unique<int>(5);
auto ptr2 = std::make_unique<int>(6);
f(g, ptr, std::move(ptr2));
auto l = f(g, ptr, std::make_unique<int>(7));
l();
return 0;
}
| You can use a tuple to store args... and decide whether to store a value or a reference depending on whether the args... are lvalue or rvalue. Then use std::apply to forward parameters
template <typename F, typename ... Args>
auto f(F&& func, Args&& ... args) {
// by value or by reference
auto lamb = [func, args_tuple =
std::tuple<Args...>(std::forward<Args>(args)...)]() mutable {
std::apply([func](auto&... args) {
func(std::forward<Args>(args)...);
}, args_tuple);
};
return lamb;
}
Demo
|
72,896,973 | 72,899,963 | Combinations of a variadic list of arbitrary types | I'd like to get a cartesian product of all the possible string-value pairs which are input in a variadic list of arguments and obtain a map M as,
using M = std::unordered_map<std::string, boost::any>;
template<typename ...Args>
std::vector<M> combinations(const std::pair<std::string, std::vector<Args>> &...args) {
// ... ??
}
A possible input is
std::pair<std::string, std::vector<std::string>> v1 = {"A", {"x","y","z"}};
std::pair<std::string, std::vector<int>> v2 = {"B", {1,2,3}};
std::pair<std::string, std::vector<double>> v3 = {"C", {0.1,0.2,0.3}};
auto m1 = combinations(v1,v2) // a vector consisting of 9 maps. E.g., m1[0] = {{"A","x"},{"B",1}} etc...
auto m2 = combinations(v1,v2,v3) // a vector consisting of 27 maps. E.g., m2[0] = {{"A","x"},{"B",1},{"C",0.1}} etc...
m1 (to be explicit)
m1[0] : {{"A","x"},{"B",1}}
m1[1] : {{"A","x"},{"B",2}}
m1[2] : {{"A","x"},{"B",3}}
m1[3] : {{"A","y"},{"B",1}}
m1[4] : {{"A","y"},{"B",2}}
m1[5] : {{"A","y"},{"B",3}}
m1[6] : {{"A","z"},{"B",1}}
m1[7] : {{"A","z"},{"B",2}}
m1[8] : {{"A","z"},{"B",3}}
How do I implement this?
| I don't think it's necessary to use std::any/boost::any here since we can figure out the exact types.
For example, m1 will be a:
std::vector< std::tuple< std::pair<std::string, std::string>,
std::pair<std::string, int> > >;
Here's one way:
In combinations I deduce the tuple type to store in the resulting vector and call xprod passing all the pairs on with an index_sequence.
From these the cross product will be created in the function xprod. I create an array of pair<size_t, size_t> for the indices in each vector. idxlim[].first holds the current index, and idxlim[].second holds each vector's size(). To step the combined index value over all the vectors, I use this:
template <size_t N>
bool step_index(std::array<std::pair<size_t, size_t>, N>& idxlim) {
for (size_t i = N; i--;) {
auto&[idx, lim] = idxlim[i];
if (++idx != lim) return true;
idx = 0;
}
return false; // reached the end
}
The xprod function receives the pairs and creates idxlim which contains the current index and the limit for each vector and just loops through all combinations, populating the resulting vector, rv, as it goes:
template <class T, size_t... I, class... P>
auto xprod(std::index_sequence<I...>, const P&... pairs) {
std::vector<T> rv;
std::array<std::pair<size_t, size_t>, sizeof...(P)> idxlim{
{{0, pairs.second.size()}...}
};
do {
rv.emplace_back(T{{pairs.first, pairs.second[ idxlim[I].first ]}...});
// ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// std::string the "any" type
} while(step_index(idxlim));
return rv;
}
The "magic" in T{{pairs.first, pairs.second[ idxlim[I].first ]}...} is that it's a parameter expansion over I... (think horizontally) and I... is supplied by creating an index_sequence from the entry function (se below). It's not one pair. It's all of them (keep thinking horizontally):
It'll be expanded to these emplace_backs:
T{{"A", "x"}, {"B", 1}}
T{{"A", "x"}, {"B", 2}}
T{{"A", "x"}, {"B", 3}}
T{{"A", "y"}, {"B", 1}}
T{{"A", "y"}, {"B", 2}}
T{{"A", "y"}, {"B", 3}}
T{{"A", "z"}, {"B", 1}}
T{{"A", "z"}, {"B", 2}}
T{{"A", "z"}, {"B", 3}}
Entry function:
template <class... Ts>
auto combinations(const std::pair<std::string, std::vector<Ts>>&... args) {
using tt = std::tuple<std::pair<std::string, Ts>...>;
return xprod<tt>(std::make_index_sequence<sizeof...(Ts)>{}, args...);
}
Demo
|
72,897,447 | 72,908,496 | Crash on boost::posix_time::from_time_t when compile with -ftrapv | I use function ptime from_time_t(time_t t); and set t with big values like as UINT_MAX.
When i use -ftrapv option - program crashes because happens signed overflow, without option - sometimes result is not correct(near 00:00, Jan 1 1970).
I don't want to disable -ftrapv option.
Question:
Is it boost bug or from_time_t has some restricts on parameter?
Code example
#include <boost/date_time/posix_time/posix_time.hpp>
#include <climits>
#include <type_traits>
int main() {
long int lmax{LONG_MAX};
unsigned int umax{UINT_MAX};
std::cout<<"Start = "<<lmax<<std::endl;
std::cout<<"std::is_same_v<time_t, long int> = "
<<std::is_same<time_t, long int>::value<<std::endl;
try {
std::cout <<boost::posix_time::from_time_t(umax)<<std::endl;
std::cout <<boost::posix_time::from_time_t(lmax)<<std::endl;
}
catch(const std::exception& e)
{
std::cout<<"exception e = "<<e.what()<<std::endl;
}
std::cout<<"Finish"<<std::endl;
}
| I'm afraid there are undocumented "implicit" limits (preconditions) on the input to from_time_t:
The input causes signed integer overflow: 9223372036854775807 * 1000000 cannot be represented in type 'long int' in boost/date_time/time_resolution_traits.hpp:153:47 (boost 1.79).
In short if you need trapv you should probably avoid calling from_time_t with invalid arguments. You can raise an issue with the library developers to point out the lack of documentation. They'll probably reply with "but that's implentation/platform dependent", but if you give them your use-case, they could be compelled by documenting a "portably safe" input domain for time_t.
|
72,898,090 | 72,908,088 | float number to string converting implementation in STD | I faced with a curious issue. Look at this simple code:
int main(int argc, char **argv) {
char buf[1000];
snprintf_l(buf, sizeof(buf), _LIBCPP_GET_C_LOCALE, "%.17f", 0.123e30f);
std::cout << "WTF?: " << buf << std::endl;
}
The output looks quire wired:
123000004117574256822262431744.00000000000000000
My question is how it's implemented? Can someone show me the original code? I did not find it. Or maybe it's too complicated for me.
I've tried to reimplement the same transformation double to string with Java code but was failed. Even when I tried to get exponent and fraction parts separately and summarize fractions in cycle I always get zeros instead of these numbers "...822262431744". When I tried to continue summarizing fractions after the 23 bits (for float number) I faced with other issue - how many fractions I need to collect? Why the original code stops on left part and does not continue until the scale is end?
So, I really do not understand the basic logic, how it implemented. I've tried to define really big numbers (e.g. 0.123e127f). And it generates huge number in decimal format. The number has much higher precision than float can be. Looks like this is an issue, because the string representation contains something which float number cannot.
| Finally I've found out what the difference between Java float -> decimal -> string convertation and c++ float -> string (decimal) convertation. I did not find the original source code, but I replicated the same code in Java to make it clear. I think the code explains everything:
// the context size might be calculated properly by getting maximum
// float number (including exponent value) - its 40 + scale, 17 for me
MathContext context = new MathContext(57, RoundingMode.HALF_UP);
BigDecimal divisor = BigDecimal.valueOf(2);
int tmp = Float.floatToRawIntBits(1.23e30f)
boolean sign = tmp < 0;
tmp <<= 1;
// there might be NaN value, this code does not support it
int exponent = (tmp >>> 24) - 127;
tmp <<= 8;
int mask = 1 << 23;
int fraction = mask | (tmp >>> 9);
// at this line we have all parts of the float: sign, exponent and fractions. Let's build mantissa
BigDecimal mantissa = BigDecimal.ZERO;
for (int i = 0; i < 24; i ++) {
if ((fraction & mask) == mask) {
// i'm not sure about speed, maybe division at each iteration might be faster than pow
mantissa = mantissa.add(divisor.pow(-i, context));
}
mask >>>= 1;
}
// it was the core line where I was losing accuracy, because of context
BigDecimal decimal = mantissa.multiply(divisor.pow(exponent, context), context);
String str = decimal.setScale(17, RoundingMode.HALF_UP).toPlainString();
// add minus manually, because java lost it if after the scale value become 0, C++ version of code doesn't do it
if (sign) {
str = "-" + str;
}
return str;
Maybe topic is useless. Who really need to have the same implementation like C++ has? But at least this code keeps all precision for float number comparing to the most popular way converting float to decimal string:
return BigDecimal.valueOf(1.23e30f).setScale(17, RoundingMode.HALF_UP).toPlainString();
|
72,898,205 | 72,902,694 | clang-tidy-10 and compile_commands.json does not support relative paths | There are various posts about this - but I can't seem to find a definitive answer. Some people are saying it works and others not, and yet others saying its tools / IDEs that are the issue.
So I made as small an example as I could. Here are the two files I have:
compile_commands.json
[
{
"arguments": [ "gcc", "test.cpp" ],
"directory": "/home/user/development/sandbox/comp_commands",
"file": "test.cpp"
}
]
test.cpp
bool is_it()
{
// no return value - give clang warning
}
Now if I run the command clang-tidy test.cpp in the same directory as the files I get:
[user] comp_commands$ clang-tidy test.cpp
1 warning generated.
test.cpp:4:1: warning: non-void function does not return a value [clang-diagnostic-return-type]
}
... as expected. However if I change the line in the compile_commands.json directory to:
"directory": ".",
Then I get the output:
[user] comp_commands$ clang-tidy test.cpp
Skipping /home/user/development/sandbox/comp_commands/test.cpp. Compile command not found.
here "MaskRay"s answer suggests this is fine/works. Since I am using no IDE, just clang-tidy directly- it can't be the IDE...
Is it possible to use relative paths in the compile_commands.json file? - I am generating this file via a script and can use either, but I specifically want it to be relative paths.
| Short answer
No, the directory in compile_commands.json cannot be relative. It must be absolute to work with clang-tidy.
What the spec says
The specification
for compile_commands.json says:
directory: The working directory of the compilation. All paths specified in the command or file fields must be either absolute or relative to this directory.
That is not very explicit, but as it acknowledges the possibility of
relative paths in other attributes, while saying nothing about a
relative directory, this is weak evidence that the path must be
absolute.
What the source says
The code that prints Compile command not found. is in
ClangTool::run:
std::vector<CompileCommand> CompileCommandsForFile =
Compilations.getCompileCommands(File);
if (CompileCommandsForFile.empty()) {
llvm::errs() << "Skipping " << File << ". Compile command not found.\n";
FileSkipped = true;
continue;
}
This is calling JSONCompilationDatabase::getCompileCommands,
which consults the MatchTrie member, which is built in
JSONCompilationDatabase::parse, and includes these key lines:
if (!Directory) {
ErrorMessage = "Missing key: \"directory\".";
return false;
}
SmallString<8> FileStorage;
StringRef FileName = File->getValue(FileStorage);
SmallString<128> NativeFilePath;
if (llvm::sys::path::is_relative(FileName)) {
SmallString<8> DirectoryStorage;
SmallString<128> AbsolutePath( // (1)
Directory->getValue(DirectoryStorage));
llvm::sys::path::append(AbsolutePath, FileName); // (2)
llvm::sys::path::native(AbsolutePath, NativeFilePath);
} else {
llvm::sys::path::native(FileName, NativeFilePath);
}
Although this code is willing to handle a relative FileName, the
Directory value is simply assumed to be absolute at (1), as its value
(as a YAML string) is concatenated with FileName at (2) and the result
treated as absolute from then on.
When the input file name test.cpp is passed on the command line,
the tooling infrastructure turns that into the absolute path
/home/user/development/sandbox/comp_commands/test.cpp, then
compares it as a string (via MatchTrie) to the path built by the above code,
which will be ./test.cpp and hence not match.
What about ccls?
ccls is a separate project that
happens to also consume the compile_commands.json format, but with an
extension to allow relative directory attributes.
That extension is not present in clang-tidy.
|
72,898,340 | 72,898,396 | C++: Insert an element in a Vector without insert() | I have been trying to solve the above problem for a friend, everytime the last element of the vector gets removed although I feel that its size should increase dynamically after insertion.
Here's the Code:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void display(vector<int> arr){
cout<<"Result"<<endl;
for(auto &p: arr){
cout<<p<<endl;
}
}
void indsert(vector<int> arr, int size, int element, int ind){
for(int i=size+1; i>=ind; i--)
arr[i] = arr[i-1];
arr[ind] = element;
display(arr);
}
int main()
{
int ind,size,element;
cout<<"Enter the size of the array"<<endl;
cin>>size;
vector<int> arr;
cout<<"Enter the elements of the array"<<endl;
for(int i=0;i<size;i++){
int temp;
cin>> temp;
arr.push_back(temp);
}
cout<<"Enter the element to be inserted"<<endl;
cin>>element;
cout<<"Enter the index"<<endl;
cin>>ind;
indsert(arr, size, element, ind);
return 0;
}
| You have two problems.
The first is with the function signature:
void indsert(vector<int> arr, ...)
You pass the vector by value. That means a copy of the vector is made, and that copy is passed to the function.
You can modify this copy as much as you want, but the original vector will still not change.
You need to pass the vector by reference:'
void indsert(vector<int>& arr, ...)
// ^
// Note ampersand here, making this a reference
The second problem is much worse: You seem to assume that you can insert into a vector using the [] operator. That's not what's happening.
Instead you go out of bounds of the vector, which leads to undefined behavior.
You need to explicitly resize the vector, either using insert, push_back/emplace_back, or resize.
Also remember that since indexes are zero-based, the top-index is the same as the vector size minus one. Using the vector size as index will be out of bounds. Using the vector size plus one is even more out of bounds.
|
72,898,843 | 72,899,719 | Adding new constructors to a specialised template class | I have a class defining an array of fixed length n, with some methods.
template<int n>
struct array_container{
/* some code here */
int array[n];
};
Let's say I want to add a constructor to array_container<3>, something along the lines of:
array_container<3>::array_container(int a0, int a1 ,int a2){
array[0] = a0;
array[1] = a1;
array[2] = a1;
}
I know of two ways to do this:
One is to copy the entire code of the generic class, replacing n with 3, and add my constructor:
template<>
struct array_container<3>{
/* some code here */
int array[3];
array_container(int a0, int a1 ,int a2){
array[0] = a0;
array[1] = a1;
array[2] = a1; }
};
This works correctly, but has the disadvantage of needing to copy all the code and methods from the generic base.
Another method is to add a constructor array_container(int a0, int a1, int a2); in the generic class, then define:
template<>
array_container<3>:: array_container(int a0, int a1 ,int a2){
array[0] = a0;
array[1] = a1;
array[2] = a1; }
This has the disadvantage of populating my generic base class with at best undefined or at worst incorrect constructors, such as
array_container<2>(int a0, int a1 ,int a2) (undefined or incorrect depending on whether or not I add the definition to the generic base or not).
Is there any approach that avoids both pitfalls? Ie. doesn't need to copy-paste the entire generic base code for the specialization, and doesn't add unnecessary constructors to the generic base?
|
Is there any approach that avoids both pitfalls? Ie. doesn't need to copy-paste the entire generic base code for the specialization, and doesn't add unnecessary constructors to the generic base?
Ignoring the fact that, as @Goswin von Brederlow mentions, you seem to be reinventing the wheel (std::array and aggregate initialization), C++20's requires-expressions allows you to define constructors in a primary template that are constrained to only certain specializations. E.g.:
#include <type_traits>
// Helper trait for constraining a ctor to a set
// of specializations.
template <int n, int... ns> struct is_one_of {
static constexpr bool value{false};
};
template <int n, int n0, int... ns> struct is_one_of<n, n0, ns...> {
static constexpr bool value{(n == n0) || is_one_of<n, ns...>::value};
};
template <int n, int... ns>
inline constexpr bool is_one_of_v{is_one_of<n, ns...>::value};
template <int n> struct array_container {
/* some code here */
int array[n];
// Constrained to n == 3 or n == 5.
template <typename... Args>
requires(std::is_same_v<Args, int> &&...) && (sizeof...(Args) == n) &&
is_one_of_v<n, 3, 5 /*, ... */> array_container(Args... args)
: array{args...} {}
};
// Demo.
array_container<3> arr3{1, 2, 3}; // OK
array_container<4> arr4{1, 2, 3, 4}; // Error (no matching ctor)
array_container<5> arr5{1, 2, 3, 4, 5}; // OK
|
72,899,549 | 72,922,555 | how to set a value to list or text box using wxWidgets library | I've been struggling with converting the numbers on my buttons to the text box for my assignment. Basically what I'm trying to do is when a user presses for example when I click on 7 it should appear in the text box but currently in my Button Pressed method it only puts in a . instead of 7 and I'm not too familiar with the wxWidgets library classes. is there another command or method I can use?
wxBEGIN_EVENT_TABLE(calMain, wxFrame)
EVT_BUTTON(100, ButtonPressed)
wxEND_EVENT_TABLE()
calMain::calMain() : wxFrame(nullptr, wxID_ANY, "Calculator UI!", wxPoint(50, 50), wxSize(335, 545))
{
wxFont font(15, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false);
m_txt1 = new wxTextCtrl(this,wxID_ANY, " ",wxPoint(0, 21), wxSize(322, 50));
CalButton = new wxButton(this, 100, "7", wxPoint(30, 156), wxSize(50, 70));
CalButton->SetFont(font);
}
void calMain::ButtonPressed(wxCommandEvent& evt)
{
m_txt1->SetLabelText(CalButton->GetLabelText());
evt.Skip();
}
| You need to use wxTextCtrl::SetValue() (or ChangeValue(), which is very similar, but doesn't generate any events about the change in the text control) to change the value (not the label) of wxTextCtrl.
|
72,899,920 | 72,900,340 | Inheritance and operator overloading | Hi I am new to c++ and had some conceptual questions that I wasn't able to find any direct answers to online.
So if we have a parent class and multiple children classes and we want to create an overloaded input function for it. So do we create it for every child class or just for once for the parent class. Also do we have to define the function in every class even if we leave it blank?
For example:
class A{
public:
friend std::istream &operator >> (std::istream &, A &);
friend std::ostream &operator << (std::ostream &, const A &);
}
class B: public A{
}
class C: public A{
}
So would the above be correct and using this implementation I can take input of both B and C?
What would be the correct method if I had to implement another operator like + that has different implementations for class B and C. Do I just define them individually (because I read that friend functions cannot be inherited, i might be wrong)
| So, what @john said, basically, something like this (reduced to a minimal example):
#include <iostream>
class A {
public:
friend std::ostream &operator << (std::ostream &os, const A &a);
private:
virtual std::ostream& print (std::ostream &os) const { std::cout << m_x; return os; }
int m_x = 42;
};
class B: public A {
std::ostream& print (std::ostream &os) const override { std::cout << m_y; return os; }
int m_y = 84;
};
std::ostream &operator << (std::ostream &os, const A &a) { return a.print (os); }
int main ()
{
B b;
std::cout << b;
}
Note that you don't have to override print in any particular derived class if you don't want to. It's just a virtual function like any other.
|
72,900,175 | 72,901,482 | Deduction of template arguments for friend function declared in class template | Consider the following example:
#include <iostream>
template <class T, int V>
struct S
{
friend int Func(T) // decl-1
{
return V;
}
};
struct U
{
friend int Func(U); // decl-2
};
template struct S<U, 42>; // spec-1
int main()
{
std::cout << Func(U{}) << std::endl; // Compiles and prints 42
}
My understanding is that the expression Func(U{}) causes an unqualified name lookup of the function Func, and through ADL finds declaration decl-2. However, this is not a viable candidate function for overload resolution (since it is not defined), and thus the compiler selects declaration decl-1. Misunderstanding, and irrelevant to the question, see comment from @LanguageLawyer
My question is what rule(s) in the standard allow the compiler to use the template parameters from the specialization spec-1 to instantiate the class template that contains decl-1.
Searching through cppreference, the only rule I found that seems to apply refers to overload resolution of function templates, and to cite:
For function templates, template argument deduction and checking of any explicit template arguments are performed to find the template argument values (if any) that can be used in this case:
if both succeeds, the template arguments are used to synthesize declarations of the corresponding function template specializations, which are added to the candidate set, and such specializations are treated just like non-template functions except where specified otherwise in the tie-breaker rules;
if argument deduction fails or the synthesized function template specialization would be ill-formed, no such function is added to the candidate set.
Source: https://en.cppreference.com/w/cpp/language/overload_resolution#Details
Is decl-1 considered a function template for the purposes of overload resolution? Does the compiler synthesize a declaration template int Func<U, 42>(U) using spec-1 (through template argument deduction, presumably)? Or is something else at play here?
EDIT: An additional misconception that I may have is what exactly is spec-1, my current understanding is that it is the declaration of an explicit specialization of class template S as an incomplete type, if possible please clarify if this is correct.
|
what rule(s) in the standard allow the compiler to use the template parameters from the specialization spec-1 to instantiate the class template that contains decl-1.
This is specified in temp.explicit-12 which states that:
An explicit instantiation definition that names a class template specialization explicitly instantiates the class template specialization and is an explicit instantiation definition of only those members that have been defined at the point of instantiation.
(emphasis mine)
And since spec-1 is an explicit instantiation definition, the result will be the instantiation of the class template specialization S<U, 42>
Is decl-1 considered a function template for the purposes of overload resolution?
No, decl-1 is a definition for an ordinary(non-template) function. Moroever, this decl-1 is nothing but the definition for the function declared in decl-2.
|
72,900,372 | 72,901,206 | std::thread and ros::ok() do not work in ROS | I have a function that is executing by std::thread. I want it works until the user closes the terminal that running roscore by pressing Ctrl+C. Because of that I use this inside the thread:
void publish_camera_on_topic(std::vector<Camera> cameras, const std::vector<ros::Publisher> publishers, const int camera_index)
{
int frameSize;
BYTE *imagePtr;
// frame id
int frame_id = 0;
cv_bridge::CvImage img_bridge;
sensor_msgs::Image img_msg;
while (ros::ok()) {
// Grab and display a single image from each camera
imagePtr = cameras[camera_index].getRawImage();
frameSize = cameras[camera_index].getFrameSize();
cameras[camera_index].createRGBImage(imagePtr,frameSize);
unsigned char* pImage = cameras[camera_index].getImage();
if (NULL != pImage) {
Mat image(cameras[camera_index].getMatSize(), CV_8UC3, pImage, Mat::AUTO_STEP);
// release asap
cameras[camera_index].releaseImage();
//cvtColor(image, image, CV_BGR2RGB,3);
// publish on ROS topic
std_msgs::Header header; // empty header
header.seq = frame_id; // user defined counter
header.stamp = ros::Time::now(); // time
img_bridge = cv_bridge::CvImage(header, sensor_msgs::image_encodings::RGB8, image);
img_bridge.toImageMsg(img_msg); // from cv_bridge to sensor_msgs::Image
publishers[camera_index].publish(img_msg); // ros::Publisher pub_img = node.advertise<sensor_msgs::Image>("topic", queuesize);
}
// increase frame Id
frame_id = frame_id + 1;
}
std::cout << "ROS closing for thread of camera " << camera_index << " recieved." << std::endl;
}
Also, I create thread like this:
// image publisher
// for each camera create an publisher
std::vector<ros::Publisher> publishers;
for (size_t i = 0; i < cameras.size(); i++) {
char topic_name[200];
sprintf(topic_name, "/lumenera_camera_package/%d", i + 1);
publishers.push_back(nh.advertise<sensor_msgs::Image>(topic_name, 10));
}
// work with each camera on a seprate thread
std::vector<std::thread> thread_vector;
for(size_t i=0; i < cameras.size(); i++) {
thread_vector.push_back(std::thread(publish_camera_on_topic, cameras, publishers, i));
}
ros::spin();
std::for_each(thread_vector.begin(), thread_vector.end(), [](std::thread &t){t.join(); });
for(size_t i=0; i < cameras.size(); i++) {
cameras[i].stopStreaming();
}
ROS_INFO("Node: [lumenera_camera_node] has been Ended.");
However, when I press Ctrl+C in the terminal and stop the roscore, the threads keep running, and the value of ros::ok() does not change.
| The problem is solved. The issue is ros::ok() does not check for ROS master. Instead of this line:
while (ros::ok()) { //do sth}
This line should be used:
while (ros::ok() && ros::master::check()) { // do sth}
|
72,900,864 | 72,901,165 | Deleting nodes recursively | I have created this function to recursively delete nodes from a doubly linked list. The issue here is that based on the call stack, it starts from the second so it does not delete the entire list. I can delete the remaining node from the method where I'm calling this but there should be a way around that. Is there a way of resolving this issue?
void RecursiveClear(const Node* _curr) {
if(_curr != nullptr) {
//_curr->prev = _curr;
_curr = _curr->next;
RecursiveClear(_curr);
}
if (_curr != nullptr) {
delete _curr;
}
}
| First: Don't use a leading _.
You modify _curr in the function so by the time you end up at the delete the original pointer is gone. So don't do that, just call the function wiht the next value without modifying the local vbariable:
RecursiveClear(_curr->next);
You also shouldn't do a recursion like that because lists can be long. Your code is not tail recursive. Every node in the list will use up a little bit of stack space. For long lists this will overflow the stack and crash.
Use a temporary so you can reorder the operations to be tail recursive:
void RecursiveClear(const Node* curr) {
if (curr != nullptr) {
const Node *next = curr->next;
delete curr;
RecursiveClear(next);
}
}
|
72,900,938 | 72,906,268 | Failing Tictactoe in c++ | I'm a beginner in c++, i'm trying to make a tictactoe. My program fails at the part acfter i enter input. When I enter an input, there is no next action from the program like i expected it to ("unvalid", check if win or loose, ask for input again). It only shows blank. like below: after I enter "1", nothing happens, and I can keep enter more input.
terminal example photo
I know it is a simple activity but I just ca't figure it out ToT. Thank you for helping!
//tictactoe
#include <iostream>
#include <vector>
using namespace std;
//declared variables
vector<char> out = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
int in = 2;
char player_out;
bool loose = false;
char x;
bool filled = false;
bool end(){ //won yet?
bool loose = false;
//horizontal
if (out[1] == out[2] && out[3] == out[2]){
loose = true;
}
else if (out[4] == out[5] && out[6] == out[5]){
loose = true;
}
else if (out[7] == out[8] && out[9] == out[8]){
loose = true;
}
//vertical
else if (out[1] == out[4] && out[7] == out[1]){
loose = true;
}
else if (out[2] == out[5] && out[8] == out[2]){
loose = true;
}
else if (out[3] == out[6] && out[9] == out[3]){
loose = true;
}
else if (out[1] == out[5] && out[9] == out[5]){
loose = true;
}
else if (out[3] == out[5] && out[7] == out[5]){
loose = true;
}
else{
loose = false;
}
return loose;
}
void game_start_display(){ //display the board
cout << "TIC TAC TOE\n";
cout << " | | \n";
cout << " " << out[1] << " | " << out[2] << " | " << out[3] << " \n";
cout << "______|______|______\n";
cout << " | | \n";
cout << " " << out[4] << " | " << out[5] << " | " << out[6] << " \n";
cout << "______|______|______\n";
cout << " | | \n";
cout << " " << out[7] << " | " << out[8] << " | " << out[9] << " \n";
cout << " | | \n\n";
}
int change_player(){ //take turn 1st and 2nd player
if (in == 1){
in++;
}
else{
in--;
}
return in;
}
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O'){
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O')
cout << "The square has already been used!\n";
filled = false;
return filled;
}
char player_out_f(){ //change output sign for each players (X, O)
if (in == 1){
player_out = 'X';
}
else if (in == 2){
player_out = 'O';
}
return player_out;
}
void c_player_display(){ //tell players to enter a number
cout << "Player " << in << "'s turn, please enter a number:\n";
}
int main(){
//intro
int loose = false;
game_start_display();
while(loose == false){ //when the game is still happening
change_player(); //change player (player start is set 2 so this comes first and change it to 1)
player_out_f(); //change player output sign (X, O)
c_player_display(); //print the line to ask for input
while(filled == false){ //when the there is no input yet (the spot is not filled)
cin >> x; // input
if (x > 0 && x < 10){ //check if input is in range 1-9
filled_f(); //check if the spot is occupied
}
else if(x < 0 && x > 10) { //if input is out of range
cout << "Invalid! Enter again!\n";
filled = false; //repeat the asking input circle (the while)
}
}
game_start_display(); //output the board again with new char (X or O)
end(); //check if anyone's won yet, if no, repeat the circle
}
cout << "Player " << in << " won! GG";
}
| You have infinite loop at while (filled == false) { ... }, because filled_f always sets filled to false (and the else if branch of the condition inside this loop as well does so). It's because you most likely missed figure brackets when writing else if block in filled_f. Your indentation hints that you wanted 2 statements to be in that block, but as of now, only the first is executed conditionally, and the second (filled = false;) is executed after the branch. In other words, with intuitive indentation this function looks like this:
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O') {
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O')
cout << "The square has already been used!\n";
filled = false;
return filled;
}
It sets filled = false; in any case, since if/else execute (depending on condition) the statement immediately following one of them (see here), and indentation is ignored (unlike in, e.g., Python, where indentation alone determines boundaries of conditions, loops, function etc), so only cout << ... is conditionally executed. To do what you want put figure brackets around appropriate statements the same way you already did for the first if branch to create compound statement (block) from them, which is a statement itself and does what you want - groups several other statements within it, executed in sequence:
bool filled_f() { //check if the spot is filled
if (out[x] != 'X' and out[x] != 'O') {
filled = true;
out[x] = player_out; //fill the input into the spot
}
else if (out[x] == 'X' or out[x] == 'O') {
cout << "The square has already been used!\n";
filled = false;
}
return filled;
}
Additional remarks
Note that logically it's not needed to have if condition in else since if the first if condition is dissatisfied, else if condition is definitely satisfied (look De Morgan's Laws) and you can just write else:
// ...
else {
cout << "The square has already been used!\n";
filled = false;
}
// ...
Also in your main loop, you use this:
if (x > 0 && x < 10){ //check if input is in range 1-9
filled_f(); //check if the spot is occupied
}
else if(x < 0 && x > 10) { //if input is out of range
cout << "Invalid! Enter again!\n";
filled = false; //repeat the asking input circle (the while)
}
to test whether x is within range, but your condition in else if is wrong (should be x <= 0 || x >= 10 instead of x < 0 && x > 10) and can be omitted altogether (again see De Morgan's Laws) by using just else.
|
72,900,977 | 72,906,771 | Typecasting from one class to another isnot working | Conversion from SI to ImperialSystem is working but the reverse isnot working.
The error message:
static_cast: cannot convert from ImperialSystem to SI
code:
#include<iostream>
#define endl '\n'
using std::cout;
#define MTRTOFEETRATIO 3.28084;
/*
Write two classes to store distances in meter-centimeter and feet-inch systems respectively. Write conversions functions so that the program can convert
objects of both types.
*/
class SI;
class ImperialSystem {
private:
int mfeet;
int minch;
public:
ImperialSystem(int m, int cm) :mfeet{ m }, minch{ cm }{};
ImperialSystem(float dis) :mfeet{ static_cast<int>(dis) }, minch{ static_cast<int>((dis - mfeet) * 12) } {}
operator float() {
return mfeet + minch / 12.0;
}
operator SI();
friend std::ostream& operator <<(std::ostream& out, const ImperialSystem& dis);
};
class SI {
private:
int mmeter;
int mcentimeter;
public:
SI(int m, int cm) :mmeter{ m }, mcentimeter{ cm }{};
SI(float dis) :mmeter{ static_cast<int>(dis) }, mcentimeter{ static_cast<int>((dis - mmeter) * 12) } {}
operator ImperialSystem();
friend std::ostream& operator <<(std::ostream& out, const SI& dis);
};
std::ostream& operator <<(std::ostream& out, const SI& dis) {
out << " " << dis.mmeter << " m " << dis.mcentimeter << " cm ";
return out;
}
std::ostream& operator <<(std::ostream& out, const ImperialSystem& dis) {
out << " " << dis.mfeet << " ft " << dis.minch << " in ";
return out;
}
ImperialSystem::operator SI() {
double feet = mfeet + minch / 12;
double meter = feet / MTRTOFEETRATIO;
return meter;
}
SI::operator ImperialSystem() {
double meter = mmeter + mcentimeter / 100.0;
double feet = meter * MTRTOFEETRATIO;
return feet;
}
int main() {
SI s{ 20,35 };
cout << s << " = " << static_cast<ImperialSystem>(s) << endl;//this works
ImperialSystem i{ 10,11 };
cout << i << " = " << static_cast<SI>(i) << endl;//but this doesnot
return 0;
}
| Remove,
operator float() {
return mfeet + minch / 12.0;
}
from your SI class.
This creates confusion in construction and casting in msvs and clang compiler.
|
72,901,268 | 73,047,016 | COleDateTimeSpan dates difference returns incorrect value sometimes | I am using the following code to find the difference between two dates basically one is current system date and another server date. I am getting different values at different times, hence I changed the format to only include dates and not datetimes. But still the difference of values remains the same issue. Issue as mentioned in the src line comments.
//dtHigher retrieved from a file from Server
COleDateTime datetimetmp = COleDateTime::GetCurrentTime();
CString strhigherDt = dtHigher.Format(_T("%d/%m/%Y")); //12/07/2022
CString strcurrentDt = datetimetmp.Format(_T("%d/%m/%Y")); //07/07/2022
COleDateTime dateHigher, dateCurrent;
dateHigher.ParseDateTime(strhigherDt);
dateHigher.ParseDateTime(strcurrentDt);
COleDateTimeSpan spanDays = dateHigher - dateCurrent;
CString strdatespan = spanDays.Format(_T("%D.%H.%M.%S")); //this gives some times 4.23.59.59, some times 5.00.00.00
int daysRem = (int) ::ceil(spanDays.GetTotalDays()); //based on above return value, its either 4 or 5
| Hello I was able to solve it by getting the date, month and year separately from COleDateTime class and getting the difference manually. Thanks for all the help.
|
72,901,339 | 72,904,766 | Is it possible to use a literal double if a given template type doesn't have a method that returns a double | Here's my problem, I have a class Foo() which holds two doubles, its value and an extra one:
class Foo {
public:
Foo(double value, double extra) :
value_(value), extra_(extra) {
}
operator double() const
{
return value_;
}
double extra() const {
return extra_;
}
private:
double value_;
double extra_;
};
I want to be able to access the value_ as if it was a literal double, hence the double() operator, but I also want to access its extra value.
Now say I have a template class that holds a Foo and a literal double, and can access the value and extra value of both (extra value of literal doubles should always be 1):
template <typename T1, typename T2>
class Testing {
public:
Testing(T1 a, T2 b) :
a_(a), b_(b) {
}
void test() {
double valA = a_;
double valB = b_
std::cout << valA << " " << valB << std::endl;
double extraA = a_->extra();
double extraB = b_->extra();
std::cout << extraA << " " << extraB << std::endl;
}
private:
T1 a_;
T2 b_;
};
This obviously doesn't compile, because double doesn't have any extra() method.
Would there be any way to implement this and say something (in compile time) like, if either type T1 or T2 doesn't have an extra() method, simply use 1 when calling extra?
The only thing I've come up with that works are these operators for Foo (which I wouldn't use either way):
double operator*(const double& rhs) const
{
return extra() - 1;
}
double operator/(const double& rhs) const
{
return value_;
}
(I had to use the division operator instead of double() to avoid ambiguity)
Combined with this:
void test() {
double valA = a_/1;
double valB = b_/1;
std::cout << valA << " " << valB << std::endl;
double extraA = a_*0 + 1;
double extraB = b_*0 + 1;
std::cout << extraA << " " << extraB << std::endl;
}
But I don't think this is very elegant. A more "readable" option could be to have a wrapper class around double that has the extra() method, but considering I would be working with many of these values I don't like the memory overhead. EDIT: This wouldn't work, I need the double to be literal.
Thanks for the help, I would also be intereted in knowing whether there are would be any performance issues with the aforementioned possible solution.
| To me it sounds like you could do several things. Either Testing should not be a template and only have Foo members, so that you can use a converting constructor for Foo,
Foo(double value, double extra = 1);
to allow implicit conversion from a single double. Or, as you say, another Foo-like class whose extra() simply returns 1.
Otherwise, you could obtain the extra value using functions like these:
template<typename T>
double extra(T const&) { return 1; }
double extra(Foo const& foo) { return foo.extra(); }
|
72,901,652 | 72,901,803 | Applying a function to a parameter pack | I'm playing around with parameter packs, and I'm trying to apply a mapping via a lambda function which adds 1 to each member of the parameter pack as shown. However, I get the output 4 while 234 is expected.
#include <iostream>
// method to print a variadic list of arguments
template<typename... Args>
void print(const Args &... args) {
(std::cout << ... << args) << std::endl;
}
// transform each element of argument list
// and then perfect forward the result
template<typename F, typename... Args>
auto mapping(F f, Args &&... args) {
return (f(std::forward<Args>(args)), ...);
}
int main() {
print(1,2,3); // 123 (OK)
print(mapping([](auto &&a) {return a + 1;}, 1, 2, 3)); // 4 (!) (234 expected)
}
How do I pass the mapped parameter pack 1,2,3 --> 2,3,4 to the variadic function print above?
| You can't return a parameter pack. The closest thing is std::tuple.
Something like this:
template<typename F, typename ...Args>
auto mapping(F f, Args &&... args)
{
// Note `{...}` instead of `(...)`, forcing the call order of `f`.
return std::tuple{f(std::forward<Args>(args))...};
}
You'll need to modify your printing function to accept tuples too.
|
72,901,883 | 72,913,274 | why is linking to libOpenCL.dylib failing with undefined symbol | I am trying to build the pocl library on MacOS
System:
MBP 16" 2019
Intel i9, AMD Radeon 5500m
Mac OS 12.4
using bash, instead of zsh
llvm from home-brew, -version 14
I have the following in my .bash_profile to setup the build environment
export PATH=/usr/local/opt/llvm/bin:$PATH
export CC=clang
export CMAKE_C_COMPILER=clang
export CXX=clang++
export CMAKE_CXX_COMPILER=clang++
I go and clone the repo with git, cd into the source directory, mkdir build
Then in build/ run:
cmake .. -DENABLE_TESTS=OFF -DENABLE_EXAMPLES=OFF -DENABLE_ICD=OFF
The config seems to work and then when I run make everything builds, and gets to the end but then gives me the following error:
[100%] Linking C executable poclcc
clang-14: warning: argument unused during compilation: '-pie' [-Wunused-command-line-argument]
Undefined symbols for architecture x86_64:
"_clBuildProgram", referenced from:
_main in poclcc.c.o
_poclu_load_program_multidev in libpoclu.a(misc.c.o)
"_clCreateCommandQueue", referenced from:
_poclu_get_any_device2 in libpoclu.a(misc.c.o)
_poclu_get_multiple_devices in libpoclu.a(misc.c.o)
"_clCreateContext", referenced from:
_main in poclcc.c.o
_poclu_get_any_device2 in libpoclu.a(misc.c.o)
_poclu_get_multiple_devices in libpoclu.a(misc.c.o)
"_clCreateContextFromType", referenced from:
_poclu_create_any_context in libpoclu.a(misc.c.o)
"_clCreateProgramWithBinary", referenced from:
_poclu_load_program_multidev in libpoclu.a(misc.c.o)
"_clCreateProgramWithIL", referenced from:
_poclu_load_program_multidev in libpoclu.a(misc.c.o)
"_clCreateProgramWithSource", referenced from:
_main in poclcc.c.o
_poclu_load_program_multidev in libpoclu.a(misc.c.o)
"_clGetDeviceIDs", referenced from:
_main in poclcc.c.o
_poclu_get_any_device2 in libpoclu.a(misc.c.o)
_poclu_get_multiple_devices in libpoclu.a(misc.c.o)
"_clGetDeviceInfo", referenced from:
_main in poclcc.c.o
_poclu_load_program_multidev in libpoclu.a(misc.c.o)
"_clGetPlatformIDs", referenced from:
_main in poclcc.c.o
_poclu_create_any_context in libpoclu.a(misc.c.o)
_poclu_get_any_device2 in libpoclu.a(misc.c.o)
_poclu_get_multiple_devices in libpoclu.a(misc.c.o)
"_clGetProgramBuildInfo", referenced from:
_main in poclcc.c.o
_poclu_show_program_build_log in libpoclu.a(misc.c.o)
"_clGetProgramInfo", referenced from:
_main in poclcc.c.o
_poclu_show_program_build_log in libpoclu.a(misc.c.o)
"_clReleaseContext", referenced from:
_main in poclcc.c.o
"_clReleaseProgram", referenced from:
_main in poclcc.c.o
ld: symbol(s) not found for architecture x86_64
I checked and libOpenCL.dylib was successfully built in the pocl/build/lib/CL/ directory. Just as a check, I tried compiling clinfo with a direct link to this library and it gave me the same set of error messages shown above.
Running nm libOpenCL.dylib | grep clBuildProgram prints the following:
0000000000013850 t _clBuildProgram
So its in there, but it is a local text section symbol. I don't actually know what that means though, and if that means it should work, or should not work. I don't actually understand what the problem is here or why this linking is failing, or what to do about it. Looking for some guidance on that.
| The meaning of the lower case t is that the symbols are local, i.e. not externally visible to linking programs. Upper case T would be externally visible.
POCL has a number of configuration options, not all of which are documented in the Build section of the docs. The VISIBILITY_HIDDEN option is on by default unless the ENABLE_PROXY option is on.
In build/, running:
cmake .. -DENABLE_ICD=OFF -DVISIBILITY_HIDDEN=OFF
and then:
make
the compile succeeds to the end. Then in build/lib/CL/ running:
nm libOpenCL.dylib | grep clBuildProgram
now prints:
0000000000013790 T _clBuildProgram
|
72,902,751 | 72,905,144 | Is it defined behavior to explicitly call a destructor and then use placement new to reconstruct it? | This is very similar to Correct usage of placement-new and explicit destructor call but tighter in scope:
If I have a type, S, for which std::is_nothrow_default_constructible_v<S> and std::is_nothrow_destructible_v<S> and not std::has_virtual_destructor_v<S> and not std::is_polymorphic_v<S>, is it defined behavior to call this function?:
template <typename T>
void reconstruct(T& x) noexcept {
// C++20: requires instead of static_assert:
static_assert(std::is_nothrow_default_constructible_v<T>);
static_assert(std::is_nothrow_destructible_v<T>);
static_assert(!std::has_virtual_destructor_v<T>);
static_assert(!std::is_polymorphic_v<T>);
x.~T();
::new (&x) T{};
}
What if there are existing pointers or references to, as in
int main() {
S s;
s.x = 42;
const S& sref = s;
reconstruct(s);
return sref.x; // Is this UB because the original S sref references no longer exists?
}
My reason to ask this is that std::once_flag has no reset mechanism. I know why it generally can't and it would be easy to misuse, however, there are cases where I'd like to do a thread-unsafe reset, and I think this reconstruction pattern would give me what I want provided this reconstruction is defined behavior.
https://godbolt.org/z/de5znWdYT
| Unfortunately, sometimes it is defined behavior, and other times you have to run the pointer through std::launder. There are a number of cases where the compiler may assume that the object hasn't changed, particularly if there are references or const fields in struct S. More information is available in the cppreference section on storage reuse.
In the particular code that you show, you will run into problems if S is a base class of the complete object, because the compiler could, for example, be caching to wrong vtable somewhere.
In a bit more detail, this is something that has changed between C++17 and C++20. In C++17 and earlier, you need to call std::launder when S contains any const or reference fields. However, that particular requirement has been relaxed in C++20, though there are still other restrictions.
|
72,903,031 | 72,903,364 | PI Approximation not approximating right | i just started on C++ and i tried to convert my working PI approximation JS code to C++
But when compiling my C++ it doesn't approximate correctly...
I think it's because i'm not using double variables at the right way.
Here's my code:
#include <iostream>
using namespace std;
double four = 4, pi = 4, num = 1;
bool lever = false;
int calcpi() {
while (true) {
num = num +2;
if (lever) {
lever = false;
pi = (four/num) - pi;
} else if(lever == false){
lever = true;
pi = (four/num) + pi;
}
cout << pi <<"\n";
}
}
int main(){
calcpi();
}
| It looks like you're implementing the approximation
π = 4 – 4/3 + 4/5 – 4/7 + 4/9 – …
In that case, the line pi = (four/num) - pi; is backwards. It should be pi = pi - (four/num);, which represents the subtraction terms.
Also, subtraction from the initial value of 4 should be the first operation, so the lever flag should be initialized to true.
Here's the modified version that I got working after a little bit of troubleshooting.
void calcpi() {
double pi = 4.0, num = 1.0;
bool lever = true;
for (int i = 0; i < 1000; i++) {
num = num + 2.0;
if (lever) {
lever = false;
pi = pi - (4.0 / num);
}
else {
lever = true;
pi = pi + (4.0 / num);
}
std::cout << pi << std::endl;
}
}
This does give a slowly converging approximation of Pi.
|
72,903,637 | 72,903,675 | check string equal with regex | I have a simple question.
How would i check if my string equals another string if that string has changing numbers at the end.
Random:1
Random (1):1
Random (2):1
Random (3):1
Random (4):1
So on...
and also with a string like this
Random
Random_1
Random_2
Random_3
Random_4
So on...
| You need std::regex_match and std::regex from <regex>:
#include <regex>
bool match(const char* cstr)
{
static auto re = std::regex("Random \\([0-9]*\\):1"); // or whatever regex you'd like
return std::regex_match(cstr, re);
}
|
72,903,966 | 72,903,990 | My C++ code seems to stop in the middle of a for loop | I've been practicing USACO questions and I solved the problem but my code just randomly stops executing in the second for loop.
Code:
#include <vector>
#include <string>
using namespace std;
int main()
{
int R = 0;
int C = 0;
cin >> R >> C;
vector<vector<char>> values;
string temp;
for (int i = 0; i < R; i++)
{
cin >> temp;
values.push_back(vector<char>());
for(int j = 0; j < C; j++)
{
values[i].push_back(temp[j]);
}
}
int counter = 0;
for (int i = 0; i < R; i++)
{
for(int j = 0; j < C; j++)
{
cout << i << " " << j << endl; //for testing purposes
if(values[i][j] == '#')
{
if(values[i+1][j] != 'a' && values[i-1][j] != 'a' && values[i][j+1] != 'a' && values[i][j-1] != 'a')
{
values[i][j] = 'a';
counter += 1;
}
}
}
}
cout << counter << endl;
return 0;
}
Input:
.#....
..#...
..#..#
...##.
.#....
Output:
0 0
0 1
0 2
0 3
0 4
0 5
1 0
1 1
1 2
1 3
1 4
1 5
2 0
2 1
2 2
2 3
2 4
2 5
3 0
3 1
3 2
3 3
3 4
3 5
4 0
4 1
The for loop just stops executing at i = 4 and j = 1, and the program crashes. Please help my identify the problem! Any help is appreciated.
| When i equals zero then values[i-1][j] is an out of bounds access on your vector.
When i equals R-1 then values[i+1][j] is an out of bounds access on your vector.
Similar errors exist for j.
|
72,904,426 | 72,913,967 | Moving objects can change the order destructors are called. Why isn't that a problem? | In the following example, a mutex is used to protect a file:
#include <fstream>
#include <memory>
#include <mutex>
std::mutex m;
int main() {
std::unique_ptr<std::lock_guard<std::mutex>> ptr_1 = std::make_unique<std::lock_guard<std::mutex>>(m);
std::fstream file_1("file_name.txt");
std::unique_ptr<std::lock_guard<std::mutex>> ptr_2{std::move(ptr_1)};
}
When the destructors are called, the mutex will be unlocked before the file is closed. This can cause a race condition. It seems to me that there must be some guideline about move-operations, destructors, or ownership that I don't know about. What design guideline has been broken?
| There are two guidelines/best practices that I see are violated here.
The first is enshrined in the C++ Core Guidelines as R.5:
Prefer scoped objects, don’t heap-allocate unnecessarily
Using heap allocation removes the structure afforded by the lexical scoping rules in C++. It is effectively an assertion that the programmer will manage lifetimes.
If you do not heap-allocate, the code doesn't compile:
std::lock_guard<std::mutex> lg_1{m};
std::fstream file_1("file_name.txt");
std::lock_guard<std::mutex> lg_2{std::move(lg_1)};
The second is CP.50:
Define a mutex together with the data it guards
The spirit of that rule is to encapsulate the synchronization. Put the data and lock together, and expose an API that is more difficult to misuse. Many designs would still have an RAII guard, because that is a flexible option, so you still have to put that on the stack. A guard type isn't strictly necessary though.
|
72,904,457 | 72,904,537 | How in multimap run for range from to? | I need to go from the beginning +3 and from the end -3
that is, if the total size is 10, then I have to iterate from 3 to 7
who it doesnt work?
std::multimap<int,int> _multimap;
for(auto it = _multimap.begin() + 3; it != _multimap.end() - 3; it++) {
std::cout << it->first;
}
| The problem is that the class template std::multimap does not have random access iterators. It has bidirectional iterators.
So you may not write
_multimap.begin() + 3
or
_multimap.end() - 3
Instead you could write the for loop the following way using standard function std::next and std::prev
#include <iterator>
//...
for( auto first = std::next( _multimap.begin(), 3 ),
last = std::prev( _multimap.end(), 3 );
first != last;
++first ) {
/// TODO: something happen
}
Here is a demonstration program.
#include <iostream>
#include <map>
#include <iterator>
int main()
{
std::multimap<int, char> m =
{
{ 65, 'A' }, { 66, 'B' }, { 67, 'C' }, { 68, 'D' }, { 69, 'E' },
{ 70, 'F' }, { 71, 'G' }, { 72, 'H' }, { 73, 'I' }, { 74, 'J' },
};
for ( auto first = std::next( std::begin( m ), 3 ), last = std::prev( std::end( m ), 3 );
first != last;
++first )
{
std::cout << first->first << ": " << first->second << '\n';
}
}
The program output is
68: D
69: E
70: F
71: G
If you want to have the range of elements [3, 7 ] then instead of
last = std::prev( std::end( m ), 3 )
you need to write
last = std::prev( std::end( m ), 2 )
Do not forget to include the header <iterator>.
|
72,904,485 | 72,904,555 | Improve the execution time of a function which manage std::map objects, how? | I have a header file header.hpp in which is declared this function:
#ifndef COMMON_HPP
#define COMMON_HPP
#include <string>
#include <map>
extern std::string func( const std::map <std::string, std::string>& generic_map, const std::string& feat_string )
#endif
and that function is defined in a .cpp file:
#include "header.hpp"
#include <string>
#include <map>
std::string func( const std::map <std::string, std::string>& map_s, const std::string& str )
{
if( map_s.find( str ) == map_s.end() )
{
throw std::runtime_error( "Error!" );
}
return map_s.at( str );
}
Benchmarking registered an execution time of 292 ns in 2684415 iterations. Do you know if there is any way to improve the function in order to make it faster?
| Given how small the code is, there is really not many changes you can make to it, but there are a few:
use the iterator that map::find() returns, you don't need to call map::at() afterwards. You are actually performing the same search 2 times, when you really want to perform it only 1 time.
return a reference to the found value, to avoid making a copy of it (map::at() returns a reference anyway). The exception you are throwing will ensure the returned reference is never invalid.
If you don't need the map to be sorted, use std::unordered_map instead, which is usually faster than std::map for inserts and lookups.
Try this:
const std::string& func( const std::map <std::string, std::string>& map_s, const std::string& str )
{
auto iter = map_s.find( str );
if (iter == map_s.end() )
throw std::runtime_error( "Error!" );
return iter->second;
}
That being said, if you don't mind what kind of error message is thrown, you can replace map::find() with map::at(), since map::at() throws its own std::out_of_range exception if the key is not found (that is the whole purpose of map::at() vs map::operator[]), eg:
const std::string& func( const std::map <std::string, std::string>& map_s, const std::string& str )
{
return map_s.at( str );
}
|
72,904,549 | 72,909,549 | How to use C++ struct array for QML ComboBox? | I've got a struct with two fields, for example:
struct testStruct
{
Q_GADGET
Q_PROPERTY(QString text MEMBER m_text);
Q_PROPERTY(QString value MEMBER m_value);
public:
QString m_text;
QString m_value;
};
There is a QList<testStruct> m_testStructs member of my "AppEngine" class exposed to QML via
Q_PROPERTY(QList<testStruct> testStructs READ testStructs NOTIFY testStructsChanged).
It is filled like that:
testStruct newStruct1, newStruct2;
newStruct1.m_text = "text1";
newStruct1.m_value = "value1";
newStruct2.m_text = "text2";
newStruct2.m_value = "value2";
m_testStructs << newStruct1 << newStruct2;
So I want to see "text" members in ComboBox list and use "value" members in further operations.
In fact QML ComboBox popup shows me the list of objects names when I set ComboBox's "textRole" property to "text" and "valueRole" to "value", but it does nothing for "currentText" or "currentValue" properties when I click the item, only "currentIndex" changes. Also "displayText" remains blank.
This is what I get in console when clicking those items:
qml: currentIndex: 0; currentText: ; currentValue: undefined
qml: currentIndex: 1; currentText: ; currentValue: undefined
So I see that ComboBox gets members of struct, but doesn't want to work with them. What should I do to make "currentText" and "currentValue" members of ComboBox work as they should?
Here are all the needed files:
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "appengine.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(u"qrc:/qml_testComboBoxStruct/main.qml"_qs);
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
//exposing AppEngine class to QML
AppEngine appEngineObj;
QQmlContext *context = engine.rootContext();
context->setContextProperty("AppEngine", &appEngineObj);
engine.load(url);
return app.exec();
}
my custom class header AppEngine.h
#ifndef APPENGINE_H
#define APPENGINE_H
#include <QObject>
#include <QDebug>
struct testStruct
{
Q_GADGET
Q_PROPERTY(QString text MEMBER m_text);
Q_PROPERTY(QString value MEMBER m_value);
public:
QString m_text;
QString m_value;
};
Q_DECLARE_METATYPE(testStruct)
class AppEngine : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<testStruct> testStructs READ testStructs NOTIFY testStructsChanged);
public:
explicit AppEngine(QObject *parent = nullptr);
QList<testStruct> testStructs();
private:
QList<testStruct> m_testStructs;
signals:
void testStructsChanged();
};
#endif // APPENGINE_H
my custom class cpp file AppEngine.cpp
#include "appengine.h"
AppEngine::AppEngine(QObject *parent)
: QObject{parent}
{
testStruct newStruct1, newStruct2;
newStruct1.m_text = "text1";
newStruct1.m_value = "value1";
newStruct2.m_text = "text2";
newStruct2.m_value = "value2";
m_testStructs << newStruct1 << newStruct2;
qDebug() << "m_testStructs.length():" << m_testStructs.length();
}
QList<testStruct> AppEngine::testStructs()
{
qDebug() << "testStructs()";
return m_testStructs;
}
main.qml
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("C++ struct to QML ComboBox")
ComboBox
{
anchors.centerIn: parent
width: 180
height: 30
id: comboBoxID
textRole: "text"
valueRole: "value"
model: AppEngine.testStructs
onActivated:
{
console.log('currentIndex:', currentIndex, '; currentText:', currentText, ';currentValue:', currentValue);
}
}
}
| As I checked in the main.qml model property cant find and understand as you show it is undefined.
qml: currentIndex: 0; currentText: ; currentValue: undefined
qml: currentIndex: 1; currentText: ; currentValue: undefined
from ListView::model property
The model provides the set of data that is used to create the items in
the view. Models can be created directly in QML using ListModel,
ObjectModel, or provided by C++ model classes. If a C++ model class is
used, it must be a subclass of QAbstractItemModel or a simple list.
For example, you can have this :
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("C++ struct to QML ComboBox")
ComboBox
{
id: comboBoxID
anchors.centerIn: parent
width: 180
height: 30
textRole: "text"
valueRole: "value"
model: ListModel {
id : model
ListElement { text: "text1" ; value : "value1" }
ListElement { text: "text2" ; value : "value2" }
ListElement { text: "text3" ; value : "value3" }
ListElement { text: "text4" ; value : "value4" }
}
onActivated:
{
console.log('currentIndex:', currentIndex, '; currentText:', currentText, '; currentValue:', currentValue);
}
}
}
Because you use QML ListModel if you want to define your model from C++ it must be a subclass of QAbstractItemModel or a simple list.
updated :
you need to use QStandardItemModel which inherits from QAbstractItemModel you cant inherit from the abstract interface because of that I use QStandardItemModel
in appengine.h:
#ifndef APPENGINE_H
#define APPENGINE_H
#include <QObject>
#include <QDebug>
#include <QStandardItemModel>
struct testStruct: public QStandardItemModel
{
Q_OBJECT
Q_PROPERTY(QString text MEMBER m_text);
Q_PROPERTY(QString value MEMBER m_value);
public:
QString m_text;
QString m_value;
};
Q_DECLARE_METATYPE(testStruct)
class AppEngine : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<testStruct *> testStructs READ testStructs NOTIFY testStructsChanged);
public:
explicit AppEngine(QObject *parent = nullptr);
QList<testStruct *> testStructs();
private:
QList<testStruct *> m_testStructs;
signals:
void testStructsChanged();
};
#endif // APPENGINE_H
In appengine.cpp
#include "appengine.h"
AppEngine::AppEngine(QObject *parent)
: QObject{parent}
{
testStruct *newStruct1 = new testStruct;
testStruct *newStruct2 = new testStruct;
newStruct1->m_text = "text1";
newStruct1->m_value = "value1";
newStruct2->m_text = "text2";
newStruct2->m_value = "value2";
m_testStructs << newStruct1 << newStruct2;
qDebug() << "m_testStructs.length():" << m_testStructs.length();
}
QList<testStruct *> AppEngine::testStructs()
{
qDebug() << "testStructs()";
return m_testStructs;
}
|
72,904,666 | 72,904,947 | Transmit data to an adress stm32CubeIde | I am newly working on Stm32CubeIde and I am trying to understand how it works. I would like to transmit data to a specific address using the UART port and I don't know how to do it. So far I have been able to transmit using these three methods:
using the poll —> HAL_UART_Transmit
using the interrupt —> HAL_UART_Transmit_IT
using DMA —> HAL_UART_Transmit_DMA
but none of them in their implementation refer to transmitting to a specific address.
Can someone help me ?
| The UART hardware will transmit a series of high a low voltages onto the wire. RS232 and RS422 are full duplex so there is only a single receiver. RS485 is half duplex so there can be multiple receivers listening to the same data. How that data is framed including which receiver the data is for depends on the higher level protocol like Modbus
|
72,904,741 | 72,905,097 | Can I make separate definitions of function template members of a class template? | Here's a minimal code example to show what I'm attempting that works, but not how I'd like it to:
#include <string>
#include <type_traits>
#include <iostream>
struct string_tag {
using R=const std::string;
};
struct int_tag {
using R=const int;
};
template <bool TS>
class Wibble {
public:
template<typename TAG>
typename TAG::R getValue(TAG);
};
template <bool TS>
template <typename TAG>
typename TAG::R Wibble<TS>::getValue(TAG) {
if constexpr (std::is_same<TAG, string_tag>::value) {
return "hello";
}
if constexpr (std::is_same<TAG, int_tag>::value) {
return 42;
}
}
// instantiate classes
template class Wibble<true>;
template class Wibble<false>;
int main () {
Wibble<true> tw;
Wibble<false> fw;
std::cout << "tw string: " << tw.getValue(string_tag{}) << std::endl;
std::cout << "tw int: " << tw.getValue(int_tag{}) << std::endl;
std::cout << "fw string: " <<fw.getValue(string_tag{}) << std::endl;
std::cout << "fw int: " << fw.getValue(int_tag{}) << std::endl;
}
example in godbolt here
The part I want to change is the ugly function template definition with all the constexpr logic. I'd like to be able to define the different specializations in TAG standalone, but doing this gives me redefinition of ... errors.
Syntax like the following would be nice:
template<bool TS>
template<>
string_tag::R Wibble<TS>::getValue(string_tag) {
return "hello";
}
but computer says "no".
| I gave it a thought, read language specs etc. and the following things come to my mind:
Class template has to be specialized in order to specialize member function template. Period. This cannot be overcome with concepts, or at least I haven't found a way. I guess you don't want to replicate the code for each case of TS. Maybe it can be done automagically with some Alexandrescu-style metaprogramming techniques, but I can't think of anything right off the bat.
Overloads instead of templates are a good alternative but I'm guessing you'd like to be able to add them out-of-line, instead of inside the class...
Then I recalled David Wheeler: “All problems in computer science can be solved by another level of indirection." So let's add one:
namespace detail
{
template<typename TAG> auto getValue(TAG);
template<>
auto getValue<string_tag>(string_tag)
{
return "hi";
}
template<>
auto getValue<int_tag>(int_tag)
{
return 42;
}
template<>
auto getValue<double_tag>(double_tag)
{
return 1324.2;
}
}
template<bool TS>
template<typename TAG>
auto Wibble<TS>::getValue(TAG t)
{
return detail::getValue(t);
}
https://godbolt.org/z/GsPK4MP8M
Hope it helps.
|
72,905,028 | 72,905,107 | Is there a way to have a C or C++ program open a new terminal window and start executing code for you? | I want to create a C or C++ program that automates some things for me.
The idea is as such: I run the program ./a.out and sit back and watch as it opens up three or four new terminal windows and runs various UNIX commands. Is there a way to do this?
I am on a MacBook.
| As the comments point out, this is probably best accomplished by a shell script. However, you can execute shell commands from C with the system(3) standard library function. To open a terminal, just run a terminal with a particular command. For example:
system("xterm -e 'echo hello; sleep 5'");
|
72,905,471 | 72,905,654 | Why is my console not showing up when my Dll is loaded? | I have two files, the file which I'll use to load the Dll into the process is the following:
#include <Windows.h>
int main()
{
// path to our dll
LPCSTR DllPath = any_path;
// Open a handle to target process
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, 26188);
// Allocate memory for the dllpath in the target process
// length of the path string + null terminator
LPVOID pDllPath = VirtualAllocEx(hProcess, 0, strlen(DllPath) + 1,
MEM_COMMIT, PAGE_READWRITE);
// Write the path to the address of the memory we just allocated
// in the target process
WriteProcessMemory(hProcess, pDllPath, (LPVOID)DllPath,
strlen(DllPath) + 1, 0);
// Create a Remote Thread in the target process which
// calls LoadLibraryA as our dllpath as an argument -> program loads our dll
HANDLE hLoadThread = CreateRemoteThread(hProcess, 0, 0,
(LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("Kernel32.dll"),
"LoadLibraryA"), pDllPath, 0, 0);
// Wait for the execution of our loader thread to finish
WaitForSingleObject(hLoadThread, INFINITE);
// Free the memory allocated for our dll path
VirtualFreeEx(hProcess, pDllPath, strlen(DllPath) + 1, MEM_RELEASE);
return 0;
}
So far, it's working properly and loading the Dll into the file, however, the Dll doesn't seem to be working:
#include "pch.h"
#include <iostream>
#include <windows.h>
#include <TlHelp32.h>
DWORD WINAPI HackThread(HMODULE hModule)
{
//Create Console
AllocConsole();
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);
std::cout << "ttt" << std::endl;
std::cin.get();
fclose(f);
FreeConsole();
FreeLibraryAndExitThread(hModule, 0);
return 0;
}
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)HackThread, hModule, 0, nullptr);
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
I know the Dll is loading properly because the process is hitting the 'DLL_PROCESS_ATTACH' case and when I tested it with a message box instead of the CreateThread, it showed up, however, I can't seem to make the console show up. What would be the problem?
| One issue I see is that your thread is re-mapping only stdout to the new console, but it is not re-mapping stdin as well. So it is quite likely (use a debugger to verify this) that std::cin.get() is failing and thus not blocking the thread from closing the console immediately after creating it.
|
72,905,675 | 72,906,198 | Macros not expanding properly | I have these macros defined:
#define AL_ASSERT_NO_MSG(x) if (!(x)) { assertDialog(__LINE__, __FILE__); __debugbreak(); }
#define AL_ASSERT_MSG(x, msg) if (!(x)) { assertDialog(msg, __LINE__, __FILE__); __debugbreak(); }
#define GET_MACRO(_1, _2, NAME, ...) NAME
#define AL_ASSERT(...) GET_MACRO(__VA_ARGS__, AL_ASSERT_MSG, AL_ASSERT_NO_MSG)(__VA_ARGS__)
I wanted to have it dispatched to the AL_ASSERT_NO_MSG macro if I only pass one argument and AL_ASSERT_MSG if I pass two arguments.
However, when I use the macro like this: AL_ASSERT(false, "Test") it expanded to if (!(false, "Test")) { assertDialog(23, "C:\\Dev\\c++\\SortingAlgorithms\\AlgorithmVisualizer\\src\\Window.cpp"); __debugbreak(); }; and it does not work.
More information: I am using Visual Studio with MSVC. This is not a solution-based project but a CMake project opened as a folder.
What did I do wrong? Any help is appreciated.
| It seems that MSVC does not expand __VA_ARGS__ into multiple arguments (see this related question: MSVC doesn't expand __VA_ARGS__ correctly)
This seems to work:
#define GET_MACRO(_1, _2, NAME, ...) NAME
#define XGET_MACRO(args) GET_MACRO args
#define AL_ASSERT(...) XGET_MACRO((__VA_ARGS__, AL_ASSERT_MSG, AL_ASSERT_NO_MSG))(__VA_ARGS__)
And if you are targeting C++20 (and have Visual Studio 2019 version 16.5), you can use __VA_OPT__:
#define AL_ASSERT(x, ...) if (!(x)) { assertDialog(__VA_OPT__( (__VA_ARGS__) , ) __LINE__, __FILE__); __debugbreak(); }
Or you can do it with some functions:
#define AL_ASSERT(x, ...) (([](bool b, const auto*... msg) { \
static_assert(sizeof...(msg) <= 1, "AL_ASSERT passed too many arguments"); \
if (!b) { \
if constexpr (sizeof...(msg) == 1) { \
const char* m{msg...}; \
assertDialog(msg, __LINE__, __FILE__); \
} else { \
assertDialog(__LINE__, __FILE__); \
} \
__debugbreak();
})(x, __VA_ARGS__))
And with version 16.10 you can do it without a macro with std::source_location:
void AL_ASSERT(bool x, const std::source_location location = std::source_location::current()) {
if (!x) {
assertDialog(location.line(), location.file_name());
__debugbreak();
}
}
void AL_ASSERT(bool x, const char* msg, const std::source_location location = std::source_location::current()) {
if (!x) {
assertDialog(msg, location.line(), location.file_name());
__debugbreak();
}
}
|
72,905,721 | 72,906,890 | Is there a good way to make vscode intellisense detect g++ gcm files generated from -xc++-system-header flag for importing? | I'm trying to dabble with the c++20 modules feature and would like to import the standard library headers as modules. Currently I have
import <iostream>;
int main()
{
std::cout << "hello world!" << std::endl;
return 0;
}
and I run the commands
g++-11 -fmodules-ts -std=c++20 -xc++-system-header iostream
g++-11 -fmodules-ts -std=c++20 -o program main.cpp
This gives a perfectly functioning hello world program and a module file at gcm.cache/usr/include/c++/11/iostream.gcm. But vscode complains:
"iostream" is not an importable header
My c_cpp_properties.json file is
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"compilerPath": "/usr/bin/g++-11",
"cStandard": "c17",
"intelliSenseMode": "linux-clang-x64",
"cppStandard": "c++20"
}
],
"version": 4
}
Possible solutions that I don't know how to implement:
A way to tell vscode where this iostream.gcm file is
An alternative way of doing this where the iostream.gcm object ends up somewhere vscode already knows
| This is the known IntelliSense issue.
When importing C++20 modules or header units in C++ source:
You may not see IntelliSense completions or colorization.
You may see red squiggles that don’t match the compiler.
Status (as of June 2022)
Workaround
#if __INTELLISENSE__
#include <iostream>
#else
import <iostream>;
#endif
|
72,906,106 | 72,909,435 | Can somebody explain the mathematics of this Color Balance formula? | I have found a good example of a Color Balance implementation here and was wondering if someone could explain the derivation of these formula's:
float DR=(1-cr_val)*R1+(cr_val)*R2-0.5;
float DG=(1-cr_val)*G1+(cr_val)*G2-0.5;
float DB=(1-cr_val)*B1+(cr_val)*B2-0.5;
The full code is here:
#include <iostream>
#include <vector>
#include <stdio.h>
#include <functional>
#include <algorithm>
#include <numeric>
#include <cstddef>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int val_Cyan_Red=0;
int val_Magenta_Green=0;
int val_Yellow_Blue=0;
Mat result;
Mat Img;
void on_trackbar( int, void* )
{
float SH=0.1; // The scale of trackbar ( depends on ajusting mode Shadows/Midtones/Highlights )
float cr_val=(float)val_Cyan_Red/255.0;
float mg_val=(float)val_Magenta_Green/255.0;
float yb_val=(float)val_Yellow_Blue/255.0;
// Cyan_Red
float R1=0;
float G1=1;
float B1=1;
float R2=1;
float G2=0;
float B2=0;
float DR=(1-cr_val)*R1+(cr_val)*R2-0.5;
float DG=(1-cr_val)*G1+(cr_val)*G2-0.5;
float DB=(1-cr_val)*B1+(cr_val)*B2-0.5;
result=Img+(Scalar(DB,DG,DR)*SH);
// Magenta_Green
R1=1;
G1=0;
B1=1;
R2=0;
G2=1;
B2=0;
DR=(1-mg_val)*R1+(mg_val)*R2-0.5;
DG=(1-mg_val)*G1+(mg_val)*G2-0.5;
DB=(1-mg_val)*B1+(mg_val)*B2-0.5;
result+=(Scalar(DB,DG,DR)*SH);
// Yellow_Blue
R1=1;
G1=1;
B1=0;
R2=0;
G2=0;
B2=1;
DR=(1-yb_val)*R1+(yb_val)*R2-0.5;
DG=(1-yb_val)*G1+(yb_val)*G2-0.5;
DB=(1-yb_val)*B1+(yb_val)*B2-0.5;
result+=(Scalar(DB,DG,DR)*SH);
imshow("Result",result);
waitKey(10);
}
// ---------------------------------
//
// ---------------------------------
int main( int argc, char** argv )
{
namedWindow("Image",cv::WINDOW_NORMAL);
namedWindow("Result");
Img=imread("D:\\ImagesForTest\\cat2.jpg",1);
Img.convertTo(Img,CV_32FC1,1.0/255.0);
createTrackbar("CyanRed", "Image", &val_Cyan_Red, 255, on_trackbar);
createTrackbar("MagentaGreen", "Image", &val_Magenta_Green, 255, on_trackbar);
createTrackbar("YellowBlue", "Image", &val_Yellow_Blue, 255, on_trackbar);
imshow("Image",Img);
waitKey(0);
}
Additionally, the OP talks about how changing the scale of the trackbar adjusts the shadows, mid-tones, and highlights. What values would I change it to in order to make changes in those ranges?
| This is just a linear interpolation between C1(R1, G1, B1) and C2(R2, G2, B2).
If you imagine C1 and C2 as points in 3D space, c_val lets you choose a point on the line that goes from C1 to C2.
0 is on C1
1 is on C2
anything in (0,1) is on the line segment between (C1, C2)
anything below 0 or above 1 is extrapolated.
Subtracting 0.5 just changes the space from [0,1] to [-0.5, 0.5]
|
72,907,198 | 72,907,522 | Logfile game from array to file text is not writing anything c++ | I developed a game and everything went well except I want to make a logfile (means data from array to text file) but nothing is coming out for the array. My code:
void writeToFile(ofstream &outputfile, string name, string s2, string s3, string s4, string s5)
{
outputfile << "HI" << endl;
outputfile << endl << endl << "The card that you get is: " << name<<" "<<s2<<" "<<s3<<" "<<s4<<" "<<s5<<endl <<endl;
}
int main ()
{
ofstream outputfile;
outputfile.open("program3data.txt");
int randomnumber=random_number();
count=findwords();
k=count;
int *sr; sr= new int[count];
string *name; name= new string[count];
string *s2; s2= new string[count];
string *s3; s3= new string[count];
string *s4 ; s4 = new string[count];
string *s5 ; s5 = new string[count];
string *s6 ; s6 = new string[count];
writeToFile(outputfile, name[randomnumber],s2[randomnumber],s3[randomnumber],s4[randomnumber],s5[randomnumber]);
}
And my error:
I dont know what to do. It should display the array of the card. If anyone wants the full code, please head to https://github.com/infaddil/beyblade/blob/main/newassver2.cpp
| Look at what your code actually does
Allocate arrays of empty strings
string *name; name= new string[count];
string *s2; s2= new string[count];
string *s3; s3= new string[count];
string *s4 ; s4 = new string[count];
string *s5 ; s5 = new string[count];
string *s6 ; s6 = new string[count];
Call a function with a randomly chosen strings, but because all the strings are empty it is inevitable that empty strings will be chosen
writeToFile(outputfile, name[randomnumber],s2[randomnumber],s3[randomnumber],s4[randomnumber],s5[randomnumber]);
From that function write out the empty strings
outputfile << "HI" << endl;
outputfile << endl << endl << "The card that you get is: " << name<<" "<<s2<<" "<<s3<<" "<<s4<<" "<<s5<<endl <<endl;
Now clearly you did not mean to write out empty strings, but that is what the code you wrote actually does. No doubt there are some other strings somewhere else in your code which are the strings you actually want to write out. But without seeing more of the code I can't really help with that.
EDIT
OK I had a look at the rest of your code. It seems that the strings would want to write out are declared on lines 162 to 167. But for some reason you have declared a completely different set of strings on lines 280 to 285. Even though the variable names are the same they are still a new set of strings. So it seems that all you need to do is delete the declarations on lines 280 to 285 and you will start writing out the correct strings.
I also wonder whether you want to generate a new random number? Surely you want to use the random number that was previously generated.
|
72,907,714 | 72,911,288 | How can I silence all errors of a particular kind in clang-tidy? | I'm currently working on a university assignment where it is mandated that we use C-style arrays for our code. Infuriatingly, they have left the default setting for warning about C-style arrays, which means that every time I use a one I need to add a // NOLINTNEXTLINT(modernize-avoid-c-arrays), which is absolutely terrible in terms of readability.
I have tried silencing the errors using // NOLINTBEGIN(modernize-avoid-c-arrays), but since that was only introduced in clang-tidy-14, it isn't supported by our course-mandated clang-tidy-11.
As such, my only option for a clean way of silencing these errors is by modifying the configuration file. Unfortunately, I haven't found any information on how to silence errors of a particular type in the configuration file. In fact, I haven't found any documentation on the expected structure of the .clang-tidy file at all, except for some example files, none of which appear to silence any errors.
How can I silence the modernize-avoid-c-arrays error on a project-wide basis from my .clang-tidy file?
| Disable a check
To disable a check in .clang-tidy, add a Checks: line, and as its
value put the name of the check, preceded by a hyphen (meaning to
disable rather than enable). For example, here is a complete
.clang-tidy file that first enables all of the modernize-* checks
(since they are not enabled by default), then disables
modernize-avoid-c-arrays:
Checks: 'modernize-*,-modernize-avoid-c-arrays'
Documentation of .clang-tidy format
The .clang-tidy format is (tersely!) specified in the
output of clang-tidy --help:
--config-file=<string> -
Specify the path of .clang-tidy or custom config file:
e.g. --config-file=/some/path/myTidyConfigFile
This option internally works exactly the same way as
--config option after reading specified config file.
Use either --config-file or --config, not both.
However, the --config-file option and its documentation are missing
in Clang+LLVM-11, so that may be why you didn't find it. They are in
Clang+LLVM-14 (I'm not sure which version introduced that option).
Nevertheless, Clang+LLVM-11 responds to the presence of .clang-tidy.
You can use the --dump-config option to have clang-tidy print its
current configuration in the .clang-tidy syntax, then trim or edit as
desired.
Related:
github gist: A general clang-tidy configuration file
SO question: Clang Tidy config format
Complete example
Input source code:
// test.cpp
// Test input for clang-tidy.
void f()
{
int arr[3];
bool b = 1;
}
// EOF
Run using the above .clang-tidy:
$ /home/scott/opt/clang+llvm-11.0.1-x86_64-linux-gnu-ubuntu-16.04/bin/clang-tidy test.cpp --
1 warning generated.
/home/scott/wrk/learn/clang/clang-tidy-config/test.cpp:7:12: warning: converting integer literal to bool, use bool literal instead [modernize-use-bool-literals]
bool b = 1;
^
true
Without disabling modernize-avoid-c-arrays, two warnings would be
printed. (And without enabling modernize-*, nothing is printed.)
|
72,907,820 | 72,911,697 | passing null structure pointer ctypes | I am writing a Python wrapper for cpp APIs in that for one API I am trying to pass a NULL structure pointer as a parameter. Not sure how we can achieve that in Python.
Below is my sample implementation:
cpp_header.hpp
typedef enum {
E_FLAG_ON = 0,
E_FLAG_OFF
} option;
typedef struct {
float *a;
float b;
char *file_path;
option flag;
} inputs;
// API
int op_init(const inputs*);
This is what happening inside the init API:
Implementation.cpp
int op_init(const inputs* usr_ptr) {
internal_opration_read_set(&local_struct) { // local struct variable
// read one input file and update the structure values
}
if (usr_prt != NULL) {
internal_opration_update_set(usr_ptr, &local_struct) {
// update the values only if i send NOT NULL structure
}
}
}
From cpp test application I'm passing NULL structure to initialize.
test.cpp
int main() {
inputs *usr_cfg = NULL;
op_init(usr_cfg);
}
ctypes_imple.py
From ctypes import *
class inputs(Structure):
_fields_ = [('a', POINTER(c_float)),
('b', c_float),
('file_path', c_char_p),
('flag', option)]
# loading so file
so_lib = CDLL('some so')
# how we can initialize NULL structure pointer here?
so_lib.op_init() # how to send structure pointer as argument?
NOTE: this API reads inputs from a file and updates values to a structure in C. I am clueless how we can achieve the same in a Python wrapper? I mean updating values from so file runtime to a ctypes Python class.
| Use None to pass a null pointer:
so_lib.op_init(None)
To send the actual structure instantiate one and send it. Best to define .argtypes and restype as well so ctypes doesn't have to guess and can perform better error checking:
so_lib.op_init.argtypes = POINTER(inputs),
so_lib.op_init.restype = c_int
arg = inputs() # all initialized to zero/null by default.
so_lib.op_init(arg)
|
72,908,252 | 72,908,275 | C++ create chain using struct cause circular reference. nextNode refer to the same address and value | The first call of appendChild work as expected, but then the next point to itself. need an example how to do it.
why LinkNode nextNode; not create a new instance
zsbd
zsbd
zsbd
zsbd
zsbd
zsbd
#include "iostream"
using namespace std;
template<typename T>
struct LinkNode {
T data;
bool hasNext = false;
LinkNode<T> *next = nullptr;
};
template<typename T>
void appendChild(LinkNode<T> &initNode, T &node) {
LinkNode<T> *ptr = &initNode;
while (ptr && ptr->hasNext) {
ptr = ptr->next;
}
// end of the chain
ptr->data = node;
ptr->hasNext = true;
// create new node
LinkNode<T> nextNode;
// append to the end
ptr->next = &nextNode;
cout << "done" << endl;
};
int main() {
int a = 123;
int b = 456;
int c = 789;
LinkNode<int> initNode;
initNode.data = 1;
appendChild(initNode, a);
appendChild(initNode, b);
appendChild(initNode, c);
cout << "finish" << endl;
}
Detail on the pause.
enter image description here
| LinkNode<T> nextNode; This is a local variable. It is destroyed when it goes out of scope. Thus ptr->next = &nextNode; will add the address of a local variable.
Accessing it's address is Undefined Behavior.
edit: a modern solution would be to use std::unique_ptr (we don't use new anymore). E.g.
#include <iostream>
#include <memory>
template<typename T>
struct LinkNode {
T data;
std::unique_ptr<LinkNode<T>> next;
};
template<typename T>
void appendChild(LinkNode<T> & initNode, T &node) {
LinkNode<T> *ptr = &initNode;
while (ptr && ptr->next) {
ptr = ptr->next.get();
}
// end of the chain
ptr->data = node;
// create new node
ptr->next = std::make_unique<LinkNode<T>>();
std::cout << "done\n";
};
int main() {
int a = 123;
int b = 456;
int c = 789;
LinkNode<int> initNode;
initNode.data = 1;
appendChild(initNode, a);
appendChild(initNode, b);
appendChild(initNode, c);
std::cout << "finish\n";
}
|
72,908,385 | 72,908,687 | Lifetime of lambda c++ | I have the following situations and trying to understand the scope of the lambdas
std::future<void> thread_run;
void run(Someclass& dbserver){
thread_run = std::async(std::launch::async, [&]{
dbserver.m_com.run([&dbserver]() {
// implement another nested lambda for the m_com.run method. Does this get destroyed when the main thread leaves the run method.
}
}
}
class dbserver{
Com m_com;
}
class Com{
template<typename F>
void run(F&& func){ // do some stuff here}
}
So we launch a thread with its main lambda function. I am guessing the std::async will take care of the scope of that main lambda function. However, in my application I also invoke a function within the main lambda. That function also requires a lambda.
My question is whether the nested lambda actually has a local scope and therefore could be leading to undefined behaviour or did I miss something that will make it work.
| Create the dbserver before the future and let the future go out of scope before dbserver and you are fine (the future destructor will synchronize with the end of the thread) . If you somehow cannot manage that you may need to use a std::shared_ptr<Someclass> and pass that by value to your lambda to extend the lifetime of the database to that of the thread. (I usually am careful about using std::shared_ptr but I find this is a very good use for it)
|
72,908,482 | 72,909,224 | C++11 Move heap array into std::string | Looking around other answers on stackoverflow the answer may just be a no, but please humor me before marking it a duplicate.
So I want to be able for format a string snprintf style as shown below, but only make a single heap allocation.
Lots of examples say to touch the std::String::data() or std::String::c_str() but obviously you shouldn't do this as it's really unsafe, as this is managed memory, so references and pointers are not guaranteed to be constant memory addresses.
Also cannot use std::format as I'm not running C++20
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstdarg>
#include <cstdio>
std::string Somefunction(const char* formatstring, ...){
//Let's get the actual size, because recursively reallocating to get this is not efficient
va_list sizeVl;
va_start(sizeVl, formatstring);
const int formatSize = _vscprintf(formatstring, sizeVl);
va_end(sizeVl);
if (formatSize < 1){
return{};
}
//Some object to put the memory on the stack, I'll use a char, but could be vector<char> etc,
//whatever achieves the goal
char* tempString = new char[formatSize + 1];
va_list vl;
va_start(vl, formatstring);
const int actualLength = vsnprintf(tempString, formatSize, formatstring, vl);
va_end(vl);
if (actualLength <= formatSize){
tempString[actualLength] = '\0';
//vv--- I really don't want to reallocate on the heap, I already have some heap memory
//vv--- Move semantics 101
//std::string output = MOVE(tempString);
std::string output("Ideally I move the memory here");
return output;
}
delete[] tempString;
return{};
}
Any thoughts, or is the answer really just std::string isn't the container for you if you want this functionality?
Is there any container I can use safely as a char array in the vsnprintf function that std::String will move safely?
| The comments in your question are correctly directing you to instantiate a string with a specific size and use the .data() or &[0] operator to get what you need.
Let me suggest a simpler solution with a constraint. Consider that your output strings have some reasonable length and that you have plenty of stack memory to work with. So use a fixed length temp buffer to do your printf style formatting. 20K is not an unreasonable number of bytes to allocate on the stack.
Then return an instance of a std::string using the copy from C string constructor at the very end.
std::string Somefunction(const char* formatstring, ...){
const size_t TEMP_SIZE = 20000;
va_list vargs = {};
va_start(vargs, formatstring);
char buffer[TEMP_SIZE];
vsnprintf(buffer, TEMP_SIZE, formatstring, vargs);
va_end(vargs);
return std::string(buffer);
}
You could always increase the buffer size from 20000 to something larger if you needed it. But I'm guessing your strings never get that big. And if they did, you wouldn't want that many bytes in what I'm guessing is your log file.
|
72,909,233 | 72,911,178 | Error: invalid use of incomplete type 'class Move' / undefined reference to Move::NONE | Please, I don't know why this simple code is rejected.
It give me 2 compilation errors.
Help me please.
I use Code::Blocks 20.03
My compiler is GNU GCC
---move.hpp---
class Move {
public:
Move();
Move(int, int);
public:
int from;
int to;
const static Move NONE = Move(0,-1); //error here
//undefined reference if I use
//const static Move NONE;
};
---move.cpp---
#include "move.hpp"
Move::Move() {
this->from = 0;
this->to = 0;
}
Move::Move(int from, int to) {
this->from = from;
this->to = to;
}
---main.cpp---
#include <iostream>
#include "move.hpp"
int main(){
Move move = Move::NONE;//error here
std::cout << move.from << std::endl;
std::cout << move.to << std::endl;
return 0;
}
| You should provide an out-of-class definition for the static data member NONE in the source file(like move.cpp) which will work because at that point the class is complete as shown below:
move.hpp
#pragma once
class Move {
public:
Move();
Move(int, int);
public:
int from;
int to;
//declaration for NONE
const static Move NONE ;
//------------------------------^^------>no in class initializer here
};
move.cpp
#include "move.hpp"
//definition for Move::NONE
const Move Move::NONE = Move(0,-1);
Move::Move() {
this->from = 0;
this->to = 0;
}
Move::Move(int from, int to) {
this->from = from;
this->to = to;
}
Working demo
|
72,909,258 | 72,909,955 | switch in switch, does the outer case break if inner case break | In languages that have switch, usually a break; statement is needed. What if a switch within a switch statement? Is it necessary to put a break; statement in the outer switch when the inner switch has a break;? e.g.:
// outer switch
switch (a) {
case 1:
// inner switch
switch (b) { // this inner switch breaks either way.
case (2):
break;
default:
break;
}
break; // is this outer break still necessary?
default:
break;
}
I hope someone can help me to understand the logic more deeply and accurately.
| Both break statements are useful. This gives the language greater flexibility, and it keeps the language itself simpler to work with.
You seem to be thinking of a simple situation, where the nested switch is choosing which one thing to do. This is often a good design. However, what if more needs to be done? There might be more work to do after breaking out of the inner switch.
// outer switch
switch (a) {
case 1:
// inner switch
switch (b) {
case 2:
std::cout << "The b value is acceptable.\n";
break;
default:
std::cout << "The inner default.\n";
break;
}
std::cout << "The first case has finished.\n";
break;
default:
break;
}
If the inner break jumped out of the outer switch in this example, you would never see the output The first case has finished. Limiting the impact of a break allows for more complex code flow. (Not that complex code is desirable, but it's nice to have options.)
On top of that, if your code is not kept simple, it could quickly become difficult to deduce what the impact of a break statement is. You mentioned switch statements, but break statements also affect loops. If a switch is inside a loop, should a break in the switch also break out of the loop? What if the loop was itself inside a switch (that is, if you nest the statements switch - while - switch)? What would you expect a break in the inner switch to do? Exiting everything is unlikely to be desired. Besides, there is already a language feature that allows breaking out of multiple nesting levels (known as return).
There is a design principle that says to keep it simple. If your code is simple, you won't have these monster situations to worry about. At the same time, the principle also applies to language design. If the syntax rules for the language are kept simple (a break statement consistently breaks out of a single statement), then life is easier for the people using the language.
|
72,909,458 | 72,909,642 | Error subtracting hex constant when it ends in an 'E' | int main()
{
0xD-0; // Fine
0xE-0; // Fails
}
This second line fails to compile on both clang and gcc. Any other hex constant ending is ok (0-9, A-D, F).
Error:
<source>:4:5: error: unable to find numeric literal operator 'operator""-0'
4 | 0xE-0;
| ^~~~~
I have a fix (adding a space after the constant and before the subtraction), so I'd mainly like to know why? Is this something to do with it thinking there's an exponent here?
https://godbolt.org/z/MhGT33PYP
| Actually, this behaviour is mandated by the C++ standard (and documented), as strange as it may seem. This is because of how C++ compiles using Preprocessing Tokens (a.k.a pp-tokens).
If we look closely at how the compiler generates a token for numbers:
A preprocessing number is made up of a digit, optionally preceded by a period, and may be followed by letters, underscores, digits, periods, and any one of: e+ e- E+ E-.
According to this, The compiler reads 0x, then E-, which it interprets it as part of the number as having E- is allowed in a numeral pp-token and no space precedes it or is in between the E and the - (this is why adding a space is an easy fix).
This means that 0xE-0 is taken in as a single preprocessing token. In other words, the compiler interprets it as one number, instead of two numbers 0xE and 0 and an operation -. Therefore, the compiler is expecting E to represent an exponent for a floating-point literal.
Now let's take a look at how C++ interprets floating-point literals. Look at the section under "Examples". It gives this curious code sample:
<< "\n0x1p5 " << 0x1p5 // double
<< "\n0x1e5 " << 0x1e5 // integer literal, not floating-point
E is interpreted as part of the integer literal, and does not make the number a hexadecimal floating literal! Therefore, the compiler recognizes 0xE as a single, integer, hexidecimal number. Then, there is the -0 which is technically part of the same preprocessing token and therefore is not an operator and another integer. Uh oh. This is now invalid, as there is no -0 suffix.
And so the compiler reports an error, as such.
|
72,909,703 | 72,910,361 | How to compare two datetime structures in C++ efficiently? | I have the following DateTime structure:
struct DateTime
{
std::uint16_t year;
std::uint8_t month;
std::uint8_t day;
std::uint8_t hour;
std::uint8_t minute;
std::uint8_t second;
std::uint16_t milisecond;
};
My doubt is about the LessThan and GreaterThan methods. I have implemented as follows in order to avoid a bunch of ifs and elses, but I might have not covered all possible situations:
bool GreaterThan(const DateTime& datetime)
{
bool greater{true};
// When found a different value for the most significant value, the evaluation is interrupted
if ((year <= datetime.year) && (month <= datetime.month || year < datetime.year) &&
(day <= datetime.day || month < datetime.month) && (hour <= datetime.hour || day < datetime.day) &&
(minute <= datetime.minute || hour < datetime.hour) &&
(second <= datetime.second || minute < datetime.minute) &&
(milisecond <= datetime.milisecond || second < datetime.second))
{
greater = false;
}
return greater;
}
bool LessThan(const DateTime& datetime)
{
bool less{true};
// When found a different value for the most significant value, the evaluation is interrupted
if ((year >= datetime.year) && (month >= datetime.month || year > datetime.year) &&
(day >= datetime.day || month > datetime.month) && (hour >= datetime.hour || day > datetime.day) &&
(minute >= datetime.minute || hour > datetime.hour) &&
(second >= datetime.second || minute > datetime.minute) &&
(milisecond >= datetime.milisecond || second > datetime.second))
{
less = false;
}
return less;
}
Please, let me know which possible situation is not covered.
| From all the comments, I think the best solution was proposed by –
Richard Critten:
bool GreaterThan(const DateTime& date_time)
{
return (std::tie(year, month, day, hour, minute, second, milisecond) >
std::tie(date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, date_time.milisecond));
}
bool LessThan(const DateTime& date_time)
{
return (std::tie(year, month, day, hour, minute, second, milisecond) <
std::tie(date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, date_time.milisecond));
}
|
72,910,739 | 72,911,538 | Vulkan Storage Buffer Memory Mapping | I'm refactoring and re-writing the guide made by VkGuide as to fit my idea of an engine. I'm using VMA to handle my memory needs.
I've stumbled upon a strange (?) issue in refactoring my memory mapping code into something more easily readable:
Original code:
Renderer fields
//-------------------------------------------------
struct ObjectData { matrix4 transform };
inline Frame& frame(); // Get current frame in flight
std::vector<RenderableObject> renderables;
//--------------------------------------------------
Drawing code
void* object_data;
vmaMapMemory(allocator, frame().object_buffer.allocation, &object_data);
auto* ssbo = static_cast<ObjectData*>(object_data);
for (int i = 0; i < renderables.size(); i++) {
auto& object = renderables[i];
ssbo[i].model_matrix = object.transform;
}
vmaUnmapMemory(allocator, frame().object_buffer.allocation)
and the refactored and templated namespace-local function:
struct AllocatedBuffer { VkBuffer buffer, VmaAllocation allocation };
template <typename T, typename Func>
void effect_mmap(VmaAllocator& allocator, AllocatedBuffer& buffer, Func&& effect)
{
void* object_data;
vmaMapMemory(allocator, buffer.allocation, &object_data);
auto* t_pointer = static_cast<T*>(object_data);
effect(*t_pointer);
vmaUnmapMemory(allocator, buffer.allocation);
}
My camera position and everything else seems to shift and work incorrectly. Following shows usage (which now should replace the original code):
MemoryMapper::effect_mmap<ObjectData>(allocator, frame().object_buffer, [&](ObjectData& data) {
for (auto& object : renderables) {
data.model_matrix = object.transform;
}
});
and here are the correct (the textures are still invalid, and I don't know why, that's for another day) and afters: Correct, and Incorrect.
| Your usage example only ever sets the first SSBO in the buffer, as data is *t_pointer and never changes.
Change your code to pass t_pointer directly, change the type of the callback and then you can use it as
MemoryMapper::effect_mmap<ObjectData>(allocator, frame().object_buffer, [&](ObjectData* data) {
for (auto& object : renderables) {
data->model_matrix = object.transform;
data++;
}
});
|
72,910,829 | 72,911,415 | Same template class specialization for std::variant and boost::variant template types | I want to create a class specialization that has the same implementation if it gets passed any std::variant or any boost::variant. I tried to play around with std::enable_if, std::disjunction and std::is_same but I couldn't make it compile. Here is a code sample to show what I want to achieve.
#include <variant>
#include <iostream>
#include <boost/variant.hpp>
template <typename T>
struct TypeChecker;
template <typename T>
struct TypeChecker<T>
{
void operator()()
{
std::cout << "I am other type\n";
}
}
template <typename ... Ts> // I want to be able to capture Ts... in TypeChecker scope
struct TypeChecker<std::variant<Ts...> or boost::variant<Ts...>> // what to insert here?
{
void operator()()
{
std::cout << "I am either std::variant or boost::variant\n";
}
}
int main()
{
TypeChecker<std::variant<int, float>>{}();
TypeChecker<boost::variant<int, float>>{}();
TypeChecker<int>{}();
}
Expected result:
I am either std::variant or boost::variant
I am either std::variant or boost::variant
I am other type
| You can use a template template parameter e.g. like this
template <typename T>
struct TypeChecker {
void operator()() {
std::cout << "I am other type\n";
}
};
template<typename ... Ts, template<typename...> typename V>
requires std::same_as<V<Ts...>, std::variant<Ts...>> ||
std::same_as<V<Ts...>, boost::variant<Ts...>>
struct TypeChecker<V<Ts...>>
{
void operator()()
{
std::cout << "I am either std::variant or boost::variant\n";
}
};
Note that this uses C++20 constraints. If you can't use C++20 you can use std::enable_if instead like e.g. this:
template<typename ... Ts, template<typename...> typename V>
struct TypeChecker<V<Ts...>> : std::enable_if_t<
std::is_same_v<V<Ts...>, std::variant<Ts...>> ||
std::is_same_v<V<Ts...>, boost::variant<Ts...>>, std::true_type>
{
void operator()()
{
std::cout << "I am either std::variant or boost::variant\n";
}
};
You can see it live on godbolt.
|
72,911,198 | 72,911,278 | C++14 variadic function template expect 2 arguments - 0 provided | I'm currently working on a variadic function using template, however, I keep getting the same error:
C2780: 'void print(T,Types...)': expects 2 arguments - 0 provided
even if it is the simplest one:
template <typename T, typename... Types>
void print(T var1, Types... var2)
{
cout << var1 << endl;
print(var2...);
}
int main() {
print(1, 2, 3);
}
the same error again. I wonder what's wrong.
| Your calls to print will be like this:
print(1, 2, 3);
print(2, 3);
print(3);
print();
Your template function needs at least one argument (var1), and there is no function that takes zero arguments.
This can easily be solved by adding another function overload to handle the "no argument" case:
void print()
{
// Do nothing
}
Now this will be called in the
print();
case, and will end the recursion.
If C++17 is possible, then fold expressions are available and you could do it with only a single function:
template <typename... Types>
void print(Types&&... var)
{
((std::cout << var << "\n"), ...);
}
|
72,911,809 | 72,913,313 | How is this function returning the correct answer (trying to find the minimum value in a sorted and rotated array)? | I am trying to find the minimum element in an array that has been sorted and rotated (Edit: distinct elements).
I wrote a function that uses binary search, splitting the array into smaller components and checking whether the "mid" value of the current component was either greater than the "high" value or lesser than the "starting" value moves towards either end because by my rough logic, the smallest element must be "somewhere around there".
Thinking about it a little harder, I realized that this function would not return the correct answer for a fully sorted component/array, but for some reason, it does.
// Function to find the minimum element in sorted and rotated array.
int minNumber(int arr[], int low, int high)
{
int mid = (low + high) / 2;
if (low > high)
return -1;
if (low == high)
return arr[low];
if (mid == 0 || arr[mid - 1] > arr[mid])
return arr[mid];
else if (arr[mid] > arr[high])
{
return (minNumber(arr, mid + 1, high));
}
else if (arr[mid] < arr[low])
{
return (minNumber(arr, low, mid - 1));
}
}
Passing the array "1,2,3,4,5,6,7,8,9" through it returns 1. I though maybe the rax register might have accidentally stored a 1 at some point and now the function was just spitting it out as there was no valid return statement for it to go through. Running it through g++ debugger line-by-line didn't really help and I'm still confused as to how this code works.
FULL CODE
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
// Function to find the minimum element in sorted and rotated array.
int minNumber(int arr[], int low, int high)
{
int mid = (low + high) / 2;
if (low > high)
return -1;
if (low == high)
return arr[low];
if (mid == 0 || arr[mid - 1] > arr[mid])
return arr[mid];
else if (arr[mid] > arr[high])
{
return (minNumber(arr, mid + 1, high));
}
else if (arr[mid] < arr[low])
{
return (minNumber(arr, low, mid - 1));
}
}
};
// { Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i)
cin >> a[i];
Solution obj;
cout << obj.minNumber(a, 0, n - 1) << endl;
}
return 0;
} // } Driver Code Ends
| Short answer: Undefined behavior doesn't mean it can't give the right answer.
<source>: In member function 'int Solution::minNumber(int*, int, int)':
<source>:31:5: warning: control reaches end of non-void function [-Wreturn-type]
When the array isn't rotated you hit that case and you are simply getting lucky.
Some nitpicking:
turn on the compiler warnings and read them
int is too small for a large array
int mid = (low + high) / 2; is UB for decently sized arrays, use std::midpoint
minNumber should take a std::span and then you could use std::size_t size = span.size();, span.first(size / 2) and span.last(size - size / 2)
|
72,911,836 | 72,913,027 | How do I fix error LNK2019: unresolved external symbol _glfwInit | I have the basic code from the vulkan tutorial. I'm not using Visual Studio and opted to just compile from the command line. cl lib/*.lib main.cpp /I include. I sort of assumed that the symbols would be resolved in the .lib files which seem to compile properly, but it doesn't link so what do I do?
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <iostream>
int main() {
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(800, 600, "Vulkan window", nullptr, nullptr);
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
std::cout << extensionCount << " extensions supported\n";
glm::mat4 matrix;
glm::vec4 vec;
auto test = matrix * vec;
while(!glfwWindowShouldClose(window)) {
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
This is the full output of the compiler/linker
Microsoft (R) Incremental Linker Version 14.28.29913.0
Copyright (C) Microsoft Corporation. All rights reserved.
/out:main.exe
lib/glfw3.lib
lib/glfw3dll.lib
lib/glfw3_mt.lib
main.obj
main.obj : error LNK2019: unresolved external symbol _vkEnumerateInstanceExtensionProperties@12 referenced in function _main
main.obj : error LNK2019: unresolved external symbol _glfwInit referenced in function _main
main.obj : error LNK2019: unresolved external symbol _glfwTerminate referenced in function _main
main.obj : error LNK2019: unresolved external symbol _glfwWindowHint referenced in function _main
main.obj : error LNK2019: unresolved external symbol _glfwCreateWindow referenced in function _main
main.obj : error LNK2019: unresolved external symbol _glfwDestroyWindow referenced in function _main
main.obj : error LNK2019: unresolved external symbol _glfwWindowShouldClose referenced in function _main
main.obj : error LNK2019: unresolved external symbol _glfwPollEvents referenced in function _main
lib\glfw3.lib : warning LNK4272: library machine type 'x64' conflicts with target machine type 'x86'
lib\glfw3dll.lib : warning LNK4272: library machine type 'x64' conflicts with target machine type 'x86'
lib\glfw3_mt.lib : warning LNK4272: library machine type 'x64' conflicts with target machine type 'x86'
main.exe : fatal error LNK1120: 8 unresolved externals
| First I had to install the windows 10 SDK
Then I had to change my vcvarsall in path to the VS2022 one
Then I had to run the vcvarsall x64
Then I had to remove the glfw3.lib in favor of the glfw3_mt.lib
Then I had to add the vulkan-1.lib to my lib/ directory
And finally it compiled and showed a window
|
72,912,054 | 72,912,982 | Why does MISRA C++ allow modifying parameters when MISRA C doesn't? | MISRA rule 17.8 prohibits modification of function parameters in the function body. The rationale is that programmers new to C may misinterpret the semantics of doing so.
But in MISRA C++ it seem to be no corresponding rule. Apart from the objections to the practice of modifying parameters is equally valid in C++ there's even more possibility of getting things wrong: with the possibility to pass by reference there's a possibility to actually modify object/variables in the callers scope from the callee. After all it's just an ampersand that makes the (possibly catastrophic) difference.
To give an example: in C++ (as opposed to C) it's now possible to alter the value for the caller by just modify the parameter if it's passed as a reference:
void g(int32_t& x){
if (x == 42) {
x = 43; // must change x so we don't crash and burn
}
do_something(x);
}
void g_caller(void) {
int32_t x = get_value()
g(x);
if (x == 42) {
crash_and_burn();
}
}
But if the variable is not passed by reference it's the same story as for C, the modification of the parameter is not seen by the caller. The same code with just a ampersand removed, with catastrophic consequence just because somebody didn't think modifying parameters passed by value is as shady as in C. Is the programmers intent to make it crash and burn after all? Or did he just miss the fact that the parameter now is sent by value? Maybe x used to be passed by reference, but now has changed and the poor programmer just intended to fix a bug by modifying x here? In C++ it's not just newbies that can mistake x = 43 to just be alteration of a local copy.
void g(int32_t x){
if (x == 42) {
x = 43; // must change x so we don't crash and burn
}
do_something(x);
}
void g_caller(void) {
int32_t x = get_value()
g(x);
if (x == 42) {
crash_and_burn();
}
}
| This rule wasn't present in MISRA C:2004 either, which is the C version most similar to MISRA C++:2008. MISRA C was updated and much improved in 2012 but MISRA C++ never went through such an update - it is actually getting reviewed and updated right now, but the next version is still a work in progress, yet to be published. Maybe it will get this rule added.
The rule does make sense particularly for situations like the ones you mention in the question - we do get large amounts of troubleshooting questions with this particular bug here on SO.
Notably, this is one of them rules added mainly for the benefit of static analysers. This is exactly the kind of bug that a static analyser is much better at spotting than humans.
|
72,912,782 | 72,914,470 | Compare DayTime strings in C++ | If I have a single string storing both Day and Time in the format "mm/dd-hh:mm" how can I create the string of two days ahead?
| You can use Howard Hinnant's date library.
First of all, fix the input string by adding something that could be parsed as a year, and not a leap year (e.g. "01/"), so that date::from_stream parses the date and time input string into a time point (tp1) correctly.
Get the date two days ahead of tp1, that is, tp1 + days{2}.
Format the new date back to a string by using date::format.
[Demo]
#include <chrono>
#include <date/date.h>
#include <iostream> // cout
#include <sstream> // istringstream
#include <string>
std::string two_days_ahead(const std::string& dt) {
auto fixed_dt{std::string{"01/"} + dt};
std::istringstream iss{fixed_dt};
date::sys_time<std::chrono::minutes> tp1{};
date::from_stream(iss, "%y/%m/%d-%H:%M", tp1);
return date::format("%m/%d-%H:%M", tp1 + date::days{2});
}
int main() {
std::cout << two_days_ahead("10/30-09:50") << "\n";
}
// Input: "10/30-09:50"
// Output: 11/01-09:50
|
72,913,047 | 72,913,927 | Deselect edit control win32 c++ | How would I go about deselecting the text in edit control?
After entering the input I want the user to be able to deselect the edit control.
Because even after you click out of it and press a key, it gets entered into the edit.
Here is the code for my edit control:
HFONT fontMain = CreateFont(
-16, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
0, // Font Weight
false, // Italic
false, // Underline
false, // Strikeout
ANSI_CHARSET, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE|DEFAULT_PITCH, // Family And Pitch
TEXT("Calibri"));
HWND editControl = CreateWindow(
TEXT("EDIT"),
TEXT("TEST TEXT"),
WS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE,
x, y, width, height,
window,
(HMENU) 100,
instance,
NULL);
SendMessage(window /* parent window */, WM_SETFONT, (WPARAM)fontMain, NULL);
DeleteObject(fontMain);
I have checked MSDN docs and have not found any additional styles to add to achieve the task.
If you have any ideas on how to achieve this task could you help me out?
Thank you.
| You could use the same trick that works to dismiss dropdown list (of combo box), popup menus, and the like.
You'll need to subclass the EDIT control so you receive messages first to your own window procedure.
In your textbox subclass WM_SETFOCUS handler, call SetCapture so the next click is delivered to the textbox even if it's outside.
In the textbox subclasses's handler for mouse click messages, test the location and if outside the textbox, call SetFocus(NULL) to give up the focus. (This is where a popup would dismiss itself). Also call ReleaseCapture().
Also call ReleaseCapture() in the subclass's WM_KILLFOCUS handler, since mouse clicks are not the only way to lose focus.
The above is the way to have any click outside the textbox remove its focus. If you only want clicks in the client area of your parent window to defocus the textbox, then you can certainly skip the subclassing and capture, and just handle the mouse click events in the parent window, calling SetFocus(NULL) or SetFocus(parentHWnd).
|
72,913,138 | 72,916,944 | Atomic wait memory_order | I don't completely understand why atomic wait needs a memory order parameter. It compares its own value, so the atomic value itself is synchronized anyway. I couldn't figure out an example where anything else than std::memory_order_relaxed makes sense.
If I need additional logic based on the atomic variable I need to call other functions (with separate memory order specification) anyway, as wait is void, e.g.:
void waitToBeEmpty() noexcept
{
ssize_t currSize{ m_queueSize.load(std::memory_order_acquire) };
while (currSize > 0) {
m_queueSize.wait(currSize, std::memory_order_relaxed);
currSize = m_queueSize.load(std::memory_order_acquire);
}
}
Why do we need to specify a memory order for atomic wait?
|
If I need additional logic based on the atomic variable I need to call other functions
Do you?
Consider if T is a bool. It only has one of two states: true or false. If you wait until it is not true, then it must be false and no further atomic operations are needed.
And that's just the case where T is a type that can only (generally) assume two values. There are also cases where T is a type that technically can assume more values, but you're only using two of them. Or the cases where T could have multiple values, but your waiting code doesn't care which one it is, merely that it isn't the one you asked to wait on. "Is not zero" is a common example, as you may not care which kind of "not zero" it is.
|
72,913,745 | 73,313,271 | VS Code takes several seconds to save a document in C++ | This is my C/C++ configs in /home/user/.config/Code/User/settings.json:
"C_Cpp.formatting": "clangFormat",
"C_Cpp.default.intelliSenseMode": "linux-clang-x64",
"C_Cpp.dimInactiveRegions": false,
"C_Cpp.clang_format_path": "/usr/bin/clang-format",
"C_Cpp.clang_format_sortIncludes": true,
"C_Cpp.codeAnalysis.clangTidy.enabled": true,
"C_Cpp.codeAnalysis.clangTidy.path": "/usr/bin/clang-tidy",
"C_Cpp.default.cppStandard": "c++23",
"C_Cpp.default.cStandard": "c17",
"C_Cpp.autocompleteAddParentheses": true,
"C_Cpp.default.compilerPath": "/usr/bin/clang"
Now when i try to save a C++ document, sometimes it takes several seconds to save and sometimes not:
However when i try developing in Rust, this problem does not exist:
How can i fix that problem as it is so annoying?
Also is there a way to see what's happening while saving in vs code so that i can know what is the process that causes this delay?
| In vscode, i tried to disable all the extensions that i installed previously, i disabled them one by one, after each disable, i test by changing the code then saving, yet the problem persists, until all the extensions are off.
Then i remembered there are some other built-in extensions. I opened the extensions, then pressed on the three dots at the top right of the left side bar, then i chose Show running extensions, the Running extensions will open and you will find among them git. I noticed that git in unresponsive and had a huge number beside it like 4000+ms which is substantially greater than all the other extensions.
Notice that i am using git version 2.34.1. Also the git extension is ok and responsive during Rust development.
So i updated git to the latest version which is 2.37.1 using these commands:
sudo add-apt-repository ppa:git-core/ppa
sudo apt update
sudo apt install git
Now i restarted vscode and the git extension is responsive and working properly. Also the saving is fast and everything in fine.
The problem was due to unresponsive git extension only in C++ development as far as i know. So update git to the latest version.
Update:
I think the problem still exists even after i updated git to the latest version. The delay still only happens with C++ development. The problem is solved once i initialized git in my working directory using git init. When i restart vscode, everything works fine. Here is a screenshot of the Running extensions when the problem exists (Notice the first git extension):
Update:
I think i knew where the problem is. The directory of my C++ project is /home/user/Projects/cpp/testing_1, in cpp/ directory i put all my C++ projects such as testing_1/, testing_2/ and so on. I initialized git in cpp/ dir before which is the parent dir of all my projects. When i deleted that .git dir in cpp/ the git extension in responsive and working fine, even when i am not initializing git in my working project such as testing_1/. I think not initializing git in the parent dir of your project solved the problem. I will see where that goes.
|
72,913,925 | 72,914,008 | printf - raw string literal with format macro of fixed width integer types | How do I use raw string literal R with format macro of fixed width integer types?
For example
std::int64_t num = INT64_MAX;
std::printf(R"("name":"%s", "number":"%")" PRId64, "david", num); // wrong syntax
The output should be
"name":"david", "number":"9223372036854775807"
Use of escape sequences instead of R is not permitted
| Firstly, you should check your current format string with puts().
#include <cstdio>
#include <cinttypes>
int main(void) {
std::puts(R"("name":"%s", "number":"%")" PRId64);
return 0;
}
Result:
"name":"%s", "number":"%"ld
Now you see the errors:
You have an extra " between % and ld.
" is missing after ld.
Based on this, fix the format string:
#include <cstdio>
#include <cinttypes>
int main(void) {
std::int64_t num = INT64_MAX;
std::printf(R"("name":"%s", "number":"%)" PRId64 R"(")", "david", num);
return 0;
}
Result:
"name":"david", "number":"9223372036854775807"
|
72,913,964 | 72,914,076 | libvips in C++ on Mac | I trying to write a program in CLion IDE that read a pdf file with C++ vips library and I get this error. What it's wrong?
Undefined symbols for architecture x86_64:
"vips::VImage::pdfload(char const*, vips::VOption*)", referenced from:
_main in main.cpp.o
"vips::VImage::write_to_file(char const*, vips::VOption*) const", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
My OS: Mac OS Monteray
My Code
#include <vips/vips8>
using namespace vips;
using namespace std;
int main() {
VImage in = VImage().pdfload("/Users/myuser/CLionProjects/untitled3/files/doc.pdf");
in.write_to_file("/Users/myuser/CLionProjects/untitled3/output/img.jpeg");
}
CMakeList.txt
cmake_minimum_required(VERSION 3.19)
project(untitled5)
set(CMAKE_CXX_STANDARD 11)
find_package(PkgConfig REQUIRED)
pkg_search_module(GLIB REQUIRED glib-2.0)
pkg_search_module(VIPS REQUIRED vips)
include_directories(${GLIB_INCLUDE_DIRS})
link_directories(${GLIB_LIBRARY_DIRS})
include_directories(${VIPS_INCLUDE_DIRS})
link_directories(${VIPS_LIBRARY_DIRS})
add_executable(untitled5 main.cpp)
add_definitions(${GLIB_CFLAGS_OTHER})
target_link_libraries(untitled5 ${GLIB_LIBRARIES})
target_link_libraries(untitled5 ${VIPS_LIBRARIES})
| The missing libraries libvips-cpp to link to.
# pkg_search_module(VIPS REQUIRED vips)
pkg_search_module(VIPS REQUIRED vips-cpp)
pkg_search_module(GLIB REQUIRED glib-2.0) can be removed, vips-cpp provides it in the libs
$ pkg-config --libs vips-cpp
-L/usr/local/lib -lvips-cpp -lvips -lgobject-2.0 -lglib-2.0
|
72,914,454 | 72,972,429 | Default copy constructor and assignment operator | If among the elements of my class I have also a const data member, how do copy constructor and assignment operator behave?
I think, but I am not sure, that copy constructor is provided (as most cases) while assignment operator is not provided (differently from what happens normally) and so if I want to use it, I must implement it (of course not assigning the const data member)
| struct foo {
int const x;
};
foo f0{3}; // legal
foo f1 = f0; // legal, copy-construction
foo make_foo(int y) { return {y}; } // legal, direct-initialization
foo f2 = make_foo(3); // legal, elision and/or move-construction
f2 = f1; // illegal, copy-assignment
f2 = make_foo(3); // illegal, move-assignment
Construction and assignment are different operations. = does not mean assignment always.
You can construct const subobjects; you cannot assign to them. This property then applies to the object itself in its automatically written special member functions.
|
72,915,272 | 72,915,337 | Unordered Map Performing Much Slower than Map | Say I am attempting to solve the two-sum problem. Below are two samples of the same algorithm, one using an ordered map, and one using an un-ordered map.
Using unordered_map:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> d;
int indx {0};
for(auto num: nums){
int complement {target - num};
if(d.find(complement) != d.end()) {
vector<int> answer {d[complement], indx};
return answer;
} else {
d[num] = indx;
indx++;
}
}
return vector<int> {-1, -1};
}
};
Using (ordered) map (the only change):
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> d;
int indx {0};
for(auto num: nums){
int complement {target - num};
if(d.find(complement) != d.end()) {
vector<int> answer {d[complement], indx};
return answer;
} else {
d[num] = indx;
indx++;
}
}
return vector<int> {-1, -1};
}
};
With my understanding of the differences between the two objects, I do not understand why unordered_map is performing more slowly than the ordered map by a factor of three.
| The unordered_map has to allocate and copy to grow over and over while the map just allocates nodes.
|
72,915,339 | 72,919,284 | C++ permutation using std::list produces infinite loop | I'm trying to generate all permutations of a vector v using backtracking.
The basic idea of my algorithm is:
at each recursive step, iterate through the remaining elements of v, and pick one to add the resulting permutation. I then delete it from the vector v. I'm trying to speed up the deletion operation by using a std::list. However, this seems to produce an infinite recursive loop that outputs only the first possible permutation.
I can only suspect that it's some problem with my handling of the iterator, but I'm not sure how to fix it.
Here's my code below:
#include <vector>
#include <list>
#include <iostream>
using namespace std;
vector<int> res;
list<int> v = {1, 2, 3, 4};
void permute() {
if (v.empty()) {
for (int d : res) cout << d << " ";
cout << endl;
return;
}
for (auto it = v.begin(); it != v.end(); it ++) {
int d = *it;
res.push_back(d);
it = v.erase(it);
permute();
v.insert(it, d);
res.pop_back();
}
}
int main() {
permute();
}
This piece of code just prints "1 2 3 4" forever.
Any help is appreciated. Thanks!!
| The problem is here: v.insert(it, d);
You will need to insert the value d back where it was, but you are not doing it.
list is not suitable for what you're trying to do. Use a vector, and instead of deleting, use swaps.
|
72,915,869 | 73,533,143 | How to hook Java method with JNI during runtime? | Other questions I saw about this topic were not about while the Java program is running or were unclear to me, so I'm asking a separate question
I'd like to know if there's a way to hook/override methods with JNI during runtime
It would work as Mixins (like in Fabric API), which "injects" code at the beginning or at the end of the method but with C++ and JNI
For example: there's a getter method that returns a field of a class but I want to change the return value to something I want instead of the expected value
I've ran into some topics that said about JVM Handles but I have no idea where to start searching it
| Thank you all for the answers but I found exactly what I wanted (not sure if it's what everyone is looking for but this was my goal with this question)
Basically I found out that jmethodIDs are pointers, which I thought of actually being the address of the method on the stack
To check if this would work I debugged the jvm and found out that it is actually it!
With some testing I also found out that some methods have specific offsets in order to be hooked... you could get this with trial and error but also debugging the jvm (its mostly 0x40)
With the address of the function we can hook it with simple hooking as we would hook any other process method
Here's an example using MinHook and jni (obviously) that actually works with Minecraft with the onTick method (used to keep track of when a tick on the game happens):
typedef void(__cdecl* runTick) (void**, void**);
runTick pRunTick;
runTick pRunTickTarget;
void __cdecl tickHook(void** p1, void** p2) {
sdk::instance->hasTick = true;
return pRunTick(p1, p2);
}
bool cheat::hooks::jhooks::apply_jtickhook(bool create) {
jclass mc_class = machip::instance->get_env()->FindClass("ave");
jmethodID method = machip::instance->get_env()->GetMethodID(mc_class, "s", "()V");
pRunTickTarget = reinterpret_cast<runTick>(*(unsigned __int64*)(*(unsigned __int64*)method + 0x40));
if (create)
{
MH_STATUS status = MH_CreateHook(reinterpret_cast<void**>(pRunTickTarget), &tickHook, reinterpret_cast<void**>(&pRunTick));
if (status != MH_OK) {
wrapper::output("failed to hook onTick");
wrapper::output(MH_StatusToString(status));
return false;
}
}
if (MH_EnableHook(reinterpret_cast<void**>(pRunTickTarget)) != MH_OK) {
wrapper::output("failed to enable onTick hook");
return false;
}
machip::instance->get_env()->DeleteLocalRef(mc_class);
wrapper::output("onTick hooked");
return true;
}
For more about hooking/detour I saw this video to understand better and also this one
|
72,916,331 | 72,917,630 | Undefined behavior when reading from FIFO | I am trying to send data from javascript to C via a named pipe/FIFO. Everything seems to be working other than every couple messages there will be an additional iteration of the loop reading 0 bytes rather than the expected 256. I realize I could add something like if (bytes_read>0) {... but this seems like a band aid to a bigger problem.
From my testing it looks like the open() call in the reader is unblocked when the writer opens AND closes the file. It looks like sometimes the reader is ready (and blocked on open) for the next message before the writer closes the file from the previous so it will run through its loop twice per message.
Is this just expected behavior or am I misunderstanding something? Any advice would be greatly appriciated!
Writer:
uint32_t writer(buf)
{
int fd;
// FIFO file path
char * myfifo = "/tmp/channel";
// Creating the named file(FIFO)
// mkfifo(<pathname>, <permission>)
mkfifo(myfifo, 0666);
// Open FIFO for write only
fd = open(myfifo, O_WRONLY);
uint32_t written = write(fd, buf, sizeof(char)*256);
close(fd);
return written;
}
Reader:
int main()
{
int fd;
// FIFO file path
char * myfifo = "/tmp/channel";
// Creating the named file(FIFO)
mkfifo(myfifo, 0666);
while (1)
{
char buf[256] = "\0";
// Open FIFO for Read only
fd = open(myfifo, O_RDONLY);
// Read from FIFO
int bytes_read = read(fd, buf, sizeof(char)*256);
struct access_point *dev = (struct access_point *) &buf;
printf("Bytes read: %i\n", bytes_read);
printf("ssid: %s\n", dev->ssid);
int r = close(fd);
//sleep(0.01);
}
return 0;
}
After 5 calls to writer the output will look like:
# Call 1 (bad)
Bytes read: 256
ssid: kremer
Bytes read: 0
ssid:
# Call 2
Bytes read: 256
ssid: kremer
# Call 3
Bytes read: 256
ssid: kremer
# Call 4 (bad)
Bytes read: 256
ssid: kremer
Bytes read: 0
ssid:
# Call 5
Bytes read: 256
ssid: kremer
| A reador 0 bytes indicates the pipe was closed on the other end. So this is absolutely expected behavior.
So you do have to catch that 0 and read again so the kernel waits for the next time the pipe is opened.
Note: read can also return -1 with errno set to EINTR. Same deal, just read again.
|
72,916,424 | 72,916,464 | Why the output not show up according to my txt file? | Why can't I retrieve all of the data from a txt file using c++?
This is the data in the txt file:
Standard ;40 90 120
Delux ;70 150 200
VIP ;110 200 300
This is my coding:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <bits/stdc++.h>
#include <vector>
using namespace std;
struct Room
{
string roomType;
float tripleBed;
float doubleBed;
float singleBed;
};
void displayRoom(Room []);
void inputRoom(ifstream &, Room []);
int main()
{
Room choice[3];
ifstream room("Room.txt");
if(room.fail())
{
cout<<"File does not exist\n";
cout<<"Press any key to exit the program\n";
return -1;
}
inputRoom(room, choice);
displayRoom(choice);
room.close();
return 0;
}
void displayRoom(Room choice[])
{
cout<<"\n\n************** ROOMS SECTION ***************\n"<<endl;
cout<<"ROOM TYPE"<<"\t"<<"TRIPLE BEDDED"<<"\t"<<"DOUBLE BEDDED"<<"\t"<<"SINGLE BEDDED"<<endl;
for(int i=0; i<3; i++)
{
cout<<choice[i].roomType;
cout<<"RM"<<choice[i].tripleBed<<"\t\tRM"<<choice[i].doubleBed<<"\t\tRM"<<choice[i].singleBed<<endl;
}
}
void inputRoom(ifstream &room, Room choice[])
{
string tokens[4];
string line;
int j = 0;
while (room.good())
{
int i = 0;
getline(room, line);
stringstream ss (line);
string temp;
while (getline (ss, temp, ';'))
{
tokens[i] = temp;
i++;
}
choice[j].roomType = tokens[0];
choice[j].tripleBed = atof(tokens[1].c_str());
choice[j].doubleBed = atof(tokens[2].c_str());
choice[j].singleBed = atof(tokens[3].c_str());
j++;
}
}
This is the output
************** ROOMS SECTION ***************
ROOM TYPE TRIPLE BEDDED DOUBLE BEDDED SINGLE BEDDED
Standard RM40 RM0 RM0
Delux RM70 RM0 RM0
VIP RM110 RM0 RM0
--------------------------------
Process exited with return value 0
Press any key to continue . . .
As you can see, at double bedded and single bedded column should have a value that has been defined by me but why the value of the columns zero? can someone help me? Thank you in advance for helping me.
| Look at your input loop
while (getline (ss, temp, ';'))
{
tokens[i] = temp;
i++;
}
that reads tokens separated by semicolons.
Look at you actual input
Standard ;40 90 120
Only the first and second token are separated by a semicolon. The rest are separated by spaces.
The simple thing to do would be to edit your data so that it matches your code. E.g.
Standard;40;90;120
|
72,916,809 | 72,917,439 | Better way to give constant view of pointers in C++ | I have a class that must return a constant view of some pointers to the upper layers of software.
Internally, the pointers must be non-const, because the class will need to manipulate the objects internally.
I don't see any option for providing this const view of the pointers to a higher level client, without making a copy of all the pointers. This seems wasteful. What if I was managing millions of objects?
Is there a better way?
Here is some example code:
#include <vector>
#include <iostream>
class example {
public:
example() {
bytePtrs_.push_back(new char);
*bytePtrs_[0] = '$';
}
// I want to do this, but compiler will not allow
// error: could not convert ‘((example*)this)->example::bytePtrs_’ from ‘std::vector<char*>’ to ‘std::vector<const char*>’
std::vector<const char*> getPtrs() {
return bytePtrs_;
}
// Must make wasteful copy
std::vector<const char*> getPtrs() {
std::vector<const char*> ret;
for (auto &ptr : bytePtrs_)
ret.push_back(ptr);
return ret;
}
private:
std::vector<char*> bytePtrs_;
};
int main() {
example e;
std::vector<const char*> bytePtrs = e.getPtrs();
std::cout << bytePtrs[0] << std::endl;
}
| As the OP has pointed out in one of the comments, this is the API the code needs to comply to:
https://github.com/Xilinx/Vitis-AI/blob/master/src/Vitis-AI-Runtime/VART/vart/runner/include/vart/runner.hpp#L157
So by design it returns by copy, which is unavoidable really, thus what really can be done is this:
#include <vector>
#include <iostream>
class example {
public:
example() {
bytePtrs_.push_back(new char);
*bytePtrs_[0] = '$';
}
// Returning by value
// so shallow copy of objects is expected
// i.e. the pointers are copied
std::vector<const char*> getPtrs() {
return std::vector<const char*>(bytePtrs_.begin(), bytePtrs_.end());
}
private:
std::vector<char*> bytePtrs_;
};
int main() {
example e;
std::vector<const char*> bytePtrs = e.getPtrs();
std::cout << bytePtrs[0] << std::endl;
}
|
72,917,382 | 73,053,491 | Crypto++ generating AES key to a file | I generate key to a file using the following function
std::filesystem::path create_key(std::filesystem::path folder_path)
{
CryptoPP::AutoSeededRandomPool prng;
CryptoPP::byte key[CryptoPP::AES::DEFAULT_KEYLENGTH];
prng.GenerateBlock(key, sizeof(key));
std::cout << "Size of key : " << sizeof(key) << std::endl;
std::cout << "Key before hex encode : " << (CryptoPP::byte*)&key << std::endl;
std::filesystem::path key_path = folder_path.concat("\key.aes");
// Key hex encoded to file
CryptoPP::StringSource key_s((CryptoPP::byte*)&key, sizeof(key), true,
new CryptoPP::HexEncoder(
new CryptoPP::FileSink(key_path.c_str())));
std::cout << key_path << "\n" << std::endl;
return key_path;
}
I use same function with few modifications for IV
I get the following results:
Size of key : 16
Key before hex encode : %
"C:\\Users\\User\\Desktop\\New folder\\key.aes"
Size of IV : 16
IV before hex encode : á▀┼┘ÅP⌐ûG→.JW╓‼Ñg79▓─G
"C:\\Users\\User\\Desktop\\New folder\\iv.aes"
Obviously after encoding the results look more readable ,
Does the key should use this characters ?
How can I read the the key and iv using crypto++
I have tried reversing the function :
CryptoPP::FileSource key(key_path.c_str(), sizeof(key), true,
new CryptoPP::HexDecoder(
new CryptoPP::StringSink((CryptoPP::byte*)&key),key_path.c_str()));
And use it by loading keys and IV but it didn't worked
I checked the key.aes file and found out it's created in ANSI encoding which make difference in few characters is there a way to make it utf-8
Console prints : ╢╘r#|ÿ┴♀[ÉB!±L↨SXêu:▄
Key.aes file : ¶Ôr#|˜Á[B!ñLS
converting key.aes file to utf-8 results : ¶Ôr#|˜Á[B!ñLS
| This function is valid and works ,
No changes need to be added in my scenario.
|
72,917,672 | 72,919,189 | type 'X' is not a direct type of 'Y' - but with std::conditional | I have a Base class, two classes inheriting from that base class (they are slightly different from each other) and a Last class which can either inherit from Derived1 or Derived2 based on a template. I use std::conditional to determine at compile time which DerivedX it should actually use:
template< class >
class Base;
template< class T, class ...Args >
class Base < T(Args...) >
{
public:
Base(int a) { std::cout << "Base constructor " << a << std::endl; }
};
template< class >
class Derived1;
template< class ...Args >
class Derived1 < void(Args...) > : public Base< void(Args...) >
{
public:
Derived1(int a) : Base< void(Args...) >(a)
{ std::cout << "Derived1 constructor " << a << std::endl; }
};
template< class >
class Derived2;
template< class T, class ...Args >
class Derived2 < T(Args...) > : public Base< T(Args...) >
{
public:
Derived2(int a) : Base< T(Args...) >(a)
{ std::cout << "Derived2 constructor " << a << std::endl; }
};
template< class >
class Last;
template< class T, class ...Args >
class Last< T(Args...) > : public std::conditional<
std::is_void<T>::value,
Derived1< void(Args...) >,
Derived2< T(Args...) > >
{
public:
Last(int a) : std::conditional<
std::is_void<T>::value,
Derived1< void(Args...) >,
Derived2< T(Args...) > >::type(a)
{ std::cout << "Last constructor " << a << std::endl; }
};
int main()
{
Last<int(int)> last(1);
return 0;
}
I have read multiple topics about diamond heritage and virtual inheritance and I get the same error as those topics: type Derived2<...> is not a base class of Last<...>. However these topics never use an std::conditional. Btw it compiled fine until I try to instantiate a Last object. Is there something I'm missing ? Is it even possible to do it like that ?
| In your declaration of the base class:
template< class T, class ...Args >
class Last< T(Args...) > : public std::conditional<
std::is_void<T>::value,
Derived1< void(Args...) >,
Derived2< T(Args...) > >
{
...
}
You either need to say public std::conditional_t (where the _t is very important at the end), or else you need to put ::type after the std::conditional template parameters, as in the following:
template< class T, class ...Args >
class Last< T(Args...) > : public std::conditional<
std::is_void<T>::value,
Derived1< void(Args...) >,
Derived2< T(Args...) > >::type
{
...
}
Otherwise, your base type is std::conditional and you are trying to mem-initialize Derived2, which is not the same type.
|
72,917,908 | 72,917,972 | class template and member function template with requires | I have a template class called Speaker, with a template member function called speak. These both have a requires clause. How do I define the member function outside of the class in the same header file?
// speaker.h
#include <concepts>
namespace prj
{
template <typename T>
requires std::is_integral<T>
struct Speaker
{
template <typename U>
requires std::is_integral<U>
const void speak(const Speaker<U> &speaker);
};
// what do I put here?
const void Speaker<T>::speak(const Speaker<U> &speaker)
{
// code
}
}
| The rules for defining template members of class templates are the same in principle as they were since the early days of C++.
You need the same template-head(s) grammar component(s), in the same order
template <typename T> requires std::is_integral_v<T>
template <typename U> requires std::is_integral_v<U>
const void Speaker<T>::speak(const Speaker<U> &speaker)
{
// code
}
The associated constraint expression and template <...> form the template-head together.
As an aside:
const qualified return types are redundant in the best case, or a pessimization in the worst case. I wouldn't recommend it (especially over void).
I'd also recommend using concepts (std::integral) if including the library header, not type traits (std::is_integral) that may or may not be included. The concepts allow for the abbreviated syntax, which is much more readable:
template<std::integral T>
template<std::integral U>
|
72,917,993 | 72,918,986 | Using consistent RNG with OpenMP | So I have a function, let's call it dostuff() in which it's beneficial for my application to sometimes parallelize within, or to do it multiple times and parallelize the whole thing. The function does not change though between both use cases.
Note: object is large enough that it cannot viably be stored in a list, and so it must be discarded with each iteration.
So, let's say our code looks like this:
bool parallelize_within = argv[1];
if (parallelize_within) {
// here we assume parallelization is handled within the function dostuff()
for (int i = 0; i < 100; ++i) {
object randomized = function_that_accesses_rand();
dostuff(i, randomized, parallelize_within);
}
} else {
#pragma omp parallel for
for (int i = 0; i < 100; ++i) {
object randomized = function_that_accesses_rand();
dostuff(i, randomized, parallelize_within);
}
}
Obviously, we run into the issue that dostuff() will have threads access the random object at different times in different iterations of the same program. This is not the case when parallelize_within == true, but when we run dostuff() in parallel individually per thread, is there a way to guarantee that the random object is accessed in order based on the iteration? I know that I could do:
#pragma omp parallel for schedule(dynamic)
which will guarantee that eventually, as iterations are assigned to threads at runtime dynamically, the objects will access rand in order with the iteration number, but for the first set of iterations it will be totally random. Any suggestions on how to avoid this?
|
First of all you have to make sure that both function_that_accesses_rand and do_stuff are threadsafe.
You do not have to duplicate your code if you use the if clause:
#pragma omp parallel for if(!parallelize_within)
To make sure that in function dostuff(i, randomized,...); i reflects the order of creation of randomized object you have to do something like this:
int j = 0;
#pragma omp parallel for if(!parallelize_within)
for (int i = 0; i < 100; ++i) {
int k;
object randomized;
#pragma omp critical
{
k = j++;
randomized = function_that_accesses_rand();
}
dostuff(k, randomized, parallelize_within);
}
You may eliminate the use of the critical section if your function_that_accesses_rand makes it possible, but I cannot be more specific without knowing your function. One solution is that this function returns the value representing the order. Do not forget that this function has to be threadsafe!
#pragma omp parallel for if(!parallelize_within)
for (int i = 0; i < 100; ++i) {
int k;
object randomized = function_that_accesses_rand(k);
dostuff(k, randomized, parallelize_within);
}
... function_that_accesses_rand(int& k){
...
#pragma omp atomic capture
k = some_internal_counter++;
...
}
|
72,918,308 | 72,943,899 | Unpacking system verilog packed struct in DPI-C call | I have a very complicated packed struct, C, with nested packed structs, A and B, in SystemVerilog:
typedef struct packed {
logic [31:0] ex1;
logic [3:0] ex2;
} A;
typedef struct packed {
logic ex3;
A [7:0] ex4;
} B;
typedef struct packed {
logic ex5
A [5:0]ex6;
B ex7;
} C;
I need to send this struct via a DPI-C call and then access the different elements within the struct. Unfortunately the actual struct I'm working with is much more complicated than above and I'd like to achieve this without bit indexing into the array for every element. I have seen this post but my struct is so nested and complicated that just indexing would be largely infeasible.
So in the testbench.sv file, I have:
import "DPI-C" function void passC(input C c);
And then in the my-dpi.cc file, I want a way to simply save the svLogicVecVal into a C++ equivalent struct
struct A {
svLogicVecVal ex1; \\[31:0]
svLogicVecVal ex2; \\[3:0]
};
struct B {
svBit ex3;
A ex4[8];
};
struct C {
svBit ex5
A ex6[6];
B ex7;
};
extern "C" function void passC(svLogicVecVal* c){
C = c;
}
I know this is an extremely complicated issue so I would appreciate any advice on the best way to go about it. Unfortunately, I cannot change the SystemVerilog struct itself. I could try to convert it to C compatible types in SystemVerilog but I'd prefer to just go whatever the cleanest solution is. Thanks in advance.
| I came up with an example which allows you to use vpi calls to traverse fields of the structure. It is pure vpi example involved from a dpi function. You can use something similar.
Here is verilog code
typedef struct packed {
logic [3:0] f1;
logic f2;
} s1_t;
typedef struct packed {
logic f3;
s1_t s1;
} s2_t;
import "DPI-C" function void xploreStruct(string instName, string varName);
module test;
s2_t s2 = '{1, '{2, 0}};
initial begin
xploreStruct("test", "s2");
end
endmodule // test
The function gets called with two args: module instance, and variable name. You can probably come up with a different scheme. You might need to use a pure vpi system function instead of dpi if you want to pass the variable itself. Anyway, 'C' code for this example:
#include "stdio.h"
#include "svdpi.h"
#include "sv_vpi_user.h"
static void xploreStructUnionMembers(vpiHandle var, int offset);
void xploreStruct(const char *instName, const char *varName){
vpiHandle module = vpi_handle_by_name(instName, 0);
vpiHandle tdVar = vpi_handle_by_name(varName, module);
printf("%s %s\n", vpi_get_str(vpiType, tdVar), vpi_get_str(vpiName, tdVar));
xploreStructUnionMembers(tdVar, 1);
}
static void xploreStructUnionMembers(vpiHandle var, int offset){
vpiHandle members = vpi_iterate(vpiMember, var);
vpiHandle member;
while (( member = vpi_scan(members) )) {
printf("%*s %s %s\n", offset*4, "", vpi_get_str(vpiType, member), vpi_get_str(vpiName, member));
int vType = vpi_get(vpiType, member);
if (vType == vpiStructVar || vType == vpiUnionVar) {
xploreStructUnionMembers(member, offset+1);
}
else {
s_vpi_value value = {vpiIntVal};
vpi_get_value(member, &value);
printf("%*s = %d\n", offset*4, " ", value.value.integer);
}
}
return;
}
and the output
vpiStructVar s2
vpiLogicVar f3
= 1
vpiStructVar s1
vpiLogicVar f1
= 2
vpiLogicVar f2
= 0
This worked with vcs.
|
72,918,431 | 72,918,521 | Compile Time vs Run time speed | Why is getting a number of the Fibonacci sequence at compile-time using templates much faster than run-time using a recursive function?
#include <iostream>
using namespace std;
template<unsigned long long int I>
struct Fib
{
static const unsigned long long int val = Fib<I - 1>::val + Fib<I - 2>::val;
};
template<>
struct Fib<0>
{
static const unsigned long long int val = 0;
};
template<>
struct Fib<1>
{
static const unsigned long long int val = 1;
};
int main()
{
cout << Fib<100>::val << '\n';
return 0;
}
| A recursive function has all of its code executed at runtime (unless the compiler optimizes it).
A template is typically faster at runtime because all of its code is executed by the compiler itself and only the result is stored in the final executable, so there is no code executed at runtime at all.
So, this code:
#include <iostream>
using namespace std;
template<unsigned long long int I>
struct Fib
{
static const unsigned long long int val = Fib<I - 1>::val + Fib<I - 2>::val;
};
template<>
struct Fib<0>
{
static const unsigned long long int val = 0;
};
template<>
struct Fib<1>
{
static const unsigned long long int val = 1;
};
int main()
{
cout << Fib<100>::val << '\n';
return 0;
}
Once compiled, will behave as-if you had written this instead:
#include <iostream>
using namespace std;
struct Fib_100
{
static const unsigned long long int val = 3736710778780434371ull;
};
int main()
{
cout << Fib_100::val << '\n';
return 0;
}
Or simply:
#include <iostream>
using namespace std;
int main()
{
cout << 3736710778780434371ull << '\n';
return 0;
}
|
72,918,848 | 72,918,876 | How to get parent folder from path in C++ | I am using C++ in linux and I want to extract the parent folder from a path in C++ 14.
For example, I have the path likes
/home/abc/fi.mp4
My expected output be abc. How can I do it in C++
This is that I did
std::string getFolderName(const std::string &path) {
size_t found = path.find_last_of("/\\");
string foldername = ...
return foldername;
}
| You probably want something like this:
// Returns the path-string without the filename part
std::string getFolderPath(const std::string &path) {
const size_t found = path.find_last_of("/\\");
return (found == string::npos) ? path : path.substr(0, found);
}
// Returns only the filename part (after the last slash)
std::string getFileName(const std::string & path) {
const size_t found = path.find_last_of("/\\");
return (found == string::npos) ? path : path.substr(found+1);
}
|
72,919,866 | 72,919,994 | Why doesn't _ui64tow_s work when _ui64tow does? | I wrote some code which uses the _ui64tow function, but I'd like to use _ui64tow_s, which is safer. Unfortunately, it seems I can't get it to work properly.
Here's the original code:
#define PERCENT_SHIFT 10000000
#define SHORTSTRLEN 32
TCHAR g_szZero[SHORTSTRLEN] = TEXT("0");
WCHAR* PerfGraph::FloatToString(ULONGLONG ullValue, WCHAR* psz, BOOLEAN bDisplayDec)
{
ULONGLONG ulDecimal = 0;
ULONGLONG ulNumber = 0;
WCHAR wsz[100];
// Get the integer value of the number:
ulNumber = ullValue / PERCENT_SHIFT;
// BUGBUG: please note that _ui64tow is unsafe.
if (_ui64tow(ulNumber, wsz, 10))
{
lstrcpy(psz, wsz);
if (ulNumber)
{
ullValue = ullValue - ulNumber * PERCENT_SHIFT;
}
if (!ulNumber || bDisplayDec)
{
ulDecimal = ullValue * 100 / PERCENT_SHIFT;
if (ulDecimal && _ui64tow(ulDecimal, wsz, 10))
{
lstrcat(psz, g_szDecimal);
if (ulDecimal < 10) lstrcat(psz, g_szZero);
if (wsz[1] == L'0') wsz[1] = L'\0';
lstrcat(psz, wsz);
}
}
}
return psz;
}
And here's what I tried (please refer to the above code):
if (_ui64tow_s(ulNumber, wsz, sizeof(wsz) / sizeof WCHAR, 10))
and:
if (ulDecimal && _ui64tow(ulDecimal, wsz, sizeof(wsz) / sizeof WCHAR, 10))
What am I doing wrong?
| The _ui64tow_s function returns an error_t value which is zero on success (unlike the plain _ui64tow function, which returns a copy of the string pointer argument).
So, when changing from using _ui64tow to using _ui64tow_s, you must check against zero for success, typically by adding the ! operator to the (returned value of the) function call.
Thus, your calls should be made in the if statements like this:
if (!_ui64tow_s(ulNumber, wsz, sizeof(wsz) / sizeof(WCHAR), 10))
// ^ Note the added "!"
{
lstrcpy(psz, wsz);
if (ulNumber)
{
ullValue = ullValue - ulNumber * PERCENT_SHIFT;
}
if (!ulNumber || bDisplayDec)
{
ulDecimal = ullValue * 100 / PERCENT_SHIFT;
if (ulDecimal && !_ui64tow_s(ulDecimal, wsz, sizeof(wsz) / sizeof(WCHAR), 10))
// ... ^ and another "!" here
{
lstrcat(psz, g_szDecimal);
if (ulDecimal < 10) lstrcat(psz, g_szZero);
if (wsz[1] == L'0') wsz[1] = L'\0';
lstrcat(psz, wsz);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.