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 |
|---|---|---|---|---|
70,894,365 | 70,894,544 | Are members of a struct also a type? | The code below is from <The c++ template the complete guide> I don't know why it works, is left and right a type here too?
// define binary tree structure and traverse helpers:
struct Node {
int value;
Node* left;
Node* right;
Node(int i=0) : value(i), left(nullptr), right(nullptr) {
}
…
};
auto le... | Probably you're asking about the left and right defined at
auto left = &Node::left;
auto right = &Node::right;
These are not types; they are "pointer to member" variables. Here variable left represents the member left of struct Node, in a way that we can take any Node and the value of pointer to member left and find t... |
70,894,444 | 70,924,776 | Can I use Thread Sanitizer on Windows 10? | I'd like to test data races in C++ on windows 10(64 bit), but it seems that Visual C++ doesn't support it yet.
So, I installed Cygwin and got g++ 11.2.0, tried compiling my C++ code with -fsanitize=thread -fPIE -pie -g, but it failed with -ltsan not found error.
The doc doesn't say anything about Windows. Is it even po... | Just use WSL and use thread sanitizer on it.
|
70,894,860 | 70,928,983 | Emscripten: How to catch JS exception? | Emscripten 'val.h' API allows calling methods of JS objects, however, C++ try-catch won't catch JS exception. Consider this example:
#include <emscripten.h>
#include <emscripten/val.h>
void test(){
string t = "some invalid json";
val v = val::object();
// This C++ try-catch doesn't catch JS exception
... | Emscripten doesn't seem to be able to catch JS exceptions in C++ yet. Here's a work-around:
// extern_pre.js
function json_parse(str){
try{
return JSON.parse(str);
}
catch(E){
return null;
}
}
// app.cpp
...
val v = val::global("json_parse")(some_str);
Build:
emcc app.cpp -o app.js --b... |
70,895,113 | 70,895,612 | GetOpenFileName() and GetSaveFileName() make GetAsyncKeyState() stop working | GetOpenFileName() and GetSaveFileName() make GetAsyncKeyState() stop working.
(Note: I am also using getch() from <conio.h> in some places, if that is any use)
A little example (UNTESTED):
#include <commdlg.h>
#include <windows.h>
#include <iostream>
using std::cout;
#define keyPressed(x) GetAsyncKeyState(x) & 0x8000... | Alright, thanks to @Anders, setting ofn.hwndOwner to NULL worked. Thanks!
I didn't need to poll in another thread or use Virtual Key Codes but thanks for trying to help me!
|
70,895,591 | 70,896,264 | Structured bindings mixing rvalues and lvalues in C++ | The commented line in the following snippet does not work as expected:
double a, b;
auto [c, d] = std::make_tuple<double, double&>([&]() -> double { return a; }(),
[&]() -> double& { return b; }());
static_assert(std::is_same_v<double, decltype(c)>);
// static_assert(std::... | std::make_tuple<double, double&>(...) returns std::tuple<double, double>, since it applies std::decay to the template arguments. In any case, you're not supposed to specify the template arguments for it, it can deduce them automatically.
To have a reference in the tuple, construct it using std::tuple<double, double &>(... |
70,895,722 | 70,898,429 | How does one link and include lib-leptonica in a cross platform make file? | I have the following cmake command:
include(FindPkgConfig)
# ditto for tesseract
pkg_search_module(LEPT lept)
find_library(
LEPT
NAMES leptonica liblept liblept-dev lept
HINTS ${LEPT_INCLUDE_DIRS} ${LEPT_LIBRARY_DIRS}
)
// ditto for tesseract
target_include_dirs(tess_api PRIVATE ${LEPT_INCLU... |
However, ideally this project has best cross-platform practices implemented...
That would be this:
find_package(PkgConfig) # Never include(Find<Anything>)
pkg_search_module(Tesseract REQUIRED IMPORTED_TARGET ...)
pkg_search_module(Leptonica REQUIRED IMPORTED_TARGET lept)
target_link_libraries(tess_api
PRIVATE... |
70,896,073 | 70,897,259 | how to send data with Readable stream from NodeJS to C++ | I'm currently sending data from C++ to NodeJS passing a NodeJS readableStream.push.bind(readableStream) to the C++ binding code and writing onto the stream from C++ using
Napi::Function push = info[0].As<Napi::Function>();
Napi::ThreadSafeFunction push_safe = Napi::ThreadSafeFunction::New(env, push, "push", 0, 1);
push... | Implementing this with all the bells and whistles is not trivial. As always, the most complex part is handling all the errors.
I suggest you go check in Node.js sources src/js_stream.cc which contains something similar and you will understand why a good/fast implementation is difficult.
If you want to keep it simple, y... |
70,896,168 | 70,896,352 | Difference between C++ and C# hex values for doubles | I am replacing some C++ code that writes a binary file with C# (net6.0), and I'm noticing an discrepancy between the values written to the file.
If I have a double precision value equal to 0.0, C++ writes the bytes as:
00 00 00 00 00 00 00 00
However C# (using BinaryWriter) is writing the same value as:
00 00 00 00 00 ... | As mentioned in the comments, that trailing 0x80 byte is actually the high byte of the double value. So, the MSB being set in that is the sign bit. This means that the number being stored is actually -0.0 (which, in virtually all cases, compares equal to 0.0, so it shouldn't cause any problems).
In fact, there are othe... |
70,896,252 | 70,896,975 | How does one implicitly compile a C++ executable using GNU-Make? | I have an implicit gnu-makefile side by side with my Cross-platform build file so that I can debug either with the other.
I am trying to keep my architecture constrained such that my builds are implicit in gnu make. This will help restrict any wild build patterns.
I have managed to make everything implicit except for t... | There's no way a recipe that only knows the executable name and object file prerequisites can guess what compiler front-end should be used to link: C, C++, Fortran, whatever.
You can find the implicit rules via:
make -f/dev/null -p
You'll see that an executable uses this built-in rule:
%: %.o
# recipe to execute (bui... |
70,896,932 | 70,896,991 | Simultaneously reassign values of two variables in c++ | Is there a way in C++ of emulating this python syntax
a,b = b,(a+b)
I understand this is trivially possible with a temporary variable but am curious if it is possible without using one?
| You can use the standard C++ function std::exchange like
#include <utility>
//...
a = std::exchange( b, a + b );
Here is a demonstration program
#include <iostream>
#include <utility>
int main()
{
int a = 1;
int b = 2;
std::cout << "a = " << a << '\n';
std::cout << "b = " << b << '\n';
a = std... |
70,898,251 | 70,906,265 | Armadillo ifftshift and ifft c++ | Does anyone know how to do ifftshift + ifft (by row) for matrix in armadillo ?
I did in matlab : ifft(ifftshift(mat,2),[],2);
where mat is matrix (3,18000);
I already tried to do something like in C++ :
arma::mat v3(3,18000); ... filled with the same values from Matlab ...
static arma::cx_mat ifftshift(arma::cx_mat A... | The problem is likely that your ifftshift() shifts in both dimensions, the matlab command is only shifting in the second (row) dimension ifftshift(mat,2). Try to remove one shift in your function if you want the same behavior
return arma::shift(Axx,-ceil(Axx.n_cols/2),1).
|
70,898,401 | 70,898,526 | How to use always the same type of edge in a directed weighted graph? | I'm doing a project for college and we are simulating a public transport (Only bus) system using directed weighted graphs in c++. Each node represents a stop and each edge represents the line of the bus and the line is a parameter of the edge besides the weight. So between stops we can have multiple buses doing that bi... | For each node where there are more than one line, split the node into several connected by edges with weight the cost of changing lines. The run Dijkstra.
|
70,898,633 | 70,898,887 | How do I get the return value of a c++ function in php code? | It's a beginner question but I researched a lot and barely found anything. Many articles or examples on zend don't exist anymore and I cant really make progress so bare with me.
I'd like to get the result from an existing c++ function to use it in php code. I set up a super simple example:
My c++ code looks like the fo... | You can try this:
<?php
$out = shell_exec("date > /dev/null 2>&1; echo $?");
echo "result is: $out";
?>
This is how we get exit status of any command in shell. You execute the command and check the value of $? (and probably divide it by 256 but not in this case).
|
70,899,061 | 70,899,176 | Iterate through a container of types different based on template parameter to call same method | (I'm restricted to C++14 for now but if C++17 or 20 can allow this, please do say)
I have a class/struct containing different types:
struct Aggregation
{
Something<P> _p;
Something<S> _s;
Something<T> _t;
// There's a lot more
};
Although each type is simply a different templated parameter of Something... |
Is this possible?
Yes! Create a common base, with the common functionality.
struct SomethingBase
{
virtual std::string export() = 0;
};
Every instantiation of Something can inherit from that common base.
template<class T>
struct Something : SomethingBase
{
std::string export() override {return "some stuff";... |
70,899,416 | 70,899,558 | Restrict template to largest data type necessary for all calls | I have some function which computes an operation on numbers:
int32_t compute(int32_t x) {
// just a placeholder; the details don't matter
return ~x;
}
The full function is kind of big, and pulls in other big number functions too. I want to save every byte because it's for an 8-bit microcontroller with a tiny R... | There isn’t, at least as flexible as you’ve asked for. The problem is, the widest type in use globally won’t be known until link time… but at that point it’s too late to do anything clever with weak symbols, because the compiled calling code is already expecting to call with a particular integer type. Put differently, ... |
70,899,909 | 70,900,238 | How can I await multiple awaitables/IAsyncActions in C++/WinRT (`Promise.all` equivalent)? | Is there an equivalent to JavaScript's Promise.all in C++ or C++/WinRT for awaitables (or just Windows.Foundation.IAsyncAction)?
For example, I am trying to gather multiple IAsyncActions and continue when all of them have completed. For now I'm starting each action and then awaiting them one by one in a simple loop:
wi... | As is often the case, there is indeed a C++/WinRT function for almost this case: winrt::when_all(T... async) (it is not currently documented on Advanced concurrency and asynchrony with C++/WinRT).
If you have modern C++/WinRT, you can await multiple actions at once:
winrt::IAsyncAction MyFunctionAsync()
{
const aut... |
70,900,112 | 70,900,408 | Splitting C++ strings using a Delimiter | Okay, So I've looked around on StackOverflow and I've stumbled across a way of splitting C++ via delimiters.
So far, I've looked at these, and I still don't understand it.
Parse (split) a string in C++ using string delimiter (standard C++)
https://www.oreilly.com/library/view/c-cookbook/0596007612/ch04s07.html
C++ spl... | Let's go step by step, starting with the date:
29/01/2022 -- Day, Month, Year.
Given the following:
unsigned int day = 0u;
std::cin >> day;
The input of an integer skips whitespace until the first number character (for the first number character, also includes '+' and '-'). The extraction operator keeps reading c... |
70,900,187 | 70,904,591 | OpenGL - animating the data of the vector as separate frames | I have the output of calculation result (basically the certain amount of cuboids in the certain rotations) stored in the std::vector Box, based on which I am creating the model matrices for OpenGl visualization:
std::vector<glm::mat4> modelMatrices;
for (int32_t i = 0; i < Box.number_of_cuboids(); i++)
{
... | To animate your objects with each frame you would need to keep updating you Vertex Buffer Objects(VBOs).
Either you can keep adding each new box with a frame or change the Translation Matrices.
Than set the new data in your VBO before drawing.
If you know the maximum size of your data in that case you can build a large... |
70,900,216 | 70,900,352 | The procedure of control subclassed does not work. Why? | I recently tried to subclass a control using the SetWindowSubclass() function. And to my surprise, it worked smoothly at first. I created the control procedure, but it doesn't receive messages like WM_LBUTTONDOWN or WM_KEYDOWN, and I don't understand why! I searched all my time yesterday and I confess that I am losing ... | You are creating a new BUTTON control and assigning it to a variable named button, but you are subclassing using a different variable named boutton instead.
Assuming that is just a typo, your ControlProc() is returning 0 for every message, it is ignoring the return value of DefSubclassProc(), which may not be 0. You M... |
70,900,488 | 70,912,720 | I can't create two contexts in opengl using sdl2 | i need a debug window, in which i could better observe the scenario the possible changes, and change in real time, using sdl2 and opengl 3.3 i created the second window, changed the event system to close the window using multiple windows, but glContext is buggy, once I create a second context, and as if the first one s... | Here's an example of two windows with separate contexts:
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <stdio.h>
int main(int argc, char **argv) {
(void)argc, (void)argv;
if(SDL_Init(SDL_INIT_VIDEO) < 0) {
fprintf(stderr, "SDL_Init error: %s\n", SDL_GetError());
return 1;
}
... |
70,900,537 | 70,901,544 | How to fix error with SHFileOperationA when I am trying to copy a directory from a remote drive to a new directory on that same drive. WinSysErr 183 | When I am using this method on my local drive it will work as intended and copy my intended directory(With two files inside) to another location on my local drive.
However, when trying to do the same thing on a remote drive, I receive an error code from SHFileOperationA( &directory ); Specifically 183, which looking at... |
I receive an error code from SHFileOperationA( &directory ); Specifically 183, which looking at Windows System Errors I find this: ERROR_ALREADY_EXISTS 183 (0xB7) Cannot create a file when that file already exists.
That is not what error code 183 means in this situation. The SHFileOperation() documentation has the f... |
70,900,539 | 70,900,893 | find the smallest of a set of integers c++ | #include <stdio.h>
int main () {
int n, smNum = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (n != 0 || smNum != 0){
printf("Enter a number: ");
scanf("%d", &smNum);
if (smNum< n) smNum = n;
}
printf("The smallest number is: %d", n);
}
This program must de... | There is a little bit of confusion in the question in my opinion. I will try to understand what you wanted to do and maybe solve some of your doubts.
First of all, it looks a little odd to use the stdio.h functions in C++. Even though it can be used and will definitely work, I would suggest using C, or use C++ function... |
70,900,555 | 70,902,896 | How to enable boost library in xcode | I have a problem with adding boost library to my project in Xcode.
It seems that some parts of boost work correctly but when I use some of them I get the following errors.
Example- boost fiber library:
Undefined symbols for architecture arm64:
"boost::fibers::future_category()", referenced from:
std::make_error... | You would need to manually add the library file in your Xcode. For instance, you were using boost/fiber, then you should at least add the corresponding library file libboost_fiber-mt.dylib in your Xcode project. The file should be located in hombrew/lib. And to add it, you can simply drag it to Targets->General->Framew... |
70,900,886 | 70,901,301 | winsock printing too much | I wanted to try a server/client connection kind of thing, and so I modified the code from a YouTube tutorial (New to C++). So far everything works just fine, except when I try to print the message that was sent by the client.
The code used for sending and receiving data is the following:
char buf[4096];
while (true)
{... | recv() tells you how many bytes were actually put into your buf, but you are ignoring that value when printing the contents of buf. The operator<< you are using expects a null-terminated string, but recv() does not guarantee your buf is null-terminated (even if the client sends a null terminator, it may not have arriv... |
70,901,580 | 70,901,591 | variable in c++ is changing in a function | I have a simple converting function however the variable is changing.
void convert_print(std::string type,int num)
{
if(type=="oct"){
std::cout << num << " oct value is: " << std::oct << num << endl;
}
else if(type == "hex"){
std::cout << num << " hex value is: " << std::hex << num << endl;
}
}... | You haven't told cout to reset the formatting after your last call. This question describes how to restore it. Restore the state of std::cout after manipulating it
|
70,901,800 | 70,901,889 | What happens to a pointer after it has become a unique_ptr? | I have a function that creates a unique pointer to a dynamically allocated object "c".
template<typename T, typename... TArgs> void addComponent(TArgs&&... MArgs) {
if(!components.count(typeid(T))) {
T* c = new T(std::forward<TArgs>(MArgs)...);
c->entity = this;
std::unique_ptr<Component> u... | Wrapping a raw pointer inside of a smart pointer does not change anything about the raw pointer. It still points at the same memory it was originally pointing at. The smart pointer is merely copying the pointer and then managing the pointed-at memory for you, delete'ing the memory when the smart pointer is destroyed ... |
70,901,816 | 70,901,833 | C++ make::shared wrapping on existing raw pointer | I am working on a small wrapper for an FMOD library. Below is a snippet of the code that I have, and there are other libraries that manage the SoundData class:
class SoundData
{
public:
...
std::string mSoundName;
std::shared_ptr<FMOD::Sound> mFmodSoundHandle;
...
}
void SoundLib::CreateSound(SoundDat... | You're passing a pointer where you should pass a reference. Try *sound.
Notice that you're not wrapping a pointer, you're creating a new instance of Sound and copying the value of *sound into it.
To wrap it consider:
data.mFmodSoundHandle.reset(sound);
|
70,902,305 | 70,902,365 | Multiple constructors in a C++ class | While looking online at an implementation of vectors for a math engine, i came across this code.
class R4DVector3n{
private:
public:
//x, y and z dimensions
float x;
float y;
float z;
//Constructors
R4DVector3n();
R4DVector3n(float uX,float uY,float uZ);
//Destructors
~R4DVector3... |
What are the reasons / uses for there being multiple constructors for the class
So that we can create instances of that class using different forms. In other words, to initialize member variables differently for different objects. For example, for your class R4DVector3n we can create instances that uses different con... |
70,902,615 | 70,903,153 | C++ I cant get my function to run in my program | The Function won't initiate can someone help? When I run it in the debugger program skips over function and I don't know why?
#include <iostream>
using namespace std;
int size_array= 0;
int *data_array;
void sorting(int *[], int);
int main()
{
cout<<"enter in array size \n";
cin>>size_array;
int *data_array=new i... | The marked code is simply declaring the function, not calling it.
Also, your data_array is a pointer to a single int whose value is initialized as size_array. But you want an array of size_array number of ints instead.
Try this:
#include <iostream>
using namespace std;
void sorting(int[], int);
int main()
{
int s... |
70,902,673 | 70,928,551 | How to open an in-memory web page with WebView2? | My C++ code has these steps, trying to get JavaScript-generated HTML codes.
Call ICoreWebView2Settings::put_IsScriptEnabled to turn on JavaScript feature
Call ICoreWebView2::NavigateToString to set an in-memory webpage.
When NavigationCompleted happens, we harvest the HTML codes of the entire web page.
Unfortunately,... | I've tried many ways to have JavaScript-rendered code, the best one I got is:
Call ICoreWebView2::AddWebResourceRequestedFilter and ICoreWebView2::add_WebResourceRequested to enable a pseudo URI, e.g. "file://in-mem/doc".
In the callback of event WebResourceRequested,
Call ICoreWebView2WebResourceRequestedEventArgs:... |
70,902,800 | 70,903,032 | How local variable can change the value of global variable in cpp | Here, how can the operation n / 10 which is inside the inner loop, while(n>0), can change the value of n which is inside the same while loop. How the operation of local variable which is inside the inner while loop can change the value of upper level scope variable which is outside the while loop.
|
how can the operation n / 10 which is inside the inner loop, while(n>0), can change the value of n which is inside the same while loop.
For the same reason that digit_sum = digit_sum + last_digit; can change the value of digit_sum, even though it is declared outside of the loop, same as n.
How the operation of local... |
70,903,006 | 71,110,789 | Can getters be marked `noexcept`? | For a class such as this:
class CharMatrix
{
public:
.
.
.
private:
int m_Y_AxisLen;
int m_X_AxisLen;
char m_fillCharacter;
mutable std::vector< std::vector<char> > m_characterMatrix;
}
inline const int& CharMatrix::getY_AxisLen( ) const
{
return m_Y_AxisLen;
}
inline const int& CharMatrix::getX... |
Can one mark all of these getter member functions as noexcept?
Is there any chance that any of these getters might throw?
You can mark them as noexcept.
A simple return (by reference) cannot throw.
A return by copy might throw depending of the copied type.
can operator[] of std::vector throw?
For valid index, no.
... |
70,904,106 | 70,906,692 | Not receiving correct D-Bus reply with Qt | I want to get idle time on Gnome. The following command works when typed into a terminal:
dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime
I'm new to Qt D-Bus and am not sure how to get that same result using QDBusInterface. I have t... | I was able to get this working by changing the type of QDBusReply to qulonglong. The working code is:
QDBusInterface interface( "org.gnome.Mutter.IdleMonitor",
"/org/gnome/Mutter/IdleMonitor/Core",
"org.gnome.Mutter.IdleMonitor");
QDBusReply<qulonglong> reply = inter... |
70,904,351 | 70,908,445 | SQLite3 C++, need a workaround for a sqlite3_stepback | I'm currently programming a .dll in C++ using the functionalities from the sqlite3.c file which can be found in the official SQLite page
The sqlite3.c contains various functions to do basic stuff with sqlite3 like connect to a DB, open a recordset, execute SQL statements, etc..
One of the functions used to navigate to ... |
I need to do a step and then do a stepback in a function to determine the size of the data that will be returned
No, you don't. If you did, someone else would have needed it before you, and the function would exist. Therefore we know some other way is possible, and probably better.
Just reorganize how you're accept... |
70,904,780 | 70,904,802 | Can someone explain the use of last two things in given code | struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
I understood int start and int end but can anyone please describe what other two things represent.
| Interval() : start(0), end(0) {}
This is an empty constructor which initializes the value of start and end to 0.
Interval(int s, int e) : start(s), end(e) {}
This is another constructor which takes two values as parameters and sets the value of start to s and sets the value of end to e
|
70,904,942 | 70,907,220 | Attempting to get every possible substring in binary array | I was not entirely sure how to phrase the title, so please forgive me for that.
Effectively, I am working on a project that has become quite complex, so I am cutting down alot of the code to make it quicker and easier to work with.
So that's the context, here's the issue. I have to find every possible substring of bina... | I combined some info I listed in the comment above, especially one in wikipedia, giving a python code which I adapted to C#. The Concatenate method comes from SO. Note that the original python code is more powerful because it can manage any set of objects, not only zeros and ones.
Here it is, as console app:
using Syst... |
70,904,969 | 70,905,529 | Why is my code not working properly? Is there something in STL-list which I am forgetting? | This is my code:
#include <iostream>
#include <list>
using namespace std;
template <class T>
void display(list<T> l){
list<int>::iterator i;
for (i = l.begin(); i != l.end(); i++)
{
cout << *i << " ";
}
}
void enter(list<int> l){
list<int>::iterator i;
int index = 1;
for (i = ... | The issue is that you pass the list by value in enter. When you update the list with cin >> *i, you are updating a copy of l2 instead of the l2 declared in main().
If you would like to update the list you will need to pass by reference instead.
void enter(list<int>& l){
list<int>::iterator i;
int index = 1;
for ... |
70,904,998 | 70,907,394 | A c++ cross-platform background clipboard manager | So, I've decided to develop my first app. Basically, its functionality is just sitting in the background, waiting for hotkeys (by default they're something like Ctrl-Shift-Key) to handle:
Ctrl-Shift-C provides access to advanced clipboard (probably after programmatically pressing Ctrl-C);
Ctrl-Shift-V draws a pool of ... | Under MSW and Mac you can use wxWindow::RegisterHotKey() to be notified about key presses even when your application doesn't have focus. Unfortunately this function is not implemented for Linux/GTK port and I don't know how could this be done there. If you find a way to do it, don't hesitate to submit patches to wxWidg... |
70,905,026 | 70,905,339 | Issue with capturing of a variadic pack inside of lambda in MSVC19 | I'm trying to write a SFINAE-friendly bind_back function, similar to C++20's std::bind_front. However, it seems that MSVC is having some issues with the code.
I managed to minimize the issue to the following code fragment:
auto bind_back(auto f, auto ...back_args) {
return [=](auto ...front_args)
requires r... |
this is valid C++20, right?
Yes, lambdas can be constrained by requires clause in C++20, so it's well-formed.
is there a work around for MSVC such that I can use these kind of constructs? (i.e. making it SFINAE-friendly).
MSVC seems to have some issues with handling requires clause. Instead, you can use std::in... |
70,905,100 | 70,905,186 | C++ concepts for numeric types and preventing instantiation on pointers | I'm trying to write a concept that instantiates a function if the template parameter is only of numeric type (integers, floats, doubles and so on) and throw an error if the type is a pointer type or a boolean type.
#include <iostream>
#include <type_traits>
#include <boost/type_index.hpp>
template<typename T>
concept ... | The requires clause only checks the validity of the expression and does not evaluate the value, you need to use nested requires:
template<typename T>
concept NumericType = requires(T param)
{
requires std::is_integral_v<T> || std::is_floating_point_v<T>;
requires !std::is_same_v<bool, T>;
requires std::is_a... |
70,905,215 | 70,905,319 | Convert between C++20 NTTP and type | I'm playing around with C++20 NTTPs (non-type template parameters), and I was wondering, is there a way to convert between the elements of an NTTP std::array and types in the form of T<int>?
Consider this example:
template<int X>
struct Func;
template<auto ints>
struct Foo{
// This doesn't work because within the... | You can get a parameter pack with indices to the ints array as template parameter pack using the std::index_sequence method:
return []<std::size_t... I>(std::index_sequence<I...>){
return std::tuple{Func<ints[I]>{}...};
}(std::make_index_sequence<std::size(ints)>{});
Then ints[I] can be used exactly as you intend ... |
70,905,227 | 70,905,552 | epoll does not signal an event when socket is close | I have a listener socket, every new connection I get I add it to epoll like this:
int connfd = accept(listenfd, (struct sockaddr *)&clnt_addr, &clnt_addr_len);
ev.events = EPOLLIN | EPOLLET | EPOLLONESHOT | EPOLLHUP;
ev.data.fd = connfd;
epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &ev)
When new data is received, epoll s... | There are a few problems with your attempt.
You should not use EPOLLONESHOT unless you know what you are doing and you really need it. It disables the report of any other events to the epoll instance until you enable it again with EPOLL_CTL_MOD.
You should not use EPOLLHUP to determine if a connection was closed. The... |
70,905,618 | 71,077,075 | i am unable to initilize vector with initilize elements | I am unable to initialize the vector with initial elements.
I am receiving this error:
no instance of constructor "std::__1::vector<_Tp, _Allocator>::vector
[with _Tp=int, _Allocator=std::__1::allocator]" matches the
argument list
I am using VS Code on a MacBook Air M1.
| Thanks @BoP.
I have just changed my settings to c++14 and it worked image.
|
70,905,720 | 70,905,771 | Why can't we use compile-time 'variables' in consteval functions as template parameters? | I was testing this code (https://godbolt.org/z/fe6hhbeqW)...
// Returns the nth type in a parameter pack of types (ommited for clarity)
// template <std::size_t N, typename...Ts>
// nth_type{}
template <typename... Ts>
struct Typelist{
template <typename T>
consteval static std::size_t pos() noexcept {
... | It doesn't matter that i is guaranteed to be evaluated only at compile-time when its value is known in an abstract sense.
It also doesn't matter whether the function is consteval or constexpr or none of these.
The language is still statically typed and nth_type_t<i, Ts...>; must in any given instantiation of the functi... |
70,905,925 | 70,907,171 | OpenSSL in Qt5 on Windows | I'm trying to link openssl with qt5.12 but the result differs when running executable from qt and from command line. I use QSslSocket::supportsSsl(), QSslSocket::sslLibraryVersionString() and QSslSocket::sslLibraryBuildVersionString() to observe the results. When running exe from qt i get the following output respectiv... | Using listdlls tool i managed to find the name and location of openssl DLLs. They're libssl-1_1-x64.dll and libcrypto-1_1-x64.dll and located in %QT_INSTALL_PATH%/Tools/QtCreator/bin. Copying those DLLs to the build folder of the project solved the issue.
QtCreator used build environment which is apparently the default... |
70,906,214 | 70,906,352 | How can I treat specific warnings as errors in C++ to be cross-platform? | I need to treat some specific warnings as errors to ensure the program runs as it is supposed to. For instance, functions with the [[nodiscard]] attribute should always return, otherwise the compiler prints an error. In Visual Studio (MSVC), it is easy to do that with:
#pragma warning (error: warning_id)
This works pe... | For GCC and clang, the #pragma to elevate a specific warning to an error is very similar.
For GCC:
#pragma GCC diagnostic error "-Wunused-result"
For clang:
#pragma clang diagnostic error "-Wunused-result"
The Intel C/C++ compiler does, as you presume, support the MSVC-style #pragma (and it also defines the _MSC_VER ... |
70,906,222 | 72,711,240 | Howto calculate v (parity / recovery Id) for ECDSA signature using secp256k1 library in C++? | I use the following code (secp256k1 lib for linux) to create an ethereum tx signature in C++:
secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
int res = secp256k1_ec_seckey_verify(ctx, secret);
if(!res)
{
secp256k1_context_destroy(ctx);
return false;
}
secp... | Here is the life-saving code for everyone reads it afterward:
secp256k1_ecdsa_recoverable_signature rawSig;
int res = secp256k1_ecdsa_sign_recoverable(ctx, &rawSig, (uint8_t*) hash.data(), secret, NULL/*secp256k1_nonce_function_rfc6979*/, NULL);
if(!res)
{
secp256k1_context_destroy(ctx);
return false;
}
Signat... |
70,906,254 | 70,913,359 | OpenCL C++ HelloWorld | Good afternoon!
I am learning OpenCL C++ in this tutorial: Click (it's not necessary)
The video uses CL API version 1.2, so I downloaded the OpenCL 1.2 headers from the link in this reply: https://stackoverflow.com/a/57017982/11968932
Visual Studio 2022 shows no errors, but the program outputs these symbols:
╠╠╠╠╠╠╠╠╠╠... | Three mistakes:
It is either __kernel or kernel, but not _kernel with one underscore; same for __global
cl::Buffer memBuf(context, CL_MEM_READ_WRITE, 16*sizeof(buf)); - here 2 things were wrong: the CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY flags meant the buffer on the device side was entirely inaccessible, and it only al... |
70,906,393 | 70,906,577 | c++ function to check if a number is a prime | bool prime (long long int n) {
bool prime = 1;
if (n == 1) {
return 0;
}
else {
for (long long int i = 2; i <= n/2 ; i++) {
if (n % i == 0) {
prime = 0;
break ;
}
}
return prime;
}
}
This is my func... | Your code's time complexity is O(n/2) -> O(n).
It would take around 10000 second to check the primality of n if n is 10^12 (given 1 second can only do around 10^8 operation).
for (long long int i = 2; i <= n/2 ; i++) {
if (n % i == 0) {
prime = 0;
break ;
}
The trick here is that you don't need to ... |
70,906,749 | 70,906,801 | Is there a safe way to cast void* to class pointer in C++ | I am using a C library and I'm passing a "user pointer" to it. When I want to obtain the user pointer the library returns it as void*. I'm currently using static_cast in order to de-reference the members of the original pointer.
So my question is: is there a way to check if the static_cast succeeded?
As far as I know s... | Yes, static_cast is correct here.
Assuming that the void* value is only copied inside the C library, static_cast will return the original pointer value pointing to the passed object if you cast it to a pointer of the same type as it was originally.
Under some conditions you may also cast to a different type, the rules ... |
70,907,123 | 70,907,197 | C++: Segmentation fault - Calling function through std::vector<> using a virtual function and abstract class | This may be a total obvious error for some, but I can't seem to find out why this segmentation fault happens.
I do understand that segmentation faults occur when accessing an address that my program should not access.
First, I have this base-class called "UiObject":
class UiObject {
private:
public:
UiObject()... | = 0 for an abstract base class is correct.
However,
ProgressBar pBar;
//...
uiArray.push_back(&pBar);
is not.
pBar will be destroyed once the scope in which it is declared is left and then trying to dereference the dangling pointer later in renderDisplays is undefined behavior.
You need to create the object with n... |
70,907,132 | 70,907,875 | Compile mex function with external libraries | I'm trying to generate a mex function usigin external libraries. I'm using Ubuntu 18 and Matlab R2021a.
In particular I want to compile my file.cpp that uses my cpp library called model.
What I did is
mex -I<path_library_include> -L<path_library_so_file> -lmodel.so -lboost_system -lstdc++ file.cpp -v
where in -I i pu... | Thanks to 273K that gave me the right direction.
The problem was that the LD_LIBRARY_PATH was not configured well in fact running /sbin/ldconfig -v my library was not present. So to add the shared library i created a new file as root in /etc/ld.so.conf.d/ called mylib.conf it is not important the name just the extensio... |
70,907,173 | 70,907,456 | Printing Pairs inside tuple in C++ | I am trying to print all the values of pair inside of a tuple,
header file
template <typename... Args>
void printPairs(std::tuple<Args...> t)
{
for (int i = 0; i <= 4; i++) //the value of 'i' is not usable in a constant expression
{
auto pair = std::get<i>(t);
cout << pair.first << " " << pair.... | You can use std::apply:
template<typename Tuple>
void printPairs(const Tuple& t) {
std::apply([](const auto&... pair) {
((std::cout << pair.first << " " << pair.second << std::endl), ...);
}, t);
}
|
70,907,179 | 70,907,335 | Why is && strict in compile time? | I am experimenting with basic template metaprogramming. I tried implementing structure templates which help us establish whether their template argument is prime or not. I.e.:
template<int N, int D>
struct IsPrime_Descend {
const static bool val = (N % D != 0) && IsPrime_Descend<N, D - 1>::val;
};
template<int N>
... | Short-circuit evaluation deals with evaluation of expressions. The expression is still there in the text of the C++ file, and it therefore must be compiled. If that expression contains a template instantiation, then that template must be instantiated. That's how compilation works (unless you use if constexpr, which you... |
70,907,397 | 70,907,439 | Passing arguments by reference to constructors of self-defined objects | I have read the sometimes it is better to pass arguments by reference so that if the argument type is large in space, we will not copy it (as happens when we pass by reference).
But I dont quite see how it prevents all of the copies. For example consider the BinaryNode class:
template <class T>
class BinaryNode
{
p... | If you used
BinaryNode(T _key):key(_key), left(NULL), right(NULL), parent(NULL){}
, then there would be potentially two copies if the argument is a lvalue. One copy construction from the constructor argument to the parameter and one from the parameter to the member.
You would usually avoid copies by preferring move op... |
70,908,027 | 70,908,071 | How to use `std::vector.back()` correctly? | I have a bug in my code which I don't quite understand. According to the documentation, std::vector.back() returns a reference to the last element in the container, so here's what I did: (live here)
#include <iostream>
#include <vector>
class Foo {
public:
Foo(int id) : id(id) {
std::cout << "foo " << id... | What's happening here is that when you .emplace_back(1) the std::vector does not have enough space for two elements, so it has to reallocate, copy/move all the existing elements to the new allocation, then emplace_back the new one. Hence you see the only existing element being destroyed from the old allocation.
This go... |
70,908,127 | 70,911,663 | OpenGL VBO doesn't show anything when it is put in a class | I have an OpenGL project where I wanted to wrap all the objects in classes. I started with the VBO. Before wrapping, the code looked something like this:
// includes
int main()
{
// init OpenGL
GLfloat vertices[] = {
// vertices
};
GLint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_... | Use std::vector &vertices instead of float*
VBO::VBO(std::vector<float> &vertices, GLenum type)
{
glGenBuffers(1, &id);
glBindBuffer(GL_ARRAY_BUFFER, id);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &vertices[0], type);
}
Also would be a good idea to create custom Constructor and assign... |
70,908,524 | 70,908,611 | Is this a proper implementation of the Rule of Five (or Rule of Four and 1/2)? | I am studying the Rule of Five and it's cousins (Rule of Four and 1/2, Copy and Swap idiom, Friend Swap Function).
I implemented the Rule of Four and 1/2 on a test class. It compiles well. Is there any hidden mistake in my implementation?
I am particulary preoccupied about the unique_ptrs stored in the m_unorederd_map... | Most important of all:
This class doesn't need custom copy/move operations nor the destructor, so rule of 0 should be followed.
Other things:
I don't like swap(*this, other); in the move ctor. It forces members to be default-constructed and then assigned. A better alternative would be to use a member initializer lis... |
70,909,196 | 70,909,624 | Are view iterators valid beyond the lifetime of the view? | Say I have a custom container class that stores data in a map:
class Container
{
public:
void add(int key, std::string value) { _data.emplace(key, std::move(value)); }
private:
std::map<int, std::string> _data;
};
I want to provide an interface to access the values (not the keys) of the map. The ranges li... |
Are view iterators valid beyond the lifetime of the view?
The property here is called a borrowed range. If a range is a borrowed range, then its iterators are still valid even if a range is destroyed. R&, if R is a range, is the most trivial kind of borrowed range - since it's not the lifetime of the reference that t... |
70,909,321 | 70,909,465 | What should the result be when assigning a variable to a reference to itself, in-between modified and then returned by a function call? | #include <iostream>
int& addOne(int& x)
{
x += 1;
return x;
}
int main()
{
int x {5};
addOne(x) = x;
std::cout << x << ' ' << addOne(x);
}
I'm currently in the middle of learning about lvalues and rvalues and was experimenting a bit, and made this which seems to be getting conflicting results.
ht... | Since C++17 the order of evaluation is specified such that the operands of = are evaluated right-to-left and those of << are evaluated left-to-right, matching the associativity of these operators. (But this doesn't apply to all operators, e.g. + and other arithmetic operators.)
So in
addOne(x) = x;
first the value of ... |
70,909,372 | 70,910,497 | DIPlib: Converting a dip::Image object to a vigra::MultiArrayView object with dip_vigra::DipToVigra not working | I am facing some trouble when I try to convert from a dip::Image object to a vigra::MultiArrayView. The way vice versa works fine, but when I try to call dip_Vigra::DipToVigra I am getting:
error: no matching function for call to ‘DipToVigra(dip::Image&)
How should I do this conversion?
As said, the way vice versa wo... | Because dip::Image has properties (dimensionality and pixel type) defined at runtime, and vigra::MultiArrayView has properties defined at compile time through template parameters, the templated function dip_vigra::DipToVigra() needs explicit template parameters for the compiler to know what the output type is.
That is,... |
70,909,407 | 70,909,700 | Basic operations on iterators in Rust in comparison with C++ | In order to learn Rust, I'm rewriting some leetcode solution from C++ to Rust and on this way I struggle to understand how to perform some basic operations with iterators.
A particular good problem in this context is Data stream as disjoint intervals.
The full implementation in C++ might be found elsewhere.
To avoid go... | When converting code, you should think less about equivalent functions but equivalent concepts.
This code appears to find the entry in the map m that is at or before the key val. Rust's iterators are not like C++'s since they represent a range instead of a pointer to a value. We can use the range ..=val and get the ent... |
70,909,825 | 70,909,934 | Strange behavior from the GNU Compiler | I came across something strange today when writing some code to gather information about network interfaces on Linux. I'm using the standard functionality like ifaddrs and ioctl to pull what I need to pull from the kernel. I'm new to the most of ifaddrs and ioctl functions used to accomplish this, so I'm writing lines,... | ifr_addr is a macro defined in glibc https://github.com/lattera/glibc/blob/master/sysdeps/gnu/net/if.h#L153
# define ifr_addr ifr_ifru.ifru_addr /* address */
So your code becomes:
class RawSock {
private:
//struct ifreq ifr_addr;
struct ifreq ifr_ifru.ifru_addr;
};
Which is invalid.
You may ask ... |
70,909,838 | 70,909,898 | Cannot delete array without read access violation | I recently wanted to make a quick emulator in C++ without using the C++ (C is allowed) standard library features. Thus, I used raw pointer arrays to store the memory of my emulator. However, I encountered a read access violation while moving my memory class to another memory class. All suggestions are welcome.
Memory c... | delete[] mem; is an attempt to delete a not yet allocated memory in the move-constructor. Remove that line.
|
70,910,024 | 70,910,302 | Pointers and references | I am currently learning c++ and pointers inside of c++. I am curious as to why I get a different memory address when I reference a pointer and why it isn't the same as the reference to the variable. Here is my super simple code:
#include <iostream>
using namespace std;
int main() {
int n = 50;
int *p = &n;
cout << "Num... | First you declare an int variable n with the value of 50. This value will be stored at an address in memory. When you print n you get the value that the variable n holds.
Then you declare a pointer *p pointing to the variable n. This is a new variable that will hold the address to the variable n, where it is stored in ... |
70,910,799 | 70,910,980 | polymorphism error: redefinition of a pointer (C++) | I have included
#ifndef FileName_H
#define FileName_H
...
#endif
within all of my header files. In my main.cpp, I would like to use polymorphism of a class Worker:
Worker * w = NULL;
w = new Employee(001,"Tom",3);
w->showInfo();
delete w;
Worker * w = NULL;
w = new Manager(002,"Bob",1);
w->showInfo();
delete w;
Work... | Exactly what the error message says.
Worker * w = NULL;
w = new Employee(001,"Tom",3);
w->showInfo();
delete w;
Worker * w = NULL; // <<<<<<< here's the problem
w = new Manager(002,"Bob",1);
w->showInfo();
delete w;
The second assignment to the pointer redefines the pointer variable, which isn't allowed within the s... |
70,910,855 | 70,911,252 | Remove HTML header from server reply using Regular Expressions | I have an ESP32 T-CALL with an integrated GSM-unit and used this as a base in Arduino IDE.
My code makes a server-call and processes the result. This code reads from the buffer and outputs it to a String. It uses a manually generated POST header, sent serially. However, I need to remove the HTTP header, leaving only th... | This is not a direct answer on how to use the regex, however, if you want to skip the headers and get the payload, other than using regex, or a httpclient library that I suggested in the comment, it is not difficult to do that without using any library.
To skip the header and get the payload, you need to modify your co... |
70,910,948 | 70,911,003 | No iostream for makefile compilation but fine with regular compilation | I have a file like this: (p1.c)
1 #include <iostream>
5
6 int main(int argc, char* argv[]) {
7 std::cout << "No iostream\n";
8 return 0;
9 }
And I try to compile with a simple makefile like this:
1 app: ... | You have only specified a Makefile rule to link the object file to an executable. You haven't actually specified a rule to compile the source code file to an object file.
Therefore make will try to use an implicit rule to build the object file p1.o from p1.c.
Because p1.c has the file ending .c it will assume that the ... |
70,911,121 | 74,032,690 | [Clang Format]Make MACRO after if statement stay on same line | I'm looking for a configuration options(s) for .clang-format that will make clang-format keep a MACRO on the same line as an if statement.
Current:
What I want:
Here is my current .clang-format: https://pastebin.com/GYH79k7u
---
Language: Cpp
BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignConsecutiveAssignments: tr... | Clang-format 12 adds AttributeMacros, as in
AttributeMacros: ['_LIKELY', '_UNLIKELY']
The "clang-format 12.0.1" installed by Homebrew doesn't yet support this option, but clang-format 14.0.6 (the current Homebrew release) does. The result with your .clang-format file plus the above line seems to give exactly what you ... |
70,911,226 | 70,911,333 | How to overload + operator so can write newVacation = oldVacation + 5, // which adds 5 to numDays, while just copying numPeople | I am trying to write a program that overloads the + operator. When I input 7 and 3, it correctly prints:
First vacation: Days: 7, People: 3
But incorrectly prints:
Second vacation: Days: -158458720, People: 32764
It should be outputting:
Second vacation: Days: 12, People: 3
#include <iostream>
using namespace std;
cla... | Your operator has undefined behavior.
It is declared as returning a new FamilyVacation object, but is actually not returning anything at all. That is why secondVacation.Print() is printing garbage.
Worse, your operator is modifying the object it is being called on (and not even modifying it with the correct value!), wh... |
70,911,546 | 70,911,637 | C++ hide all function symbols except for what I specify in a shared library | In my example code:
main.cpp
#include <iostream>
#if defined(_WIN32) || defined(__WIN32__)
#define EXPORT extern "C" __declspec(dllexport)
#elif defined(linux) || defined(__linux)
#define EXPORT __attribute__((visibility("default")))
#endif
EXPORT void hello()
{
std::cout<<"Hello world!"<<std::endl;
}
... | Your approach is correct but your program contains some undefined symbols which need to be imported from libstdc++ at startup (e.g. std::cout). Linker has to insert such symbols in your library's symbol table, otherwise loader won't know that they need to be imported.
You can link against static version of STL (via -st... |
70,912,100 | 70,912,182 | Windows C++: Check if DLL is present and loadable without calling LoadLibrary | Does Windows have a built-in way of checking if a DLL is present and could be loaded with LoadLibrary, without actually calling LoadLibrary?
I want to check for the presence of DLL B, from within a function called during LoadLibrary for DLL A. Calling LoadLibrary from within a LoadLibrary call (nested LoadLibrary calls... | GetModuleHandle() can check if a DLL is already loaded.
While you are not supposed to call LoadLibraryEx() in DllMain(), calling it with LOAD_LIBRARY_AS_DATAFILE might be OK. If you do this, you have to chop off the bottom two bits in the handle, and manually check that the machine value in the PE header is the same as... |
70,912,126 | 70,912,272 | Segfault when trying to add a node to front of linked list | Im confused why im getting a segfault in this code. gdb says the segfault occurs when I try and assign data to the list->value but I cant figure out why that would be so. Any help is appreciated!
int main(){
SingleLinkedListNode *list = 0;
int element = 10;
pushFront(list, element);
//cout << list->v... | I assume this is for some academic purpose, because in reality no one in their right mind would reinvent a single linked list when you could just use a std::forward_list and be done with it (don't reinvent wheels).
You appear to be confused between trying to tie a global head pointer into a solution that (a) doesn't ne... |
70,912,167 | 70,912,205 | How do I tell if I am using VLA (Variable Length Array)? | I am on a project where we have to read in from a file, temporarily store them in dynamically allocated memory, do sorting and stuff, and deallocate the memory.
As per the project is testing our knowledge over dynamic memory and memory leak, one of the instructions is do not use VLA.
I am not sure what our instructor m... | int *numberArray; numberArray = new int[size]; is not a variable-length array, it's a dynamically allocated array. That's fine. Note that you have to delete[] it when done, which you do.
A VLA declaration would look like int numberArray[size]; where size is not a constant. It gets automatically deallocated when it g... |
70,912,301 | 70,912,363 | The rest of the statement is not executed after the while statement completes | I type in a sentence on the console,the rest of the statement is not executed after the while statement completes.
map<string, size_t> stringMap;
string str;
while (cin>>str)
{
++stringMap[str];
}
for (const auto &w : stringMap)
{
cout << w.first << "occurs" << w.second << "times" << endl;
}
| You'll have to pass EOF. To pass EOF you can use Ctrl+z in Windows and Ctrl+d in Unix systems.
Another solution is to type a specific word to exit. Eg:
while ((cin>>str) != "exit").
|
70,912,377 | 70,912,411 | Why do I get an error for the first statement, but not the second one? (C++ substring) | The goal is to get the first, middle, and last name initials each followed by a period.
string first;
string middle;
string last;
string result;
The expression is typed in the string result.
I typed:
result = first[0] + "." + middle[0] + "." last[0] + ".";
And received an the following error:
invalid operands of type... | first[0] + "."
In this expression:
first is a std::string.
Therefore, first[0] is a char (some immaterial technical details omitted).
"." is a char [2] (an array of two char values).
In C++, it is illegal to add a char value to a char [2], you can't just add char to an array. That's simply not allowed in C++. There ... |
70,912,432 | 70,912,760 | Iteration speed of unordered_set vs vector | I have an application where I need to store various subsets of different customers. The order of the customers in the container does not matter.
Since the order does not matter, I was hoping that storing and iterating through this set of customers would be faster on an std::unordered_set<int> as compared to std::vector... | std::vector is the fastest STL container for linear iterations like in your scenario. This is simply because memory is contiguously allocated and therefore can benefit of caching mechanisms. A vector iterator just increments a pointer internally.
You might improve performance further by trying to use a smaller type tha... |
70,912,455 | 70,912,589 | How can I use a variable from a previous recursive call? | The general problem:
Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.
Return the number of nice sub-arrays.
My question:
I want to solve this problem recursively. The part I'm struggling to implement is how do I use the count from every previous re... | it's not particularly good candidate for recursion. might be possible to solve with just one pass on the array.
That said, small adjustments to your code could make it work. There is no reason to pass count into the recursive method.
Your method calculates the number of subarrays that are 'nice' starting with the given... |
70,913,545 | 70,913,581 | Template enable_if for arithmetic AND complex numbers | I have the following template-statement that works for int's, floats, doubles:
template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type > struct Matrix
{
//...
};
I want to extend it to cover complex numbers as well. How do I add/change the above for that. Or am I going for ov... | template <template <typename...> typename T, typename U>
inline constexpr bool is_specialization_of_v = false;
template <template <typename...> typename T, typename ...P>
inline constexpr bool is_specialization_of_v<T, T<P...>> = true;
Then is_specialization_of_v<std::complex, T> will tell you if T is std::complex<..... |
70,913,680 | 70,914,123 | std::unique_ptr saving reference in a Factory class? | I am attempting to utilize a ConnectionPoolFactory (let's call it Factory A) this factory creates a std::unique_ptr<cpool::ConnectionPool> .. i understand this unique pointer cannot be copied (otherwise it won't stay unique)..
but how can I pass this reference to another factory (let's call it Factory B) for use?
The e... | The smart pointer sharing issue is something you are already aware of, so focusing on the how to pass and assign a reference question.
What's wrong
Reference variables (const declared ones aswell) can be assigned only once during initialization. This is what the compiler would complain about if the types would match.
H... |
70,913,891 | 70,915,039 | Compile-time map on a type list | I am looking for an idiomatic way to apply a type-level transform for each element in a type list. So far I came up with the following, which works as expected:
namespace impl_
{
template <template <typename> typename, typename>
struct MapVariant;
template <template <typename> typename F, typename... Ts>
struct MapVari... | Thanks to Fureeish I managed to fix this with a trivial change:
template <template <typename> typename, typename>
struct MapVariant;
template <template <typename...> class C, template <typename> typename F, typename... Ts>
struct MapVariant<F, C<Ts...>>
{
using Result = C<F<Ts>...>;
};
The outer alias need not be ... |
70,914,115 | 70,914,241 | Incompatible sender/receiver arguments | Hello veryone Please, help me to solve this probleme...
File.h
public slots:
void Manage_User_Connexion(QString UserName, QString Password);
file.cpp
QObject::connect(PbLogin,SIGNAL(clicked()),this,SLOT(Manage_User_Connexion(QString,QString)));
And I get this error: Incompatible sender/receiver arguments
Thank fo... | Signal clicked() probably does not have any arguments. So you cannot connect it to a slot which expects two QString arguments. The arguments passed to signal when it is emitted are supposed to be passed to the slot. If the arguments are not compatible, then this cannot be done. You need to redesign your code, you proba... |
70,914,117 | 70,914,285 | Is there a method on how i can find and replace a character in a string? | So i want to make a simple hangman console game that chooses random words from a file. The problem is, when i try to check if the input is found in the word i'm trying to guess, the program jumps over the check. I'm thinking i made a serious mistake earlier in another functions and i don't know how to fix it.
Below you... | I'm not sure why you have two for loops? The inner for loop checks whether the first letter matches, if it does then it prints correct and breaks, if it isn't then it prints incorrect and breaks so in both cases only the first letter is checked. The outer loop then runs again and again the inner loop checks the first l... |
70,914,339 | 70,920,197 | How to find shortest path between every node within K moves? | Lets say I have following graph:
Now what I want is to get shortest path between every node in graph(or have -1 at that place in matrix if it is not possible to get from 1 node to other) , but that path need to have lenght less or same as K.
Now I tried using floyd-warshall algorithm replacing automatically path from ... | l[i][j][1]+=1; it's wrong it should actually be l[i][j][1]=l[i][k][1]+l[k][j][1]; but this brakes your solution logic. So i recommend you do like this: count log(K) matrices: i-th matrix means length from j to k in no more than 2^i moves. Look at K in binary and when it-s 1 on i-th place you should recalc your ~current... |
70,915,192 | 70,916,937 | When removing the Config.json file from the ProgramData, showing "Permission Denied" in C++ | I am trying to remove the config.json file from program data, But with the below code it is showing "Permission Denied".
int main()
{
std::string f_strConfigFile = "C:\\ProgramData\\TestApplication\\TestConfig.json";
std::string l_strFileContents;
std::ifstream l_ifConfigFileStream(f_strConfigF... | Common Application Data Folder
There might not be any issue with your code in itself. Although I stand by all the suggestions made in the comments. They will make your code more efficient.
In the comments you said:
I tried by printing errno. It is showing "Permission denied".
Administrator rights are needed to save f... |
70,915,412 | 70,917,161 | How can I execute two for loops in parallel in C++? | In C++ I would like two for loops to execute at the same time and not have one wait for the other one to go first or wait for it to end.
I would like the two for loops (or more) to finish the loops in the same speed it would take one loop of the same size to finish.
I know it's been asked and answered, but not in an ex... | As already mentioned in the comments that OpenMP may not be the best solution to do so, but if you wish to do it with OpenMP, I suggest the following:
Use sections to start 2 threads, and communicate between the threads by using shared variables. The important thing is to use atomic operation to read (#pragma omp atomi... |
70,915,441 | 70,915,600 | Finding the amount of numbers within an array within a specific range using recursion | I've been stuck on a recursion assignment for hours now.
Basically its recursion practice and I completed everything except one thing:
Find the amount of numbers in range within an array.
I have to use recursion, and pointers of the array. So far I've done find the sum of array and find if the array HAS the numbers wit... | If the number is in range add one
if ((*pBegin) >= min && (*pBegin) <= max)
return 1 + numberOfValuesInRange(min, max, pBegin+1, pEnd);
Code:
#include <iostream>
using namespace std;
int numberOfValuesInRange(float min, float max, const float *pBegin, const float *pEnd){
if(pBegin >= pEnd) // base c... |
70,915,742 | 70,915,778 | C++ - Deducing type from inherited constructor's arguments for class template | I have a class template that inherits the constructors of the base class template. (As for c++20) Is there a way to deduce the template arguments of the derived class from the constructor arguments of base?
If I specify the type explicitly, that works. Or if I reimplement the constructor and call the constructor of bas... | You can add a user-defined deduction guide:
#include <utility>
template<typename T>
struct CTestBase
{
using Type = T;
CTestBase() = default;
CTestBase(T t){}
};
template<typename T>
struct CTestDer : public CTestBase<T>
{
using CTestBase<T>::CTestBase;
};
template<typename T>
CTestDer(T &&t) -> CTe... |
70,916,163 | 70,916,270 | What does this passage from cppreference.com (Default arguments) mean? | From cppreference page on default arguments:
Non-static class members are not allowed in default arguments (even if they are not evaluated), except when used to form a pointer-to-member or in a member access expression:
int b;
class X
{
int a;
int mem1(int i = a); // error: non-static member cannot be used
... | The first part means that you are allowed to form a pointer-to-member to one of the non-static members, e.g.:
class X
{
int a, b;
int mem1(int X::* i = &X::a);
//...
};
A pointer-to-member is a rather obscure part of the language. You have maybe seen member function pointers, but you are also allowed to fo... |
70,916,398 | 70,922,191 | Fill inner area of a character with drawContours | I have an input image:
I use few functions to find contours in this image:
cv::Mat srcImg = cv::imread("input.png");
cv::Mat grayImg{};
cv::cvtColor(srcImg, grayImg, cv::COLOR_BGR2GRAY);
cv::Mat threshImg;
cv::adaptiveThreshold(grayImg, threshImg, 255, cv::ADAPTIVE_THRESH_GAUSSIAN_C, cv::THRESH_BINARY_INV, 11, 2);
My... | If you get the binary image via Otsu Thresholding, you get a nice binary blob without any "filling problems":
// Read the input image:
std::string imageName = "D://opencvImages//UZUd5.png";
cv::Mat testImage = cv::imread( imageName );
// Convert BGR to Gray:
cv::Mat grayImage;
cv::cvtColor( testImage, grayImage, cv::... |
70,916,541 | 70,916,694 | Inheritance: If private is default, why do these two examples not work the same way? | I was working around with inheritance in C++. To my knowledge if you don't specify, B will always inherit private from A.
So why does this code work:
struct A {};
struct B : A {};
int main(void)
{
A b = B();
return 0;
}
But this creates the "A is an inaccessible Base of B" error:
struct A {};
struct B : priva... | Private inheritance is the default if the derived class is defined using the word class.
If you create it using struct, then inheritance is public by default.
|
70,916,600 | 70,917,328 | Finding function offset from file from RVA | I want to find a function inside my .exe, and memcpy it somewhere else.
I have used the IDIA SDK to parse the .pdb file for my .exe, which contains a simple function named "myFunction", which simply performs an assembly "ret", just for demonstration purposes.
if (pTable->QueryInterface(__uuidof(IDiaEnumSymbols), (void*... | The formula you gave is not what is described in the answer to the question you linked. The answer to that question is, however, correct; you need to find which section contains the RVA of interest, and then add the difference between that RVA and the RVA corresponding to the start (i.e. first byte) of that section to ... |
70,916,766 | 70,917,348 | How to pass a string to omnetpp simulation from the command prompt | In my .ned file I have a simple module
simple Txc1
{
parameters:
int dummy_number = default(10);
}
When I run the simulation from the command prompt by specifying dummy_number I want i.e.,
opp_run -l tictoc omnetpp.ini --**.dummy_number=15
dummy_number equals 15 in my simulation.
But when instead of integ... | As long as your string does not contain a space, add backslashes before quotes, i.e.:
opp_run -l tictoc omnetpp.ini --**.dummy_string=\"TestWithoutSpace\"
|
70,917,439 | 70,918,462 | Clang ast-dump results in infinite loop | For some reason when I try to get the ast-dump of any C/C++ code with Clang, I get an infinite loop which eventually results in clang: error: linker command failed with exit code 1136 or some similar error code.
I'm running Windows 10 with Clang version 13.0 (Also tried Clang 12.0 with same issues). I run the command c... | It's not an infinite loop if it terminates. :-)
The dumped AST includes stdio.h, which you included, so it's quite big (about 800 lines, when I tried it).
The error message is because the clang compiler (cc1) does not produce an object file when you pass it the -ast-dump option, but the clang driver (clang) doesn't kno... |
70,917,504 | 70,917,618 | What does explicitly-defaulted move constructor do? | I'm new to C++ and need some help on move constructors. I have some objects that are move-only, every object has different behaviours, but they all have a handle int id, so I tried to model them using inheritance, here's the code
#include <iostream>
#include <vector>
class Base {
protected:
int id;
Base() :... |
What does explicitly-defaulted move constructor do?
It will initialize its member variables with the corresponding member variables in the moved from object after turning them into xvalues. This is the same as if you use std::move in your own implementation:
Base(Base&& other) noexcept : id(std::move(other.id)) {}
N... |
70,917,620 | 70,917,783 | How to avoid code duplication in this particular case | I have these generic classes for 2D geometry:
template<class T> struct Point
{
T x,y;
//...Various member functions...
//T modulus() const noexcept { ... }
//T dist_from(const Point& other) const noexcept { ... }
//...
};
template<class T> class Polygon
{
public:
// ...An awful lot of member... | You could try to parameterize the Polygon class to take in the Point type as well:
template <class P> class Polygon {
std::vector<P> vertices
}
template <class T> class Point {
T x,y;
}
class DecoratedPoint : Point<long> {
int extraData;
}
Polygon<DecoratedPoint> newPoly;
The decorated data would end up comin... |
70,917,756 | 70,917,821 | How many levels of explicit casting? | Code snippet #1.
int n = 46341;
long long value = ((long long) (n * (n + 1))) / 2;
std::cout << value; // -1073716337 -- WRONG!
Code snippet #2.
int n = 46341;
long long value = (long long)((long long)((long long)n * ((long long)n + 1))) / 2;
std::cout << value; // 1073767311 -- CORRECT!
How many levels of explicit c... | One. As a general rule, the result of an arithmetic expression will take the type of the larger of the two.
long long value = (n * (static_cast<long long>(n) + 1)) / 2;
So (long long)n + 1 is addition of a long long and an int, so the result is long long. Then n * (...) is multiplication of an int and a long long, so ... |
70,918,009 | 70,918,182 | How to input and output item names, price, and quantity in a shopping cart? | I am trying to create a program that prompts user for item name, price, and quantity. And then outputs the info entered by the user. When I run it using inputs: Chocolate Chips, 3, 1, it outputs:
Item1
Enter the item name:
Chocolate
Enter the item price:
0
Enter the item quantity:
32599
It should be outputting:
Item1
E... | Replacing
cin >> name;
with
getline (cin, name);
did the trick.
|
70,918,239 | 70,918,572 | Pass argv to function: error: array type 'char *[]' is not assignable | I want to let a sub class to handle the command line arguments but get error: array type 'char *[]' is not assignable.
I have tried assignment with *and & and also looked getoption_long()
#include <stdio.h>
class {
public:
void setParam(int _argc, char *_argv[]) {
argc = _argc;
argv = _argv; // something wron... | According to C++ standard arrays are not assignable because they are non-modifiable lvalue.
If you want to copy pointer to your arguments array to argv parameter of sp class change this parameter type to char** argv;
|
70,918,436 | 70,918,789 | How to safely zero std::array? | I'm trying to safely zero a std::array in a class destructor. From safely, I mean I want to be sure that compiler never optimize this zeroing. Here is what I came with:
template<size_t SZ>
struct Buf {
~Buf() {
auto ptr = static_cast<volatile uint8_t*>(buf_.data());
std::fill(ptr, ptr + buf_.size(),... | The C++ standard itself doesn't make explicit guarantees. It says:
[dcl.type.cv]
The semantics of an access through a volatile glvalue are implementation-defined. ...
[Note 5: volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.