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 |
|---|---|---|---|---|
73,364,524 | 73,375,622 | trying to update TWSAPI.. getting error on linking? is this the new intel lib? | I utilize a conan recipe to build the TWS-API in C++ .. and recently (4-10 months ago) IBKR pushed in a prebuilt library into the mix.. some intel lib..
I tried to fix all the code , refresh function definitions.. but on linking I am getting stuck
...
-- Library z found /home/emcp/.conan/data/zlib/1.2.12/_/_/package/df... | according to this post https://github.com/InteractiveBrokers/tws-api/issues/1150#issuecomment-1215515313
we have a problem with the new intel code not linking properly.. this user was on Debian and was able to apt install the library.. and link it manually
sudo apt install libintelrdfpmath-dev
and in your linker.. add... |
73,365,461 | 73,365,551 | Non-type parameter pack cartesian product, "template argument deduction/substitution failed" | I was messing with non-type parameter packs and tried to do a cartesian product with them. I arrived at a piece of code that somehow compiles with GCC in C++20 but not C++17, and does not compile with Clang at all. I also tried MSVC, which, like GCC, compiles in C++20 but not C++17, but also generates a lot of assembly... | When you write,
ValueParameterPack<
std::make_pair(
get_v<Is / sizeof...(values2), ValueParameterPack<values1...>>,
get_v<Is % sizeof...(values2), ValueParameterPack<values2...>>
)...
>;
you can't pass a std::pair as a template non-type argument. You can, however, pass it as... |
73,365,561 | 73,422,496 | cygwin g++ can't find pmr namespace and related issues | Ok so I decided to compile some code from godbolt locally on my Windows 10 64bit using Cygwin and the cygwin terminal. It compiles fine on godbolt, but cygwin/mingw64 g++ spits out loads of errors along the lines of:
jsontest.cpp:310:23: error: βstringβ is not a member of βstd::pmrβ; did you mean βstd::stringβ?
310 |... | To use anything in the std::pmr namespace, it looks like you need to add -D_GLIBCXX_USE_CXX11_ABI to your general compiler flags. I got a clean and successful compile and execute with g++ -std=c++20 -Wall -Wextra -Werror -D_GLIBCXX_USE_CXX11_ABI test_pmr.cpp -s -o test_pmr.exe
|
73,365,661 | 73,365,723 | Systematic approach of how to think about operator overloading | I'm learning how to do operator overloading and trying to come up with a systematic approach of how to know number of arguments an overloaded operator should take in and if the function should be constant.
I know the system is not perfect and doesn't catch all the edge cases, but I'm thinking that will work itself out ... | You got one thing wrong:
friend std::ostream& operator<<(std::ostream& os, Vector const& other);
You say this is written with two explicit arguments "because one of them is a stream." But actually it takes two explicit arguments because the friend keyword on the front implies this is a free function, not a member fun... |
73,365,803 | 73,381,619 | Error when including struct in a header file C++ "cannot overload functions distinguished by return type alone" | I have the following structures that work fine when included in a single main.cpp file. But, when I try to move things to a header.h I get an error.
An example, main.cpp with full definitions (before moved to header.h file):
using namespace std;
static const int nx = 10;
static const int ny = 10;
struct c... | As someone in the comments suggested, the solution was to only define my struct in the header.h file and not to redefine it again in the header.cpp file.
|
73,365,808 | 73,366,719 | Shared pointer to a const object thread safety | A thread holds a shared_ptr to a const map object. This shared_ptr is occasionally updated by another thread. This shared_ptr could also be read by different threads.
Code snippet:
class SharedPointerHolder {
private:
shared_ptr<const map<int, string>> sptr_;
public:
SharedPointerHolder() : sptr_(make_share... | Yes, access to sptr_ needs to be synchronized.
Only modification of the shared_ptr's control block is atomic. Modification of the shared_ptr itself is not. If a single shared_ptr object is shared across threads then it will generally need some form of synchronization.
Consider this logical diagram of multiple shared_... |
73,366,157 | 73,438,040 | Integrating X3Daudio with XAudio2 | I am currently struggling with implementing 3D positional sound with XAudio2 library.
I somehow managed to got it working when listener's and source's position are exactly 0.0f on all axis. When I move listener or source even a little bit, sound is no longer heard but is still playing. What am I missing here? Thanks :)... | Okay, thanks to @chuck-walbourn I managed to get it working.
The problem was that X3DAUDIO_EMITTER's member CurveDistanceScaler was set to FLT_MIN instead of some not-so-small value.
Weird thing is I was following official Microsoft documention How to integrate X3DAudio with XAudio2 and the example code uses FLT_MIN, ... |
73,366,837 | 73,367,346 | Removing selected child elements in a XML file C++ | I'm using tinyxml2. I have xml file with many elements on one node. My xml file:
<city>
<school>
<class>
<boy name="Jose">
<age>14</age>
</boy>
<boy name="Jim">
<age>15</age>
</boy>
<boy name="Mike">
... | You have two errors in that code. One is a syntax error and the other is a logical error.
The syntax error is that you can't name a variable "class" because "class" is a reserved word in C++.
The logical error is that your for loop is iterating over elements by incrementing using the element's NextSiblingElement getter... |
73,366,933 | 73,366,971 | What does "+" mean in cpp lambda declaration "auto fun1 = +[](){};" | I've seen in stackoverflow, people write lambda like this:
int main() {
auto f1 = +[](){};
auto f2 = [](){};
return 0;
}
(1) What does the + acturelly do in f1 expression?
I tried to add capture, then f1 doesn't compile, but the error is not readable to me:
auto f1 = +[=](){}; // fail to compile
... | A lambda has a compiler-generated type. If you just assign the lambda as-is to an auto variable, then the auto variable's type will be deduced as the lambda's generated type.
A non-capturing lambda is implicitly convertible to a plain function pointer. By placing + in front of the lambda, the lambda is explicitly con... |
73,367,039 | 73,367,074 | Allocating memory thorugh malloc for std::string array not working | I'm having trouble allocating memory on the heap for an array of strings. Allocating with new works but malloc segfaults each time. The reason I want to use malloc in the first place is that I don't want to call the constructor unnecessarily.
This works fine
std::string* strings = new std::string[6];
This doesn't
std:... | malloc() only allocates raw memory, but it does not construct any objects inside of that memory.
new and new[] both allocate memory and construct objects.
If you really want to use malloc() to create an array of C++ objects (which you really SHOULD NOT do!), then you will have to call the object constructors yourself u... |
73,367,127 | 73,367,168 | std::binary_search curious issue with char array | So I i'm implementing a rot13 for fun
const char lower[] = "abcdefghijklmnopqrstuvwxyz";
int main() {
char ch = 'z';
if (std::binary_search(std::begin(lower), std::end(lower), ch)) {
std::cout << "Yep\n";
}
else {
std::cout << "Nope\n";
}
}
This outputs nope. Any other character ... | Note that a c-string is not ordered increasingly unless empty (as it ends with '\0'). If you fix it to pass the preceding iterator (that points past 'z', not '\0'), it works:
#include <iostream>
#include <algorithm>
const char lower[] = "abcdefghijklmnopqrstuvwxyz";
int main() {
char ch = 'z';
if (std::binary... |
73,367,205 | 73,367,587 | Why cpp std::function can hold capture-lambda, while function pointer cannot? | I've got this code snippet:
int x = 3;
auto fauto = [=](){ cout<<'x'; };
function<void()> func{fauto};
func();
void (*rawPf)() = fauto; // fail to compile
rawPf();
I knew the syntax that only non-capture lambda can be assigned to function pointer. But:
(1) Why std::function can hold capture-lam... | Why can a function pointer not hold a lambda with a capture : because a Lambda is NOT a function ,it's an object!
Why can a lambda without a capture be converted to a function pointer ?
A Lambda is just an ordinairy object (a piece of data) of a compiler generated class (with a unique classname that only the compiler k... |
73,367,255 | 73,367,326 | How to pass c++ function/lambda as none-type parameter to a typedef/using template? | I've got a need to write RAII wrapper functions/classes to some C library. I know we can use a smart pointer and pass a deleter function, like this:
FILE* pf = fopen("NoSuchFile", "r");
shared_ptr<FILE> p1{pf, fclose}; // OK.
But, for more complex scenarios other than fopen()/fclose(), I don't wish to write code to pa... | What you propose will NOT work for std::shared_ptr, simply because the deleter is not a template parameter of std::shared_ptr. So, you can't specify a deleter in a typedef/using statement when aliasing a std::shared_ptr type. It can only be specified in the std:::shared_ptr's constructor.
If you don't want to specify a... |
73,367,535 | 73,396,399 | How to instruct Google Test to expect std::abort()? | I am using Google Test on code I expect to fail. As part of this failure the code calls a custom assert macro, which contains std::abort().
Unfortunately Google Test's EXPECT_EXIT() is not "catching" the std::abort().
This is a self-contained example to emulate what I'm trying to achieve:
// A placeholder for my assert... | I needed to use ::testing::KilledBySignal(SIGABRT)
|
73,367,767 | 73,368,726 | how to get `compile_commands.json` right for header-only library using cmake? | I'm learning CMake and clangd, but I can't find a way to make CMake generate a proper compile_commands.json for clangd to parse third party libraries.
Here's what I've tried:
add_library(date_fmt INTERFACE)
target_include_directories(
date_fmt INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
... | The issue is that compile_commands.json is only used for things that are actually being compiled. Since your CMakeLists.txt only creates an INTERFACE library and nothing uses it, there's no need to generate the compilation database.
Add something like this to your CMakeLists.txt
add_executable(smoke_test smoke_test.cp... |
73,367,843 | 73,368,150 | How to block a message using WH_GETMESSAGE hook? | In the CBTProc hook, there's: return 0 to allow the msg, 1 to deny.
What about the WH_GETMESSAGE hook? How I could 'block' a message from being executed?
In this example:
LRESULT CALLBACK GetMsgProc(_In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam
)
{
if (nCode < 0)
return CallNextHookEx(nullptr, nCod... |
What about the WH_GETMESSAGE hook? How I could 'block' a message from being executed?
You can't block the message. Once all hook procedures in the chain have exited, the message is then passed to the original caller of (Get|Peek)Message(). There is no option to avoid that.
Do I need to replace pMsg->message with s... |
73,367,992 | 73,369,600 | Why is ptrdiff_t signed? | If ptrdiff_t were unsigned, it would be able to refer to twice as many elements. On my machine PTRDIFF_MAX is expanded to 9223372036854775807i64, whereas ULLONG_MAX is 18446744073709551615Ui64.
I know that these values are huge themselves, but if
The type (ptrdiff_t)'s size is chosen so that it can store the maximum s... |
If ptrdiff_t were unsigned, it would be able to refer to twice as many elements.
That is not correct. Making a type unsigned does not magically increase the amount of information it can hold. Signed and unsigned integers of the same size have exactly the same number of different states. In the signed version, half th... |
73,368,382 | 73,369,311 | zsh: bus error ./array_stack on using pointers to access the stack elements | the code run fine when I used the dot operator for accessing the elements of the stack. But on using pointers to access the stack structure, I was getting this error. zsh: bus error ./array_stack. Can anyone help me in resolving this.The code is as follows:
#include<iostream>
using namespace std;
//implementing the... | EDIT: This question was originally tagged as C (not C++). I'm still not sure which way it will go. I will modify this answer to use C++ when it's clear.
The problem is you're defining S as a pointer to a Stack, but you never tell it to point to anything. So S is pointing to somewhere in memory (you probably don't ow... |
73,368,437 | 73,369,710 | How to get the HWND of the taskbar MSTaskListWClass? | How i could retrieve the MSTaskListWClass hWnd?
I mean the "Running applications" tool bar which shows the button of each window in the taskbar.
I have tried to get it with:
HWND mstask = FindWindow(L"MSTaskListWClass", NULL);
DWORD err = GetLastError();
But mstask return null, err outputs 0
| FindWindowW retrieves a handle to the top-level windows only. not for child windows. so need first search for parent window - "Shell_TrayWnd" and than use EnumChildWindows
BOOL CALLBACK EnumChild(HWND hwnd, LPARAM lParam)
{
WCHAR name[32];
if (GetClassNameW(hwnd, name, _countof(name)) && !wcscmp(name, L"MSTask... |
73,368,532 | 73,368,618 | Get istream_iterator from ifstream | I tried to get an istream iterator from an ifstream, but failed...
void Test_CH_3_1::set_up()
{
std::ifstream file_in("makefile-dependencies.dat");
typedef boost::graph_traits<Graph>::vertices_size_type size_type;
size_type n_vertices;
file_in >> n_vertices; // read in number of vertices
if (file_in... | The error message is quite clear. There is no operator>> defined for reading std::pair from a std::istream. Define one in your application code and all should be well.
std::istream& operator>>(std::istream& in, std::pair<std::size_type, std::size_type>& p)
{
return in >> p.first >> p.second;
}
|
73,368,541 | 73,645,782 | get image dimension from blob column in MySQL database | I want to read image from a database, image column is a MYSQL_TYPE_BLOB type and I read column using this code. Currently, Blob image converted as a char * array
//Get the total number of fields
int fieldCount = mysql_num_fields(result);
//Get field information of a row of data
MYSQL_FIELD *fields = my... | By decoding buffered image:
length = mysql_fetch_lengths(result)[i];
buffer = new char[length + 1];
memset(buffer, 0x00, sizeof(buffer));
memcpy(buffer, m_row[i], length);
matImg = cv::imdecode(cv::Mat(1, length, CV_8UC1, buffer), cv::IMREAD_UNCHANGED);
At first, copy array to buffer, then convert it to a cv... |
73,369,841 | 73,370,169 | Move constructor for vec3 class | I'm trying to improve my cpp lately, and I want to write my own vec3 class to represent a 3D vector and point. I want it to hold 3 values of the same type and have some standard operations like addition and things...
I'm trying to learn more about move semantics and I'd like to create a move constructor that would take... | You didn't write a move constructor, nor a copy constructor. They would have to look like vec3(vec3 &&) and vec3(const vec3 &) respectively. You shouldn't write them manually if possible (including in this case), the compiler will generate them for you. The same applies to copy/move assignment, and to the destructor.
R... |
73,369,864 | 73,370,292 | Why does overloading operator< for std::tuple not seem to work in priority_queue? | Here is the MWE:
#include <iostream>
#include <tuple>
#include <queue>
using namespace std;
bool operator<(tuple<int, int, int> lhs, tuple<int, int, int> rhs)
{
return get<1>(lhs) < get<1>(rhs);
}
int main()
{
priority_queue<tuple<int, int, int>> q;
q.push(make_tuple(2, 5, 3));
q.push(make_tuple(2, 3,... | Your overload of operator< is not selected because it's in a different namespace than both std::priority_queue and std::tuple. It's not in the candidate set, so it is never even considered as an overload candidate.
The search for a suitable overload happens in the namespace where the operator is called from, which is t... |
73,370,346 | 73,370,439 | How template argument deduction is performed in this example? | Consider the following example:
template <class T>
void f(const T&&) { std::cout << __PRETTY_FUNCTION__; };
int main(void){
const int *cptr = nullptr;
f(std::move(cptr));
}
Per [temp.deduct.call]/1:
Template argument deduction is done by comparing each function
template parameter type (call it P) tha... |
Why the deduced template argument is const int* and not int* as I expect?
The const in P = const T is a top level const and applies to T while the const in A = const int* is a low-level const meaning it does not apply to the pointer. This in turn means that you can't directly compare const T with const int* the way y... |
73,370,401 | 73,370,767 | How to get int from a line of a text and add them together in c++? | Hi I have got an text file and inside writing:
15 7 152 3078
178 352 1 57
What I want to do is get the int's from first line, sum up the numbers and make it an integer. And than do it for the second line with another int. How can I do that with c++? Thanks for your help.
| You can use stringstream to convert a string into integer. And to sum a vector of integer, use accumulate algorithm. You can pass a filename as first argument to the program, by default the program assume the filename as input.txt.
Here is a complete program to demonstrate this.
#include <iostream>
#include <fstream>
#... |
73,370,550 | 73,370,645 | [[maybe_unused]] for a function | I don't quite understand when [[maybe_unused]] on a function itself could be useful.
By reading the paper, it only said the attribute may be applied to the declaration of a function. My question is that if it implies compiler will raise warning on an unused function, then for any public header of a library, everything ... | Inspired from here:
namespace {
[[maybe_unused]] void foo() {}
void bar() {}
}
int main() {}
Functions declared in the unnamed namespace can only be used in this translation unit, hence the compiler can warn when the functions are not used. And indeed gcc warns for bar (error because of -Wall -Werror) but due... |
73,370,956 | 73,372,017 | Sleek way to use template function as function argument? | What I really want to do is to compare the performance of different algorithms which solve the same task in different ways. Such algorithms, in my example called apply_10_times have sub algorithms, which shall be switchable, and also receive template arguments. They are called apply_x and apply_y in my example and get ... | As it is not clear why you need APPLY_FUNCTION and SOMETHING as separate template arguments, or why you need them as template arguments at all, I'll state the obvious solution, which maybe isn't applicable to your real case, but to the code in the question it is.
#include <iostream>
template<int SOMETHING>
inline void... |
73,371,120 | 73,372,305 | How to do action when QStringListModel changed? | Basically, I have 2 listviews and when I drag&drop one listview to another one,I want to execute a sql query.
I tried to override dropEvent but it does not getting called. However the drop action happening.(I go through the model data with for loop and I can print the items in the model)
Why the dropEvent not called w... | I solve the problem if anyone curious about this problem.
I thought I can connect QStringListModel with SIGNAL and SLOT.
connect(ui->listViewMusteri->model(),&QAbstractItemModel::dataChanged,this, &InformationMusteriDialog::listViewMusteriChanged);
connect(ui->listViewToplam->model(),&QAbstractItemModel::dataChan... |
73,371,795 | 73,372,124 | Linker error LNK2005/1169 when using smart pointer C++ | So I'm separating class definition and implementation.
Platform: Windows x64
Compiler: MSVC
IDE: VS 2022
Error "resolves" when I use inline keyword before smart pointer, but I want to understand the problem-
Error codes:
"class std::unique_ptr<class Window,struct std::default_delete<class Window> > loaderWindow" (?lo... | You include your header file in more than one source files. This is why you see this error message. Remove the definition of the global variable from your header file, or include it in one source file only.
|
73,371,835 | 73,371,898 | C++ alternatives for libjpeg? | Are there any alternatives for libjpeg? This library requires complicated installation routines, but I cannot find another jpeg library. Those I managed to find (such as CImg) require libjpeg anyway.
| The answer is yes: stb_image is a single-file, header-only image loader that supports most common JPEG files.
|
73,372,184 | 73,372,501 | C++ sockets, how to send hexadecimal with asio? | I need help, I'm trying to send this data in hexadeciamal, but always the packet_byte.size() and date() says: the express needs to have type of calsse, but has the type "char".
I dont now what i need do, if anyone can help me.and if you can indicate what to study to understand this error Thank you.
#include <iostream>
... | Your packet_bytes is a plain character array, it doesn't have data and size member function. Hence it is not possible to call packet_bytes.data() and packet_byte.size() on character array.
To create a asio::buffer from an array of characters, you need to pass the character array and its length to asio::buffer.
Please u... |
73,372,625 | 73,372,796 | Set values of a 2D array using specific coordinates | Disclaimer: This could apply to any programming langage but I am using C++, so I'm using the C++ tag.
I have an array of an xyz structure:
struct xyz {
float x, y, z;
};
In the array I create, at first I only initialize the x and y as I know the z value only later in the code like this:
size = Width * Height;
... | That is simple mathematics. If you have x and y and want to know the index to address the z-value later, then you may calculate "y * width + x".
So:
Cloud[y * Width + x].z = zValue;
|
73,372,820 | 73,374,147 | Setup/Configuring unit-testing with google test in C++ using Visual Studio 2020 | If you can't get your solution to compile, for example by receiving an unresolved externals error, take a look at the answer section and recreate the steps listed there.
| Our example header:
#pragma once
#include <string>
std::string testfunc();
Our example sourcefile:
#include "to_test.h"
std::string testfunc()
{
return "test worked";
}
After creating our example project, we wanna check some things on our list beforehand.
add google test adapter via visual studio installer... |
73,372,875 | 73,372,876 | CMake [build] stuck on one percentage throughout build yet still builds | When building with cmake no longer getting increasing percentages, just stuck at 40%. The build still works.
[build] [ 40%] ...
[build] [ 40%] ...
[build] [ 40%] ...
| This was a permissions issue. Solved by changing the build/CMakeFiles/Progress directory to have correct ownership, e.g. using chown or chmod.
Same issue spotted in 2006: https://cmake.org/pipermail/cmake/2006-October/011544.html
|
73,372,959 | 73,372,985 | Conditional constructor calling in C++ | In the following code
#include <iostream>
enum class motorid{
M1,
M2
};
enum class encoderid{
E1,
E2
};
class encoder{
public :
encoder(encoderid eid):Eid(eid){}
private:
encoderid Eid;
};
class motor{
public:
motor(motorid mid):Mid(mid){
if(mid == motorid::M1){
e(en... | Syntax would be:
motor(motorid mid):Mid(mid), e(mid == motorid::M1 ? encoderid::E1 : encoderid::E2)
{
}
For more complex case (or for readability), creating function might help:
encoderid create_encoderid(motorid mid)
{
if (mid == motorid::M1){
return encoderid::E1;
}
return encoderid::E2;
}
motor... |
73,373,388 | 73,373,465 | How to construct some classes in a vector? | I'm working on a class, and I need to have vector of the class. I would like to have objects constructed in place rather than using copy construction. It seems that use of copy construction is inevitable.
#include <iostream>
#include <string>
#include <vector>
class MyData {
public:
int age;
std::string name... | First when you write
DEBUG(sb1.emplace_back(MyData{ 32, "SJ" }));
You create a temporary object that gets passed to the emplaced_back function. The point of emplace_back is that it calls the costructor in-place. So you have to give it the arguments for creating an object, not a temporary object or it will have to use ... |
73,374,011 | 73,376,616 | Rationale for const ref binding to a different type? | I recently learned that it's possible to assign a value to a reference of a different type. Concrete example:
const std::optional<float>& ref0 = 5.0f;
const std::optional<float>& ref1 = get_float();
That's surprising to me. I would certainly expect this to work with a non-reference, but assumed that references only bi... | The basic reason is one of consistency. Since const-reference parameters are very widely used not for reference semantics but merely to avoid copying, one would expect each of
void y(X);
void z(const X&);
to accept anything, rvalue or otherwise, that can be converted to an X. Initializing a local variable has the sa... |
73,374,946 | 73,375,021 | Import headers from c++ library in swift | I am learning how to communicate between swift and c++ for ios. As a first step I have looked on this example:
https://github.com/leetal/ios-cmake
There is an example-app that I have managed to compile and run. Took some time to get it to work. That is an objective-c project.
The next step is to create a new swift proj... | You don't import anything in your Swift code when Objective-C headers are imported in the bridging header.
All public interfaces available from the imported files get available in the entire Swift module by default after that.
Sample listing
TDWObject.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@inte... |
73,375,173 | 73,375,439 | What happens if member functions of a class in a header file are implemented in two cpp files? | What happens if member functions of a class in a header file are implemented in two cpp files which are both compiled by the compiler? I mean, lets say I have this code:
//header file A.hpp
class A
{
public:
int funcA();
}
//implementation file A1.cpp
#include "A.hpp"
int A::funcA(){/* whatever*/}
//implementat... |
What happens if member functions of a class in a header file are implemented in two cpp files which are both compiled by the compiler?
It would be Undefined Behavior, as defined by the one definition rule.
Will the compiler trigger an error?
No. A compiler's job is to compile a single translation unit (a cpp file)... |
73,375,771 | 73,377,818 | Why Launch-VsDevShell.ps1 set my working directory to source\repos | Why my working directory is modified by Launch-VsDevShell.ps1 and how can we prevent this from happening?
I'm writting a script building a C++ programm and I need MSVC on Windows.
MSVC tools (cl.exe, ...) are not definded in PATH by default and you need to execute Launch-VsDevShell.ps1 to get this tools.
After executti... | You need to use -SkipAutomaticLocation
$vsWhere = "${Env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$vsInstallationPath = & $vsWhere -products * -latest -property installationPath
& "${vsInstallationPath}\Common7\Tools\Launch-VsDevShell.ps1" -Arch amd64 -SkipAutomaticLocation
Doc:
https://lea... |
73,375,776 | 73,377,939 | No Matching Function Begin Multicast - Arduino/cpp | I was given a project to convert from ESP8266 to ESP32, and I'm definitely not a coder, but it needs to get done. So I was hoping I could get some guidance/help on how to solve this issue. I'm basically taking previous code from an old project using an ESP8266 WiFi module and converting it over to a more updated module... | The Arduino UDP API as defined by the UDP base class in Arduino core has
uint8_t beginMulticast(IPAddress, uint16_t);
In esp8266 Arduino WiFi the UDP is modified and the first parameter of beginMulticast specifies the network interface to listen to. (Network interfaces are STA, SoftAP, Ethernet etc)
In esp32 Arduino ... |
73,376,371 | 73,376,949 | Cannot find the definition of a constant | I am trying to add a new accelerator to the Nvidia Triton inference server.
One of the last thing I need to do it add a new constant like this one (kOpenVINOExecutionAccelerator) but for some reason I cannot find where it is defined:
https://github.com/triton-inference-server/onnxruntime_backend/search?q=kOpenVINOExecu... | It's in the Triton Inference Server Backend here.
|
73,376,436 | 73,381,831 | std::launder reachability rules | std::launder example has this block of code:
int x2[2][10];
auto p2 = std::launder(reinterpret_cast<int(*)[10]>(&x2[0][0]));
// Undefined behavior: x2[1] would be reachable through the resulting pointer to x2[0]
// but is not reachable from the source
What? Example from std::aligned_storage makes it seem to me like t... | You wrote:
&data[pos] is just &data[pos][0], because &p == &p[0] where p is an array.
In fact, that's not true. If p is an array (call its type T[N]), the expression &p == &p[0] will not compile. The left-hand side has type T(*)[N], and the right-hand side has type T*. These cannot be compared directly, any more than... |
73,376,508 | 73,377,963 | How to interpret std::vector<unsigned char> as a double? | I have a std::vector<unsigned char> containing values representing the bytes coming from the network. I want to interpret every 8 elements as a double, similar to this but for extracting a double instead of a uint32_t:
uint32_t extractUint32From(vector<unsigned char> const& from, uint32_t startIndex)
{
uint32_t val... | The 'byte order' in which it is sent from the network is important. (Big or Little endian Endianness)
Hopefully, the example below may help you find a solution to your issue.
// CppConsoleApplication1.cpp
//
#include <stdio.h>
#include <tchar.h>
#include <stdint.h>
#include <assert.h>
#include <vector>
#define MAX_DO... |
73,376,883 | 73,377,670 | MFC: How do I change background color in MFC? | By default the color is gray, I want to change it.I use OnEraseBkgnd in my MainFarm.h,this works, it changes color,but when somewhere further in the code mfc changes it to gray again.
BOOL CMainFrame::OnEraseBkgnd(CDC* pDC)
{
CBrush backBrush(RGB(0, 0, 0));
CBrush* pPrevBrush = pDC->SelectObject(&backBrush);
... | A MDI application doesn't just have frame windows and child windows. It also has a client window. The client window handles most of managing child windows.
But it also draws the client area of the frame window. This is what's drawing the grey background after you draw your background when you handle OnEraseBkgnd in the... |
73,377,245 | 73,377,624 | How to properly wait for condition variable in C++? | In trying to create an asynchronous I/O file reader in C++ under Linux. The example I have has two buffers. The first read blocks. Then, for each time around the main loop, I asynchronously launch the IO and call process() which runs the simulated processing of the current block. When processing is done, we wait for th... | A condition varible should generally be used for
waiting until it is possible that the predicate (for example a shared variable) has changed, and
notifying waiting threads that the predicate may have changed, so that waiting threads should check the predicate again.
However, you seem to be attempting to use the state... |
73,377,738 | 73,378,433 | Can my program use unallocated memory on the free store without my knowledge? | When defining a variable without initialization on either the stack or the free store it usually has a garbage value, as assigning it to some default value e.g. 0 would just be a waste of time.
Examples:
int foo;//uninitialized foo may contain any value
int* fooptr=new int;//uninitialized *fooptr may contain any value
... | One of the things you need to understand about heap allocations is that there is always a small control block also allocated when you do a new. The values in the control block tend to inform the compiler how much space is being freed when delete is called.
When a block is deleted, the first part of the buffer is often ... |
73,377,786 | 73,377,816 | C++ concept that a type is same_as any one of several types? | I would like to define a concept that indicates a type is one of several supported types. I can do this by repeatedly listing the types with std::same_as<T, U>:
#include <concepts>
template <typename T>
concept IsMySupportedType = std::same_as<T, int32_t> || std::same_as<T, int64_t> || std::same_as<T, float> || std::... | This can be done using a variadic helper concept (taken from the cppreference for std::same_as):
template <typename T, typename... U>
concept IsAnyOf = (std::same_as<T, U> || ...);
This can be used to define the desired concept as follows:
template <typename T>
concept IsMySupportedType = IsAnyOf<T, std::int32_t, std:... |
73,378,251 | 73,378,678 | lvalue reference on rvalue reference | I have an interesting example to understand lvalue reference, rvalue reference, and std::forward. Maybe it will be a useful example for a deep understating concept.
void foo(int&& a){
cout<<"foo&&"<<endl;
}
void foo(int& a){
cout<<"foo&"<<endl;
}
template <typename T>
void wrapper(T&& a){
cout<<"wrapperTemplate... | You can't call the lvalue reference version, as t is a double and foo() expects an int. And you can't bind the temporary generated by the implict cast from double to int to an lvalue reference. The temporary is an rvalue, so can be used to call the rvalue overload.
The fact that a is an rvalue reference doesn't change ... |
73,378,933 | 73,379,061 | declare extern class c++ in hpp file and use it cpp file | I have two classes : Individu and Cite and as u can see Individu is defined before
//file.hpp
#include <iostream>
#include <stdexcept>
#include <vector>
extern Cite CITE;
class Individu {
protected:
static int id;
TYPE t;
public:
Individu();
virtual ~Individu();
static int & ... | You have two issues in your code:
extern Cite CITE is declared before the class Cite is defined, so the compiler doesn't know what a Cite is at that point. You should move this declaration after the definition of Cite.
You never define CITE. An extern variable declaration is a promise to the compiler that you will d... |
73,379,136 | 73,379,817 | Most memory efficient way to remove duplicate lines in a text file using C++ | I understand how to do this using std::string and std::unordered_set, however, each line and each element of the set takes up a lot of unnecessary, inefficient memory, resulting in an unordered_set and half the lines from the file being 5 -10 times larger than the file itself.
Is it possible (and how, if so) to somehow... | This code is reading the input file line by line, storing only hashes of the strings in memory. If the line was not seen before, it writes the result into the output file. If the line was seen before, it does not do anything.
It uses sparsepp to reduce the memory footprint.
Input data:
12 GB file size
~197.000.000 dif... |
73,379,193 | 73,379,319 | Storing type information only of a class in std::vector | I would like to store an std::string and something in an std::tuple which is inside an std::vector for creating std::unique_ptr-s in runtime but not with an if/else. I would like something like this:
class A { };
class B : public A { static const std::string name() { return "B"; } };
class C : public A { static const s... | Probably looking for std::function:
class D
{
public:
D();
void addItem(std:string name);
private:
std::vector<std::unique_ptr<A>> my_items;
std::vector<std::tuple<std::string, std::function<std::unique_ptr<A>()>>> my_vector;
};
D::D()
{
my_vector.emplace_back(std::make_tuple(B::name(), []{ return std::ma... |
73,379,625 | 73,384,453 | c++ - implementing a multivariate probability density function for a likelihood filter | I'm trying to construct a multivariate likelihood function in c++ code with the aim of comparing multiple temperature simulations for consistency with observations but taking into account autocorrelation between the time steps. I am inexperienced in c++ and so have been struggling to understand how to write the equatio... | I have found a few examples and resources to follow
https://github.com/dirkschumacher/rcppglm
https://www.youtube.com/watch?v=y8Kq0xfFF3U&t=953s
https://www.codeproject.com/Articles/25335/An-Algorithm-for-Weighted-Linear-Regression
https://www.geeksforgeeks.org/regression-analysis-and-the-best-fitting-line-using-c/
htt... |
73,379,759 | 73,380,344 | Is shared pointer thread-safety zero-cost? | I recently found out that the control block for shared pointers (the thing that manages the reference count) is thread-safe, so things like copying and passing shared pointers are safe for multithreaded uses. However, I also know that one of the ideals of C++ is that you shouldn't have to pay for features you don't use... | No, std::shared_ptr's thread-safety is not zero-cost.
The alternative, however, would be a shared_ptr that is essentially unusable in a multithreaded environment. It would be impossible for multiple threads to safely hold multiple shared_ptrs to the same object without the possibility of creating data races on the con... |
73,379,990 | 73,380,223 | How to check if a c++ typeid(T) call is compile time or runtime determined? | C++ keyword typeid has a magic: it know when to use compile-time type info and when to use runtime type info:
#include <iostream>
#include <typeinfo>
using namespace std;
struct Interface { virtual void f() = 0; };
struct S1 : Interface { void f() { cout << "S1\n"; }};
struct S3 : S1 {... | Check this out:
template<typename T>
constexpr auto my_typeId(const T& value) {
auto compileTimeChecked{ true };
const auto& typeId = typeid(compileTimeChecked = false, value);
return std::pair<
decltype(compileTimeChecked),
decltype(typeId)
>{ compileTimeChecked, typeId };
}
The first ... |
73,381,271 | 73,381,314 | Exception thrown: read access violation. this->top was nullptr | I am currently trying to develop a RPM Calculator using C++ but I am running into this error message whenever I try to run my code
Exception thrown: read access violation. this->top was nullptr.
Here is what I have in my .h file:
template<class T>
struct MyStack
{
T data; // this is going to store the number
... | Your while loop is calling s.value() on its 1st iteration when s is empty, so the s.top field is still NULL, but value() (and also pop()) tries to access top->data (and top->link) regardless of whether top is NULL or not.
You need to fix your MyStack methods to work correctly on an empty stack, ie:
In value():
if (top-... |
73,382,644 | 73,382,717 | Visual Studio 2022 intellisense includePath errors | when using the intellisense prompt of VS2022 to automatically include the header file in the code in the Cpp file, the following error always occurs
#include "../Config/UGConfigManager.h"
Is there any way to replace the path "../" with a full path? Like this:
#include "Game/Config/UGConfigManager.h"
EDIT:
In UE5, yo... | You need to add an include path to the "Game" folder.
To set an include path you now must right-click a project and go to:
Properties -> VC++ Directories -> General -> Include Directories
Then add the include directory like so:
C:/foobar/Game
First try using an absolute path. And if that works you will want to use a ... |
73,382,672 | 73,382,763 | Can't cast type int to char using function parameters C++ | Hello im trying to understand why i can't cast type int
To a char using a user defined function with parameters.
Im following along with learncpp. And i am a beginner,
So please could i have the simplified versions.
If i create a user function, And try a return the value back it will just output the integer instead of ... | The issue is the type of your return value. It should be a char. Not an int
char ascii(int y)
{
return static_cast<char>(y);
}
|
73,383,217 | 73,383,361 | How to link my project library to my pybind module? | I'm am new to pybind11 and I'm struggling with this :
I have a cpp program called my_exec.
I want to create a python-binding for it. (with pybind11)
In my exec I have 1 simple function :
int add(int i, int j)
{
return i+j;
}
And this is my pybind .cpp file :
#include <pybind11/pybind11.h>
#include "lib.h" // my ad... | The first parameter of target_link_libraries is the name of a target. You have passed the name of your project, which will only work if you happen to name a target with the same name as your project. Here, your target is named cpp, which you specified as the first argument to pybind11_add_module.
|
73,383,266 | 73,384,084 | Convert boost::multiprecision::cpp_dec_float_100 to string with precision | In my code I want to have a function which performs some calculations based on boost::multiprecision::cpp_dec_float_100 and returns string as a result with some precision, but the question is how I should set the precision ? e.g. If the precision is 9, then I expect the following results for the following numbers:
for ... | Change the line:
return val.str(9);
To:
return val.str(9, std::ios::fixed);
You will get the expected strings.
|
73,383,403 | 73,385,377 | Is there a better way to serialize NTL ZZ? | I'm currently using the NTL library to store big integers (NTL::ZZ). It looks like the only serialization way in lib is from ZZ to std::string (and std::string to ZZ for deserialization). But if I want to store and transfer a large number of integers, it becomes too slow. And the size of the transferred text is too lar... | It is easy to miss, but ZZ provides conversions to and from byte sequences:
void ZZFromBytes(ZZ& x, const unsigned char *p, long n);
ZZ ZZFromBytes(const unsigned char *p, long n);
// x = sum(p[i]*256^i, i=0..n-1).
// NOTE: in the unusual event that a char is more than 8 bits,
// only the low order 8 bits of p[... |
73,383,545 | 73,383,591 | I think this is bad C++ coding ('new' in a function to point to a local variable). Am I correct? | I want to create a class that contains a pointer, and upon initialization, the pointer can be dereferenced to give an integer assigned at initialisation.
This was my first attempt to write this code. This passed compiler and gave me the correct result without warning. However I later think this code has a potential pro... | The statements
int *ptr = new int (0);
ptr = &a;
are problematic, but probably not because of the reasons you think.
The reason it's problematic is because you define a new and distinct local variable ptr inside the function. This is not the same as the P::ptr member variable.
There's also a second problem, which is a... |
73,383,609 | 73,383,841 | gcc 12 suggesting to add the "pure" attribute | I have written a container class very similar to std::vector.
It has a size() member function, which I declared noexcept, const and constexpr.
class my_vector {
...
constexpr auto size() const noexcept -> size_type {
assert(stride_ != 0);
return nelems_/stride_;
}
};
Since I switched to GCC... | According to the gcc documentation
Even though hash takes a non-const pointer argument it must not modify the array it points to, or any other object whose value the rest of the program may depend on. However, the caller may safely change the contents of the array between successive calls to the function (doing so dis... |
73,384,755 | 73,386,224 | rust emulating variadic serialisation of PODs | In C++ I have the following template:
template<typename UBO>
std::pair<uint, std::vector<std::byte>> SerializeUniform(UBO& ubo, uint binding)
{
// Create raw binary buffers of the uniform data
std::vector<std::byte> ubo_buffer(sizeof(UBO));
memcpy(ubo_buffer.data(), (void*)&ubo, sizeof(UBO));
return {bi... | I managed to get it to work by hacking the vec! macro from the standard library
macro_rules! UBO {
() => {Vec::<UniformBufferData>::new()};
($($ubo:expr, $binding : expr),* $(,)?) =>
{
[$(serialize_uniform(&$ubo, $binding)),+].to_vec()
}
}
This lets you call the macro UBO!(dummy2, 0, dummy, 1, ... |
73,384,774 | 73,385,549 | How to selectively enable or disable -Werror argument for entire directories in my project? | I have a project in witch I would like to use -Werror, lets call its directory proj. There is a directory within proj/external and that is an exception so I don't want to use the -Werror for that.
Is there a way to create an exception for an entire directory in cmake for using or not using a compiler argument?
| CMake 2.34+ Solution
If your minimum required CMake version for the project is equal to or greater than v3.24, you can use the CMAKE_COMPILE_WARNING_AS_ERROR variable:
This variable is used to initialize the COMPILE_WARNING_AS_ERROR property on all the targets.
So just set the variable to a desired value at the top o... |
73,385,797 | 73,385,994 | Can I naively check if a/b == c/d? | I was doing leetcode when I had to do some arithmetic with rational numbers (both numerator and denominator integers).
I needed to count slopes in a list. In python
collections.Counter( [ x/y if y != 0 else "inf" for (x,y) in points ] )
did the job, and I passed all the tests with it. ((edit: they've pointed out in t... | It's not safe, and I've seen at least one LeetCode problem where you'd fail with that (maybe Max Points on a Line). Example:
a = 94911150
b = 94911151
c = 94911151
d = 94911152
print(a/b == c/d)
print(a/b)
print(c/d)
Both a/b and c/d are the same float value even though the slopes actually differ (Try it online!):
Tru... |
73,386,231 | 73,386,391 | Type trait to check if istream operator>> exists for given type | I found this type trait which can be used to check if a certain type T supports operator<<:
template<class Class>
struct has_ostream_operator_impl {
template<class V>
static auto test(V*) -> decltype(std::declval<std::ostream>() << std::declval<V>());
template<typename>
static auto test(...) -> std::fal... | Long story short, you should change
static auto test(V*) -> decltype(std::declval<V>() >> std::declval<std::istream>());
to
static auto test(V*) -> decltype(std::declval<std::istream>() >> std::declval<V&>());
There were two errors in the code, due to the following.
The >> operator takes the stream as first argument... |
73,386,336 | 73,498,193 | C++ Read values from the registry | I want to display these registry key values:
MSSQL12.MSSQLSERVER
MSSQL15.SQLEXPRESS
MSSQL11.TEW_SQLEXPRESS
Code:
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL"),
0,
KEY_READ | KEY_WOW64_64KEY,
&hKey) == ERROR_SUCCESS){
DW... | It turned out that my task needed names, not values. And only SQL Express. Here is the code:
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
L"SOFTWARE\\Microsoft\\Microsoft SQL Server\\Instance Names\\SQL",
0,
KEY_READ | KEY_WOW64_64KEY,
&hTestKey) == ERROR_SUCCESS
)
while (RegEnumValueW(h... |
73,386,584 | 73,390,267 | "transform apply" - using tuple elements as parameters to one function to construct a parameter pack for another | Given the following:
constexpr auto t = std::make_tuple(3, 2, 1);
template<auto x>
auto InnerF() {return -x;}
auto OuterF(auto... args) {return (args + ...);}
I can use the elements of t as parameters to InnerF directly:
InnerF<std::get<0>(t)>();
But I want to be able to write
std::apply([](auto... arg) { return Out... | The error is because InnerF is expecting a non-type template parameter. Those must be compile-time constants, which auto... arg are not. Using gcc 12.1, I get this more helpful error message:
<source>:10:59: error: no matching function for call to 'InnerF<arg#0>()'
10 | std::apply([](auto... arg) { return OuterF... |
73,386,720 | 73,386,823 | Is the increment (operator++) thread-safe in C++? | Is the following function thread-safe (in C++) or do I have to add a mutex?
int example() {
return g_maxValue++;
}
where int g_maxValue is some global integer. If yes, does the same hold true
for all integer types such as std::uint64_t?
| Thread safety is guaranteed only for atomic variables (std::atomic).
From C++ standard:
The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavio... |
73,386,798 | 73,387,404 | Passing template parameter pack to type_traits and std::enable_if | I am trying to create a class holding std::variant with a member function that would only accept types held by the nested variant object.
That function works basically the same way as variant's operator=. However, the question is - how do I use std::enable_if and type_traits together with template parameter pack?
The e... |
How do I use std::enable_if and type_traits together with template parameter pack?
You might do as follows:
#include <type_traits>
template<typename T, typename... Types>
inline constexpr bool areAllowedTypes = (std::is_constructible_v<T, Types> && ...);
// && -> if all the types must be convertable, otherwise use |... |
73,386,984 | 73,387,576 | How to run Python script from QT creator and print output to GUI | void MainWindow::on_pushButton_clicked()
{
QProcess p;
// get values from ini file
settings->setValue("EMail", ui->lineEditEMail->text());
settings->setValue("Password", ui->lineEditPassword->text());
settings->setValue("Chronological", ui->checkBox->isChecked());
settings->setValue("Current_info", ui->checkBox_2->is... | The widget you could use for this purpose is QTextEdit (you can set it to be read-only from the graphical user interface).
But if you want to get the output of the execution, you will need a proper instance of QProcess and call the QProcess::readAllStandardOutput() member function to get the standard output.
You may al... |
73,387,038 | 73,390,137 | cv::cuda::NvidiaOpticalFlow_2_0::create takes about 30 seconds | To use the official example script for NvidiaOpticalFlow, I built OpenCV from source following the instructions from the Nvidia Optical Flow SDK (with slightly modified build flags to enable JPEG, OPENEXR, and Eigen). The OpenCV version is 4.5.2. I can post the CMake options on request.
This line from the example scrip... | According to user @RobertCrovella in the comments, the delay may have been to do with JIT compilation. Indeed, when calling create twice in one script, the second time does not have a delay.
Whether or not that's the real reason, the root cause was that I had incorrectly specified the arch for my GPU in the OpenCV buil... |
73,387,598 | 73,387,961 | Trigonometric Equation only works with specific input ( 5 ) doesn't work with other inputs | I try to write code for that calculation angles from lengths of triangle. formula is
cos(a)=b^2+c^2-a^2/2bc. (Triangle is here)
angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153;
angle2 = acosf((powf(length1,2) + powf(length3,2) - powf(length2,2)) / 2 * length1... | You are doing:
angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153;
You should be doing:
angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / (2 * length2 * length3))* 180 / 3.14153;
Explanation: The problem is caused by the following formula,... |
73,387,765 | 73,387,897 | Why are C++ features unable to be used in extern "C" prototypes but able to be used in the implementation to link in C? | Functions in extern "C" are interpreted in C manners, e.g. no name mangling. However, why do C++ features, such as STL, std::string, smart pointer and so on, can be used in the function definition but cannot be used in the function declaration (to link with other C code)?
For example, I want to use std::vector in exter... |
Why are C++ features unable to be used in extern "C" prototypes but able to be used in the implementation to link in C?
Because the C compiler doesn't understand C++ specific code.
The implementation of the extern "C" function that uses C++ classes is compiled with a C++ compiler.
The C compiler only sees the functio... |
73,388,430 | 73,388,492 | Is there any C++ STL function to process i and i+1 elements? | Currently my code is something like this
std::vector<int> listOfItems;
// Assume the listOfItems is filled here
for(std::size_t i=0; i<listOfItems.size()-1; i++)
{
doSomething(listOfItems[i], listOfItems[i+1]);
}
I was wondering if I could avoid this code and use any STL algorithms for better readibility.
Thank you... | I have this in my utility library. Feel free to use it:
/** Iterates over each adjacent pair of the range.
*
* For the sequence [1, 2, 3, 4], it invokes fn(1, 2), fn(2, 3), fn(3, 4).
* Nothing is invoked if the sequence is only one element long.
*
* @returns The final state of fn.
*/
template <typename FwdIt, typ... |
73,388,631 | 73,396,667 | Collapse all lines to one line in VS2019? | I there any way to do the following in VS2019?
Say I have code that looks like this:
Somefunction();
SomeStatement;
SomeOtherFunction();
I want to select these lines, and quickly and easily press a button or key and have it produce this (based on semicolon):
Somefunction();SomeStatement;SomeOtherFuncti... | Use Eidt->Advanced->Join Lines:
Shift+Alt+L,Shift+Alt+J
|
73,389,666 | 73,391,341 | Is there a benefit for functions to take in a forwarding reference to a range instead of a view? | Pre-C++20, it is necessary to use forwarding references in template functions when a std::ranges::range is expected as a parameter. Since concepts are available in C++20, it is now possible to pass a std::ranges::view by value to a generic function. Per the standard, a view is a range.
Consider the following code.
#i... | There are basically several ways that you could conceive of declaring an algorithm that takes some kind of range:
constrain on range vs constrain on view
take by T&&, T const&, T&, or T
That cartesian product gives you 8 options to consider.
The problem with T const&, even for non-mutating algorithms, is that we have... |
73,390,329 | 73,390,454 | abort() is called when I try to terminate a std::thread | Note: I'm using WinForms & C++17.
So I was working on a school project. I have this function:
bool exs::ExprSimplifier::simplify()
{
bool completed = false;
std::thread thread1(&ExprSimplifier::internalSimplity, this, std::ref(completed));
while (true)
{
if (completed)
{
t... | You can't terminate threads - end of story. In the past, they tried to make it so you could terminate threads, but they realized it's impossible to do it without crashing, so now you can't. (E.g. Windows had a TerminateThread function, because it's old. C++ doesn't have it, because C++ threads are new)
The only thing y... |
73,390,528 | 73,391,786 | Alternative of boost::asio::executor_work_guard for older boost version (1.57) | I need my boost::asio::io_service object prevent from exiting when there is no more work to do. The boost.asio library version that we are using is outdated and we are not yet allowed to upgrade. The 1.57 version we are using seems not to contain the boost:asio::executor_work_guard that could prevent the io_service obj... | In older versions you'd use a io_service::work object:
boost::asio::io_service io;
boost::asio::work work(io);
Note that to get reset() like functionality you'd wrap that in boost::optional<> or std::unique_ptr<>
This is actually still in the documentation for the 1.57.0 version in the same place(s) where you'd find e... |
73,390,640 | 73,390,797 | Number of steps to reduce a number in binary representation to 1 | Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It is guaranteed that you can always reach one for all test cases.
Step 1... | This line:
pow(2, size - 1 - i)
Can face precision errors as pow takes and returns doubles.
Luckily, for powers base 2 that won't overflow unsigned long longs, we can simply use bit shift (which is equivalent to pow(2, x)).
Replace that line with:
1LL<<(size - 1 - i)
So that it should look like this:
dec += (int(s[i]... |
73,390,707 | 73,391,233 | Initializing a member with type std::shared_ptr<B> of a class A with a pointer to class B in a member function of B | I have the following code:
class Cohomology;
struct EMField
{
std::shared_ptr<Cohomology> coh;
std::array<DIM> data;
// other methods
}
class Cohomology
{
private:
// private members
public:
Cohomology(PList params)
{
// Constructor of the class
... | std::shared_ptr exists to manage the lifetime of dynamically-allocated objects. No such management is needed (or possible) for an object with automatic storage duration (like coh). Its lifetime is tied to its enclosing scope. Therefore a pointer to coh must never be managed by a std::shared_ptr.
Instead, you should ... |
73,391,012 | 73,393,514 | How to use Gtk::CssProvider with gtkmm-4.0? | I'm trying to use Gtk::CssProvider with gtkmm-4.0 but it don't work.
I would like to change background color button.
//CSS style
Glib::ustring data = "GtkButton {color: #00ffea;}";
auto provider = Gtk::CssProvider::create();
provider->load_from_data(data);
auto ctx = m_button.get_style_context();
ctx->add_p... | I add a style class to context, so later uses of the style context will make use of this new class for styling.
Now it works as i want.
//CSS style
Glib::ustring data = ".button {background-color: #00FF00;}";
auto provider = Gtk::CssProvider::create();
provider->load_from_data(data);
auto ctx = m_button.get_s... |
73,391,436 | 73,391,915 | Why is move assignment of unordered_map slow? | I am trying to understand how the move/rvalue assignment operator works. I know that it is largely implementation-specific, but assuming that move assignment in unordered_map works by only swapping the underlying data pointer or size attributes, I suppose it should be extremely fast?
This is the code that I tried to ru... | As MilesBudnek explained in his comment, I only counted the runtime for unordered_map destructor (i.e. the object c) inside my second time_it inner function.
I changed it to:
time_it([&]() mutable {
cout << "copy\n";
auto c = m;
m = c;
});
time_it([&]() mutable {
cout << "mov... |
73,391,823 | 73,391,947 | How to add a library to a project so that if the library changes, it (the lib) gets recompiled first before the program in CMake? | I'm developing a simple library and in the past I've been using Premake. Now, I want to change that and use CMake. I've been struggling with 'porting' my workflow to CMake.
I want to have 2 projects, one for the library and one for the testing program. The library should not be dependent on the testing program but the ... | Have just one project with a single CMakeLists.txt in the root, something like this
cmake_minimum_required( VERSION 3.0 )
project( MainProject )
add_subdirectory( Library )
add_subdirectory( Application )
Once you add the Library as a dependency of Application it all should work.
Example:
# in Library/CMakeLists.txt
a... |
73,391,981 | 73,392,152 | Debugging C/C++ library used by another library which in turn is used by a python executable | I have a python executable: pyExec.py. This program utilizes a C/C++ shared library: abc.so. This abc library requires another C/C++ library: xyz. Once xyz is built, it generates multiple static library files and one shared library file, which are then used to build abc. I want to investigate a function ffn which is pr... |
gdb should be very capable but you need to be aware of versions. I was recently using clang to compile and gdb to debug and hit this exact case. Ends up clang supports more debug formats. When I switched to lldb (clang's debugger) all symbols came clean. Try lldb and see what happens.
Unit tests. They help set up edg... |
73,392,097 | 73,407,528 | TOTP implementation using C++ and OpenSSL | I am trying to implement TOTP in C++ using OpenSSL. I know there are vast amounts of existing implementations; however, I would like to implement it myself.
Currently. I have the following code:
bool verifyTOTP(char* code, char* key, int codeLen, int keyLen) {
if (codeLen != 6 || keylen != 20) {
return fals... | After dividing the Unix timestamp by 30, it is necessary to ensure that intCounter is big endian:
unsigned long long endianness = 0xdeadbeef;
if ((*(const uint8_t *)&endianness) == 0xef) {
intCounter = ((intCounter & 0x00000000ffffffff) << 32) | ((intCounter & 0xffffffff00000000) >> 32);
intCounter = ((intCounter &... |
73,392,675 | 73,392,742 | Replacing std::bind with lambda with a member function to fill vector of function pointer | I have implemented function pointer list that i want to past the function and the object i want to convert the bind to a lambda function but i failed, any help?
#include <iostream>
#include <functional>
#include <vector>
using namespace std;
class Red {
public:
template <typename F, typename M>
void addToVect... |
I have tried this list.push_back([=](){ return m->f(); });
The correct syntax to call the member function using a pointer to object would be:
//----------------------------vvvvvv------->correct way to call member function using a pointer to object
list.push_back([=](){ return (m->*f)(); });
Working demo
|
73,392,986 | 73,405,156 | In Qt and cmake, how can I moc files generate with my API( dll export) macro | In my case, I have a macro for dll export like this:(very very brief version of the declaration)
#ifdef EXPORTDLL
#define MMAPI _declspec(export)
...
And my class like this:
Class MMAPI myClass: public qobject{
Q_Object()
...
Generally, mmapi is assigned as export.
And I take a linker error because of (in my opinion... | I find out what is the problem. When I define exportdll macro separately and private for each library in cmake, problem solved. My main app lib somehow see the macro.
|
73,393,207 | 73,394,526 | Using python within C code and passing list as an argument | I am using Python code within C++ code and trying to pass a list argument to a function written in Python. I tried the normal way of executing the Python code without passing any argument and it was all working fine but when I pass a list as an argument, I get a segmentation fault.
Here is my code:
#define PY_SSIZE_T_C... | The Python function get_lists is not known during execution.
Note: The test package is meant for internal use by Python only. It is documented for the benefit of the core developers of Python. Any use of this package outside of Pythonβs standard library is discouraged as code mentioned here can change or be removed wi... |
73,393,489 | 73,393,577 | How can sizeof determine size of an array, if it's length is determined on runtime? | As much as I know, sizeof can only know size of something, if the size is determined at runtime.
int a1;
cin>>a1;
int x2[a1];
cout<<sizeof(x2)/4<<"\n";
If I give input 10, sizeof says the size of the array is:40/4=10
How can sizeof know this?
|
So in C, sizeof can only know the size on compile-time and in c++ it
can know the size even if it is determined on runtime?
No, it is wrong.
C && C++ (C++ VLA is a GCC extension) Compiler will emit the constant value if sizeof is used on something whose size can be determined compiler time, or will emit some code to ... |
73,394,062 | 73,394,128 | How to call a function from a function pointer? | How can you call a function from only a pointer to the function? For example:
void print()
{
std::cout << "Hello World!" << std::endl;;
}
void run_func(void* func)
{
func(); // what im trying to do (doesnt actually work)
}
int main()
{
run_func(print);
}
Expected output:
Hello World!
It's a bit like how... | Function pointers in function parameter lists need to be wrapped in parentheses. Change the one line, either by wrapping with parentheses or using the typedef'ed function parameter, and your sample works.
// Simplifies arcane function parameter synax.
typedef void (*FUNC_TO_RUN)();
void print()
{
std::cout << "Hel... |
73,394,348 | 73,394,590 | How to overload 2 versions of operator<< in a C++ class | I am overloading operator<< as follows :
std::ostream& operator<<(std::ostream& o, const MyClass& myobj);
Now, I would like to have 2 versions of operator<<, one that would display a short description of my object, and another that would display a longer version.
For example, MyClass could contain information about a ... | The standard way is to create a custom formatting flag and a custom manipulator using std::ios_base::xalloc and std::ios_base::iword.
So you have
class MyClass {
static int fmt_flag_index;
enum fmt_flag { output_short, output_long };
}
You initialize fmt_flag_index somewhere at the program startup:
int MyClass::... |
73,394,742 | 73,394,967 | How do I get clang/gcc to vectorize looped array comparisons? | bool equal(uint8_t * b1,uint8_t * b2){
b1=(uint8_t*)__builtin_assume_aligned(b1,64);
b2=(uint8_t*)__builtin_assume_aligned(b2,64);
for(int ii = 0; ii < 64; ++ii){
if(b1[ii]!=b2[ii]){
return false;
}
}
return true;
}
Looking at the assembly, clang and gcc don't seem to ha... | "I assume" the following is most efficient
memcmp(b1, b2, any_size_you_need);
especially for huge arrays!
(For small arrays, there is not a lot to gain anyway!)
Otherwise, you would need to vectorize manually using Intel Intrinsics. (Also mentioned by chtz.) I started to look at that until i thought about memcmp.
|
73,394,820 | 73,395,478 | Constructing std::function from extern functions gives std::bad_function_call | I am experimenting with making pure Haskell-style I/O in C++. It's working correctly, but when I reorganize some definitions, I run into a std::bad_function_call.
This is about as much as it takes to trigger the problem:
//common.h
#include <functional>
#include <iostream>
#include <utility>
#include <string>
class E... | You've run afoul of the static initialization order fiasco. In your case, getLine is yet uninitialized when it's used to initialize putGet.
The cardinal rule of C++ global variables is: Global variables must not depend on global variables in other compilation units for their initialization.
While global variables in a... |
73,395,003 | 73,395,488 | A better than O(N) solution for searching a vector of sorted intervals | Given a set of sorted intervals (first >= second), sorted by the first element of the interval:
{1, 3}, {1, 2}, {2, 4}, {2, 2}, {2, 3}, {3, 5}, {3, 3}, {3, 7}
is there an efficient algorithm for determining the first interval that intersects a given
input interval? For example:
Query ({0, 0}) = returns end()
Query ({... | There cannot be a faster than linear algorithm. Consider the input where the first value of each element is 0 and the second value is random uniform over some range. Consider the query to be {x,x+1} where x is in the same range.
Since you want "the first interval that intersects a given input", the sorting is now usele... |
73,395,594 | 73,415,175 | Generic function template deduction over existing function overloads | I'm writing an extensible library where it has become convenient to overload STL's to_string() for custom types. For that I've designed a generic overload template that throws an exception if not specialized:
namespace std {
// ...
template < typename T >
inline std::string to_string(const T& in, const std::string& sep... | I recommend that you do not generate a runtime exception for something that should be a compilation failure.
It could look like this:
#include <string>
#include <type_traits>
namespace extra {
template <class T>
inline std::string to_string(const T& in) {
static_assert(std::is_arithmetic_v<T>, "T needs extra::to_s... |
73,395,658 | 73,395,889 | Xmemory Access violation reading location 0xFFFFFFFFFFFFFFFF | Whenever I run this code, I get Exception thrown at 0x00007FF6CA077375 in console test.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
coming from a file named "xmemory", what it is supposed to do is loop through different folders looking for a specified file, so it uses a bit of recursion, I'm n... | What goes wrong here is that getFile returns a bad string (uninitialized/garbage due to not returning any string) after it reaches explored.push_back(fl);. Then back in main, that string is destroyed, but that fails, so you're seeing an access violation coming out of the deep parts of the implementation of the destruct... |
73,395,826 | 73,399,150 | C++ templates as predicates for std::find_if: auto for parameters in lambdas vs free in functions vs templated functions | Please do help to understand why auto for parameter in equivalent lambda will build correctly, but if I will use free function with auto for parameters, or templated functions, it won't. It's something I forgot about template deduction? Or new changes in C++?
Example to run (builts on MSVS 2022 compiler):
import <strin... | lambda are similar to functor class, not function:
struct lamba_unique_name
{
template <typename T>
auto operator()(const T& s) const { /* ...*/ }
// ...
};
lamba_unique_name isAllowedHandlerSymbolLambda;
It is its operator which is templated, not the class,
So deduction for std::find_if_not predicate is j... |
73,395,878 | 73,399,600 | Is it advisable to inherit from std::optional? | I understand that it the most of the time not good to inherit from STL classes (except for std::exception, etc.) because for example of the lacking virtual destructor and probably other reasons.
However, I have the following code:
typedef std::optional<uint64_t> ID;
struct IDS
{
static ID create();
static void... |
Is this still a bad idea? And if yes, what can go wrong?
As you already stated, inheriting from classes without virtual destructor leads to UB when destroyed from base class.
In addition, when inheriting from 3rd party library classes, you also depends of future interface.
You might be in trouble when/if std::optiona... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.