question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,786,137 | 72,787,001 | How to compile C++ with CMake and -L/usr/include/mariadb/mysql -lmariadbclient | My C++ file includes the mariadb/mysql.h as following.
#include <mariadb/mysql.h>
I compile my C++ file as following.
g++ -std=c++2a -g main.cpp -o main -lmariadbclient
It works fine. But if I want to compile my C++ file using CMakeLists.txt. How to compile the C++ source code with -lmariadbclient using CMake?
| It looks like major distros ship with a pkg-config file for mariadb called "mysqlclient.pc".
So you can do:
find_package(FindPkgConfig REQUIRED)
pkg_check_modules(mariadb REQUIRED IMPORTED_TARGET "mysqlclient")
and then link it to your program like so:
target_link_libraries(my_program PUBLIC PkgConfig::mariadb)
|
72,786,319 | 72,786,654 | What is (void (*) (void))((uint32_t)&__STACK_END)? | This is some startup file excerpt with interrupt vectors.
#pragma DATA_SECTION(interruptVectors, ".intvects")
void (* const interruptVectors[])(void) =
{
(void (*) (void))((uint32_t)&__STACK_END),
resetISR,
nmi_ISR,
fault_ISR,
... /* More interrupt vectors */
void (* const interruptVectors[])(void) - is an a... | This looks like the interrupt vector table for an ARM processor or similar. The interrupt vector table contains the addresses of interrupt handlers, so it is essentially an array of function pointers.
The first entry of this table is the initialization value for the stack pointer. It's obviously not a function pointer,... |
72,786,965 | 72,787,744 | How can I create objects of a nested class inside the parent class but in another header file? | I have a class Dmx with a nested class touchSlider. So before I had these classes in my main.cpp file and just created an object array of touchSlider within the Dmx class and it worked properly. How can I implement this here, with different header files? The compiler gives an error message: invalid use of incomplete t... | To be able to create an array:
touchSlider slider[10] = {50,130,210,290,370,50,130,210,290,370};
You need the class definition available, because the compiler needs to know
the size of the struct or class in use and
if there's a suitable constructor available.
You now have two options, either you provide the class d... |
72,787,017 | 72,788,152 | Question about how to deal with a map of std::ostream objects into a class? | I am dealing with the following class attribute:
std::map <std::ostream*, std::string> colors;
I was wondering if there is a way to replace the pointer to ostream with a better data-structure? I read here that using a smart-pointer in this case is not a good idea and may be useless.
The map would be used only to store... | Raw pointers should not be used to manage lifetime of dynamically allocated objects. As you mention nothing that goes against that, I assume the std::ostreams are stored elsewhere while your pointers are just pointers: They point somewhere. They do not participate in ownership, and they do not need to. In particular th... |
72,787,135 | 72,787,448 | How to explicitly tell compiler to choose exactly one parameter template during template pack expansion? | I'm trying using pack parameter template to fit some cases. I want to stop the template packed parameter expanding when there is only one parameter in the list. I want to use the typename explicitly when instancing the template, rather than using the typename to declare variables.
Here is a minimal example:
template <c... | You can constrain the variadic version of the function with SFINAE to stop it from being called if the parameter pack is empty. That would look like
template <class T, class... Args, std::enable_if_t<(sizeof...(Args) > 0), bool> = true>
void f() {
f<Args...>();
}
|
72,787,319 | 72,788,123 | Why when I define the variable I defined in the for loop as global, it only writes once on the serial monitor? | as you can see below, I have defined the variable that I need to define in the for loop global, and this time the for loop only worked once, even though it was inside the void loop. Could you tell me why?
char i = 'A';
void setup() {
Serial.begin(9600);
}
void loop() {
for ( ; i <= 'Z'; i++)
Serial.pr... | Since i is a global variable, it's value persists through each call to loop().
First time loop() is called:
void loop() {
// i == 'A', it's initial value
for ( ; i <= 'Z'; i++)
Serial.print(i);
// Now, i == '[' because of i++ in the loop
delay(500);
}
Second time loop() is called:
void loop() {... |
72,787,583 | 72,787,753 | How do you initialize a vector bool matrix in C++? | I come from a mostly Java background (I use Java for algorithm challenges) , but I'm trying to practice my C++. This is my solution to a problem in which I need a vector bool matrix.
class Solution {
public:
string longestPalindrome(string s) {
string result = "";
vector<vector<boo... | You can initialize a vector matrix like this:
std::vector<std::vector<type>> vec_name{ rows, std::vector<type>(cols) };
..which in your case is:
std::vector<std::vector<bool>> dp{ s.length(), std::vector<bool>(s.length()) };
|
72,788,279 | 72,788,561 | C4594 warning in visual studio | I wrote this code so I can understand more about c++ , I know that I get this warning because of the virtual inheritance in class B and class C is not virtual public inheritance ,and I know that this warning can go if I changed it .
but what I don't understand is : why my code works and why it wont get this warning if ... | Actually protected instead of public would suffice...
Now assume your classes would not inherit virtually.
What now happens is that any instance of B incorporates its own instance of A as well as does any instance of C. Both B and C call A's constructor already, an inheriting class D doesn't need to care for.
This chan... |
72,788,311 | 72,788,966 | Beast SSL Connection Graceful Shutdown | I am implementing an HTTPS client that tries to read information from the server. During its work the shutdown can be requested. It can be expresses in the following code:
http::async_read( stream_, buffer_, res_,
beast::bind_front_handler(
&session::o... | You can ignore this error. It happens if a server sends data concurrently - started sending an application data chunk asynchronousely right before has received close notify.
stream_.async_shutdown([t = shared_from_this()] ( beast::error_code ec ) {
if (ec ...) // add proper condition here
ec = beast::error... |
72,789,515 | 72,789,581 | c++ vector pointer reference issue | so I am having some issues with creating and using pointers for vectors. The problem I'm trying to solve with these pointers, is referencing data, without having an excess amount of code. This is how I'm currently defining the variables:
// Data vectors
std::vector<int16_t> amountData;
std::vector<float> speedData;
st... | You want pointerr->size() (without a *); the -> operator does the dereference of pointerr for you.
Or alternatively, (*pointerr).size() which is equivalent. Your attempt of *pointerr.size() was close, but the . operator has higher precedence than *, and you have to derefence the pointer before you can apply . to the o... |
72,789,833 | 72,789,869 | __stdcall in function paramater | does anybody know if is possible to add __stdcall (CALLBACK) in function parameter like this?:
void Function(LRESULT CALLBACK (*f)(HWND, UINT, WPARAM, LPARAM));
It gives me following error:
a calling convention may not be followed by a nested declarator
Any solutions?
Thx in advance <3
| Put the calling convention inside the parenthesis.
void Function(LRESULT (CALLBACK *f)(HWND, UINT, WPARAM, LPARAM));
|
72,790,232 | 73,557,091 | PyArg_Parse for multiple returns of python on c++ | I am calling python from c++ using PyObject_CallObject
as the python return only a floating point number, i can get it by:
float output_of_python;
PyObject *pValue,*pArgs;
pValue = PyObject_CallObject(pFunc, pArgs);
PyArg_Parse(pValue, "f", &output_of_python);
however, if python's returns 2 (return first,second)... | i found it, post it here for anyone needs:
In c++, in order to get 2 variables from return of python, it is
float va1,va2;
PyArg_ParseTuple(pValue, "ff", &va1,&va2);
|
72,790,741 | 72,790,802 | Is there a better way to write these If-Statements? | I'm building a Random Character Generator in C++, and I have around 12 large blocks of if statements, like this:
int wisdom = rand() % 18;
cout << "\n";
if (wisdom == 0 || wisdom == 1) {
cout << "Wisdom Score: 1\n";
cout << "Modifier: -5\n";
} else if (wisdom == 2 || wisdom == 3) {
cout << "Wisdom Scor... | The better way is to not write chained ifs at all, but instead compute the value you care about.
if (wisdom == 0) wisdom = 1; // Handle edge case treating 0 as 1
int modifier = wisdom / 2 - 5;
cout << "Wisdom Score: " << wisdom << '\n';
cout << "Modifier: " << modifier << '\n';
Note that your calculation of int wisdo... |
72,790,846 | 72,810,001 | How do I efficiently select ports in multi process C++ linux servers? | I am using Amazon Gamelift to manage a c++ game server in an Amazon Linux 2 environment. This service will launch multiple instances of the same game server on the same machine at nearly the same time. These processes then report back when they are ready and what port they are bound to. What is the best way to attempt ... | So I kind of hate that the only answer now is seemingly trying random ports within the unblocked range and retrying on collision, but that is all I seem to have to go on, so I implemented it. Here is the code if its helpful to anyone:
bool MultiplayerServer::tryToBindPort(int port, int triesLeft)
{
ServerPort = por... |
72,791,682 | 72,791,901 | How to set pack of type by number? | I need some thing like this
template<unsigned N>
class Class
{
std::function<double(double, double ...)> _function1; // double N times
std::function<double(double, ...)> _function2; // double N - 1 times
}
| Something along these lines, perhaps:
template <typename R, typename T, size_t N>
struct MakeFunctionType {
template <size_t>
using SwallowIndex = T;
template <size_t... Is>
static std::function<R(SwallowIndex<Is>...)>
MakeFunctionTypeHelper(std::index_sequence<Is...>);
using type = decltype(MakeFunct... |
72,791,713 | 72,792,127 | Issues with infinite grid in OpenGL 4.5 with GLSL | I've been toying around with an infinite grid using shaders in OpenGL 4.5, following this tutorial here. Since the tutorial was written for Vulkan and a higher version of GLSL (I'm using 450 core), I had to move the vertices out of the vertex shader and into the application code. I'm rendering the quad using an element... | Blending only works when the Depth Test is disabled or the objects are drawn from back to front. When the depth test is enabled (with its default function GL_LESS) closer objects win against more distant objects. Even if a fragment's alpha channel is 0, the fragment affects the depth buffer and the depth test. Thus, a ... |
72,792,218 | 72,792,246 | Why does main(int argc, char** argv) allow to override 'argv' parameters? Why and how does this work? | I found that main() allows overriding the argv[] parameters, because they are not const.
#include <cstdio>
int main(int argc, char** argv)
{
printf("%i %s\n", argc, argv[1]);
argv[1][0] = 'X';
argv[1][4] = 'X';
printf("%i %s\n", argc, argv[1]);
return 0;
}
And below is the result. It compiled and ... | On Linux/x86-64, the argc, argv, and env parameters are stored on the call stack by the kernel doing the execve(2) according to ABI conventions.
See also this and the Linux Assembly HOWTO.
|
72,792,332 | 72,828,983 | Check if Eigen Decomposition has been computed | How can I check to see if compute has previously been run on an Eigen::Solver? There is a protected member variable m_isInitialized in Eigen/src/EigenValues/EigenSolver.h but I don't see a getter for it.
The code below shows an example of how you would create a matrix and compute the eigen decomposition on it. In my c... | Just for completeness, assuming you don't want to wait for a feature request for Eigen, the easiest wokaround is std::optional
std::optional<Eigen::Solver<double, 3, 3>> eigen_decomp;
if(! eigen_decomp)
eigen_decom.emplace(matrix, /* computeEigenvectors = */ true);
std::cout << eigen_decomp->eigenValues() << "\n";
... |
72,792,423 | 72,792,940 | How do you parse or save data from or to json files with c++? | I'm currently trying to gain some experience in coding with c++. I've already done some projects in other languages such as c# and other but I quickly realized that stuff is done quite different and that I got a lot to learn before I can start programming some more advanced projects.
However, I'm quite experienced in r... | The reason you perceive other languages "simpler" to work with JSON is because those languages have built in class libraries to deal with JSON or they provide a near seamless dependency management framework that lets you very easily choose a 3rd party class library for the task.
The C++ standard makes very little assum... |
72,792,490 | 72,792,600 | c++ Thread handling in class | I would like to create a object in which I can start a thread and have a function to join withe the created thread. Everything insight the object, so that the thread is a private component of the object.
I have tried a bit and got those Results. Could some of you explain me what I have done wrong, and why I get this er... | std::thread A::startThread()
{
std::thread a((*threadFunction));
return a;
}
Does not interact with the member variable a, but it creates a new local variable std::thread object and then moves it to the result (unless the move is optimized out). The thread A::a always remains the default constructed one. A def... |
72,792,573 | 72,792,638 | How do I cast the result of GetProcAddress to a function pointer without -fpermissive on mingw? | When I use -fpermissive I can just write something like this:
void (*NtSetTimerResolution)(ULONG, bool, PULONG) = 0;
int main()
{
NtSetTimerResolution = GetProcAddress(GetModuleHandle("ntdll.dll"), "NtSetTimerResolution");
ULONG pointless;
NtSetTimerResolution(0x1388, 1, &pointless);
return 0;
}
and i... | You need an explicit cast:
NtSetTimerResolution = reinterpret_cast <void (*)(ULONG, bool, PULONG)> (GetProcAddress(GetModuleHandle("ntdll.dll"), "NtSetTimerResolution"));
You might still be violating strict aliasing rules here, but you can use -fno-strict-aliasing to get round that.
And, inspired by @Remy's comment, ... |
72,793,403 | 72,794,857 | Compiler Error C2440 IMAGE_NT_HEADERS64 cant be used to initialize an entity of type IMAGE_NT_HEADERS | So im writing a .dll for an injection, i ran into this problem and i have no clue abt how to fix tiError C2440 'initializing': cannot convert from 'const IMAGE_NT_HEADERS64 *' to 'const IMAGE_NT_HEADERS *' mod C:\Users\user\source\repos\mod\mod\Pattern.cpp 21
the code im using here:
const IMAGE_NT_HEADERS* ntHea... | You are trying to assign a const IMAGE_NT_HEADERS64* to a const IMAGE_NT_HEADERS*. They are not the same type.
Either cast the adjusted pointer to const IMAGE_NT_HEADERS*, or declare ntHeader as const IMAGE_NT_HEADERS64*.
|
72,793,413 | 72,797,252 | Create custom Hash Function | I tried to implement an unordered map for a Class called Pair, that stores an integer and a bitset. Then I found out, that there isn't a hashfunction for this Class.
Now I wanted to create my own hashfunction. But instead of using the XOR function or comparable functions, I wanted to have a hashfunction like the follow... | To expand on a comment, as requested:
Converting to string and then hashing that string would be somewhat slow. At least slower than it needs to be. A faster approach would be to combine the bit patterns, e.g. like this:
struct Pair
{
std::bitset<6> bits;
int intval;
};
template<>
std::hash<Pair>
{
std::size_t o... |
72,793,495 | 72,793,567 | How can I conditionally instantiate a member object to exhibit different behaviors depending on parent object? | I'm creating two objects of struct Player, each with a pawn container. I want this member to be defined with a different type depending on the Player object it is in, such that white.pawn.say() and black.pawn.say exhibit different behaviors. I've tried making WhitePawn and BlackPawn classes respectively, but I don't kn... | In your case, you're sure that there are only a given number of possible classes to choose from. This is called discriminated union in type systems and can be represented using a variant:
Example code:
struct Player {
using PawnType = std::variant<Pawn<0>, Pawn<1>>;
PawnType pawn;
Knight knight;
Bishop ... |
72,794,541 | 72,794,571 | C++: copying a struct containing a std::vector efficiently | struct MZEntry
{
uint32_t machineID;
bool mode;
uint32_t area;
uint32_t occupancy;
using ZList = std::vector<uint32_t>;
ZList authorisationZ;
ZList blockExceptionZ;
void clear()
{
machineID = 0;
mode = false;
area = 0;
occupancy = 0;
... | Declaring a copy constructor is a bad idea. Follow the rule-of-zero whenever you can and don't declare any copy/move constructor or assignment operator or destructor if you don't need custom destructor behavior because the class must manage some resource (and if it has to, always encapsulate that in a class specificall... |
72,794,542 | 72,799,450 | C++ Vulkan swapchain image_index vs current_frame | I am new to vulkan and following the vulkan-tutorial. In the chapter about swapchain and multiple frames in flight (frames_in_flight) there is something I dont understand.
The variable imageIndex gets set by the function vkAcquireNextImageKHR
uint32_t imageIndex;
vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, ima... | The difference is:
vkAcquireNextImageKHR::imageIndex is "random". It can return any number in any order.
The currentFrame changes strictly in round-robin fashion. Additionally the max-count may differ from swapchain image count.
You would use vkAcquireNextImageKHR::imageIndex for things tied to a specific swapchain ima... |
72,794,831 | 72,795,029 | Why std::vector<T>.resize() requires T has default ctor(with no parameter)? | I've got test code snippet:
#include<vector>
using namespace std;
struct My {
My(int i) {}
My(My&&) noexcept {}
My(const My&) {}
};
int main() {
vector<My> vm;
vm.emplace_back(My(3));
vm.resize(3); // compile error
return 0;
}
g++ compile with error:
In file included from /usr/include/c++/... | The rule doesn't break your class semantics -- it actually enforces them. When you resize a vector, any new elements added are default-constructed. Since that is not allowed, then you may not resize a vector this way.
Instead, you can use another overload of resize that accepts a value to initialize new elements with. ... |
72,795,189 | 72,795,239 | How can I wrap std::format() with my own template function? | Note: this question uses C++20, and I'm using Visual Studio 2022 (v17.2.2).
I would like to create a template function wrapper to allow me to use std::format style logging. The wrapper function will eventually do some other non-format related stuff that is not important here.
Refer to the code below. Note that Log1(... | You need P2508 (my paper) to land, which exposes the currently exposition-only type std::basic-format-string<charT, Args...>, which will allow you to write:
template<typename... Args>
auto Log3(std::format_string<Args...> fmt, Args&&... args)
Until then, you can just be naughty and use the MSVC implementation's inter... |
72,795,259 | 72,818,340 | Why is there a loop in this division as multiplication code? | I got the js code below from an archive of hackers delight (view the source)
The code takes in a value (such as 7) and spits out a magic number to multiply with. Then you bitshift to get the results. I don't remember assembly or any math so I'm sure I'm wrong but I can't find the reason why I'm wrong
From my understand... | In the C CODE:
auto magic = (1ULL<<32)/test_divisor;
We get Integer Value in magic because both (1ULL<<32) & test_divisor are Integers.
The Algorithms requires incrementing magic on certain conditions, which is the next conditional statement.
Now, multiplication also gives Integers:
auto answer1 = (a*magic) >> 32;
auto... |
72,795,407 | 72,866,581 | How to keep track with std::forward_list 's first element? | I want to save an iterator of the first elements in a forward list as it and do some insert on the list. Then I want to erase the element at it.
For example, in {20,30,40,50} and insert 10 at front. We get {10,20,30,40,50}. Then I want to erase 20, which means I want {10,30,40,50}.
I tried to use before_begin() but it ... | I solve this problem by adding an count, counting the number inserted at front and then move iterators from begin().
|
72,795,620 | 72,797,453 | Why max() function in C++ giving error "no matching function for call to max"? Same code works if I do it explicitly with conditional statement | Both parameters of max are of type int, then why am I getting this error?
Code is to find maximum depth of paranthesis in a string
int maxDepth(string s) {
stack<char> stac;
int maxDepth = 0;
for(auto &elem: s) {
if(elem == '(')
stac.push(elem);
else if... | The reason why your compiler reject your call to std::max function is because it cannot deduce the type it need.
Below is typical implementation of std::max
template<typename _Tp>
_GLIBCXX14_CONSTEXPR
inline const _Tp&
max(const _Tp& __a, const _Tp& __b)
{
// concept requirements
__glibcxx_... |
72,795,680 | 72,933,243 | C++ Child Class Change Parent Class's Constructor | Modified the question a bit, thanks for your help on this!
Is there a way to change Parent's constructor(e.g. change the value of protected field) when initialize the Child class.
For example, I have two class - Base and Child below. In the Base constructor, string 'a' will be assigned to a protected field - 'a_' and '... | Thanks for all the reply. After reconsideration, I decided to extract a base class(class 'RealBase') from Base class and Child class. I feel the Child class should always obey the rules defined in parent class(e.g. same attributes, same method, etc.), otherwise, it's better to extract an abstract base class that contai... |
72,795,690 | 72,802,189 | CGAL: How to get segmentation within polyline like CGAL Demo does? | I have a surface mesh with some sharp features. I want segment the mesh within the polyline composed of these features. In CGAL Demo, "Detect Sharp Features" function can fulfill my requirement, as the pic shows. Right now, I can get the polyline with domain.detect_features() which calls add_features_from_split_graph_i... | The function sharp_edges_segmentation() should do something similar.
|
72,795,727 | 72,797,139 | Boost ASIO SSL handshake failure | When attempting to securely connect to a remote IMAP server using Boost ASIO, the server handshake fails on every connection. The exception message reads:
handshake: unregistered scheme (STORE routines) [asio.ssl:369098857]
My code is below (url is a std::string_view containing the host URL):
using boost::asio::ip::tc... | Given that openssl s_client -connect my.url.com:993 -crlf -verify 1 succeeds there is not a lot that seems wrong. One thing catches my eye: I'd configure the context before constructing an SSL stream from it:
ssl::context ssl_context(ssl::context::tls);
ssl_context.set_default_verify_paths();
SSLSocket socket(context... |
72,796,200 | 72,796,271 | Not able to construct List Iterator from list.begin() | I am solving this problem https://leetcode.com/problems/queue-reconstruction-by-height/
This is the code that I wrote
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
list<vector<int>> dyn;
sort(people.begin(), people.end(), [](vector<int> a, vector<int> b) {
if (a[0] > b[0... | std::list.begin() produces a BidirectionalIterator.
As per the documentation at https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator, this type of iterator does not support the `+' operator.
The only permissable operators are:
++: Move to next iterator location.
--: Move to previous iterator location
*--:... |
72,796,284 | 72,796,361 | 'Type' does not refer to a value | I've checked other questions with similar errors, and they didn't seem comparable to the issue that I'm running into. I'm trying to instantiate an object and assign it in a constructor initialization list.
However, on line 11, I'm getting an error saying 'Enemy' does not refer to a value.
Furthermore, also on line 11, ... | Not sure why you are trying to name this object, just
Room::Room()
: Room{Enemy{"Goblin"}}{
}
Temporaries (like Enemy{"Goblin"}) are objects without names.
|
72,796,784 | 72,796,923 | cannot declare pointer to node& in c++ | #include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
vector<node*> children;
};
node* createTree(const vector<int>& nums){
stack<node*> st;
node *root = new node(nums[0]);
st.push(root);
for(int i=1;i<nums.size();i++){
if(nums[i]==-1){
st.pop();
... | You're correct about the pointer to a reference vs reference to a pointer but got the syntax wrong.
Pointer to a reference is declared as: type&* obj
Reference to a pointer is declared as: type*& obj
Thus, the way that you think is "wrong", turns out to be correct:
void display(node*& root)
Edit: It's easier to imagi... |
72,797,938 | 72,798,027 | Creating an array of Semaphores C++ | I am trying to create an array of semaphores, however my code is not running correctly so I am hoping to get some feedback on whether I am doing this correct.
Creating the semaphore array as a global variable, I have:
sem_t sems [10] = {};
Then filling the array (in main):
sem_t sem0;
sems[0] = sem0;
sem_t sem1;
sems[... | I don't know what you expect the middle part of your process to do. The additional variables you are declaring are independent semaphores from those in the array. Assignment will only copy the sem_t value (which is going to technically cause undefined behavior because you didn't initialize them).
You can just pass a po... |
72,798,527 | 72,798,714 | A template function as a template argument | How to make the pseudo code below compile?
#include <vector>
template <class T>
void CopyVector() { std::vector<T> v; /*...*/}
template <class T>
void CopyVectorAsync() { std::vector<T> v; /*...*/}
template <template <class> void copy()>
void Test()
{
copy<char>();
copy<short>();
copy<int>();
}
int main... | You can't have a template template parameter that accepts function templates, only class templates. Luckily we can make a class that looks rather like a function.
#include <vector>
template <class T>
struct CopyVector { void operator()() { std::vector<T> v; /*...*/} };
template <class T>
struct CopyVectorAsync{ void ... |
72,798,545 | 72,798,866 | std::unique_ptr custom deleter that takes two arguments | I am working on legacy code where memory allocation/deallocation done in traditional C style, but want to wrap it in a unique_ptr with a custom deleter. Consider a case where a 2 dimensional array is allocated by legacy code by calling calloc/malloc. I need to call the corresponding legacy deallocator function taking t... | The deleter is an object. It can hold onto the size.
struct LegacyDeleter
{
int size;
void operator()(char** ptr) const noexcept
{ legacyDeallocate(ptr, size); }
};
using legacy_ptr = std::unique_ptr<char*, LegacyDeleter>;
int main()
{
legacy_ptr ptr(legacyAllocatorFunction(5), LegacyDeleter{5});
}
|
72,800,031 | 72,811,554 | Serialise / deserialise std::optional with nlohmann-json | I wish to serialise a std::optional<float> with nlohmann-json.
The example given here in the docs for a boost::optional seems very close to what I want, but I don't understand where my adaptation of it is going wrong.
It seems that the deserialization component is working for me, but not the to_json aspect.
Here is a m... | This amounted to a dumb-one that's hard to spot because you're too worried its something esoteric. It's probabally quite specific to my mistake and wont likely be too much use to anyone finding this in the future though.
Nonetheless, answer is as follows.
My MWE about is a simplification of something in a real codebase... |
72,800,340 | 72,802,989 | Can anyone give me code example of how multiple outputs of a single fragment shader is recorded and how to read them seperately(VULKAN) | Take the fragment shader as example:
#version 450
//#extension GL_ARB_seperate_shader_objects : enable
layout(location = 0) in vec3 color1;
layout(location = 0) out vec4 outColor;
layout(location = 1) out float outID;
void main() {
outColor = vec4(color1, 1.0);
outID = 0.7;
}
Now can anyone tell me how... | Output at location 0 goes to color attachment 0.
Output at location 1 goes to color attachment 1.
Teh spec (Fragment Output Interface):
A fragment shader output variable identified with a Location decoration of i is associated with the color attachment indicated by pColorAttachments[i].
VkSubpassDescription:
Each el... |
72,800,478 | 72,812,353 | Change for loop increment/decrement value | Consider this code:
# include <iostream>
using namespace std;
int main()
{
for(int i = 5; i>0;)
{
i--;
cout <<i<<" ";
}
return 0;
}
The output of this code would be 4 3 2 1 0.
Can I change the decrement/increment value?
In detail, this means that the default decrement/increment value i... | d-- is shorthand for d -= 1, which is shorthand for d = d - 1.
You should not read this as a mathematical equation, but as "calculate d - 1 and assign the result as the new value of d".
#include <iostream>
int main()
{
float day = 1.2;
for(int i = 0; i < 5; i++)
{
day -= 0.2;
std::cout << d... |
72,801,432 | 72,807,679 | Why do I get the "child has a base whose type uses the anonymous namespace" warning here | I am trying to understand why I get a warning -Wsubobject-linkage when trying to compile this code:
base.hh
#pragma once
#include <iostream>
template<char const *s>
class Base
{
public:
void print()
{
std::cout << s << std::endl;
}
};
child.hh
#pragma once
#include "base.hh"
constexpr char const hello[] ... | The warning is appropriate, just worded a bit unclear.
hello is declared constexpr, as well as redundantly const. A const variable generally has internal linkage (with some exceptions like variable templates, inline variables, etc.).
Therefore hello in the template argument to Base<hello> is a pointer to an internal li... |
72,802,168 | 72,823,464 | Correctly abstracting the model from the view in an MVC Design Pattern | Context
I am developing a simple CandyCrush lookalike game in C++ to familiarise myself more with Object Oriented Programming and Design Patterns, namely MVC.
The general structure of the Model is as such :
Idea
My idea is to use a packaging logic, such that each GameComponent can be packaged into a primitive type rep... | Yes I think you may be overthinking things! Adhering to MVC in the most generic sense just means that your data and logic (the model) are independent of the user interface code, which has the view and controller components. Additionally, you could think of individual objects as models, to be rendered in individual view... |
72,802,341 | 72,802,585 | OpenCV for C++: Passing matrix using std::ref() gives a 0x0 dimension matrix | this is my code snippet:
for(int i = 0; i < numT; i++) {
cv::Mat m2 = m1(cv::Range(get<0>(offsets[i]), get<1>(offsets[i])), cv::Range::all());
cout << m2.rows << " " << m2.cols << endl;
// start threads
threadsVec.push_back( thread(myFunction, ref(m2)));
}
I want to apply myFunction to subparts... | m2 is destroyed at the end of your loop. Keeping a reference on it is undefined behavior.
Just pass m2 by value instead. cv::Mat already behaves like a shared_ptr: copying a cv::Mat (and sub-matrices count as copies) won't deep-copy its internal buffer. So there's no need to use a reference on top of that.
Just in cas... |
72,802,415 | 72,802,534 | Define a template function according to class member variable with typetraits | I'm having some difficulties understanding a piece of code that is using typetraits.
Suppose I want to define a template function that works on some classes that has a member variable k of type uint32_t. (Other classes will have another template function).
The piece of code I have found is the following:
template <type... |
(Why) do we need the std::uint32_t as input argument of has_member_k? I guess it relates to the type of k but I am not sure how.
Its a trick to be able to call either has_member_k(std::uint32_t) or has_member_k(...) (in case enable_if discards the first). When SFINAE does not kick in then both templates could be used... |
72,802,456 | 72,808,646 | Store iterator inside a struct | I need to read data from multiple JSON files. The actual reading of data is performed later in the code, after some initialization stuffs. For reasons beyond the scope of this question, I believe that it would beneficial for my application to store somewhere an iterator set to the first element of each JSON file. In t... | You're storing iterators, but using them after they were invalidated.
Reasons for invalidation are when the corresponding ptree node moved, was erased or destructed.
Just store the ptree inside the struct, which makes sure the ptree's lifetime extends long enough. Of course, you will still need to make sure the node po... |
72,802,894 | 72,804,926 | Nested concept types in templates | Consider the following template, intended on declaring some State::Machine:
enum Strategy {
Breadth,
Depth,
Heuristic,
};
template<class Map, Strategy Strategy = Depth>
struct Machine;
If we would like to enforce some constraints on the Map type, so that implementations satisfy necessary concepts, we have:
t... | Most types expose their "subtypes".
std::map has key_type and mapped_type for example.
(You can create traits to extract template parameter if needed BTW, if type doesn't provide such typedef).
Then you might use constraint on those sub-types, something like:
template <typename Map, Strategy Strategy = Strategy::Depth>... |
72,802,995 | 72,803,864 | What does it means this error?" In template: call to deleted constructor of 'std::unique_ptr<InventoryElements>" | this is the class with all the methods.
#include "InventoryElements.h"
class Inventory{
public:
explicit Inventory(int max) : MaxElements(max){
myInventory.resize(max);
NumElements=0;
}
void suf_insert(unique_ptr<InventoryElements> element);
void generic_insert(unique_ptr<InventoryEleme... | Because a std::unique_ptr can not be copied, you will need to move your unique_ptr into your vector.
myInventory.push_back( std::move(element) ); // no more error
After this line, element will no longer point to your element, as your std::vector will now contain the unique pointer.
|
72,803,180 | 72,804,299 | Angles of a Point with X, Y, Z using GLM | I have two points, one represents the cursor(a cube) and another one represents the position of the Camera.
Now to find out which face the camera is facing I have done something like this
glm::vec3 direction = glm::normalize(cursorPos - cameraPos);
float angle_x, angle_y, angle_z;
angle_x = glm::dot(direc... | You made this code hard to understand and maintain. Here is method which do not need large mind power.
Just 6 vectors defining directions and trying find one which is closest to direction:
Facing findOrientation(glm::vec3 direction)
{
struct FacingNormalizations {
Facing facing;
glm::vec3 v;
};
... |
72,804,066 | 72,804,429 | Problems with Makefile and compiling a cpp file marks error in a function declared in other file | I have problems with my Makefile.
I used the following structure to generate the .o files of each cpp file, but does not work (using c works without problems, I cant find what is the problem)
%.o : %.cpp %.h
g++ -c -Wall $< -o $@
And the error while compiling is a function is declared in a separated h and cpp file... | You got the header guard in the wrong order.
Instead of:
#define NUMB_H
#ifndef NUMB_H
It is supposed to be:
#ifndef NUMB_H
#define NUMB_H
|
72,804,375 | 72,804,752 | Cross-platform binary in C++ | I have read that a binary is the same for Windows and Linux (I am not sure if it has a different format).
What are the differences between binaries for Linux and binaries for Windows (when speaking about format)?
And if there are none, what stops us from making a single binary for both operating systems (make sure that... |
I have read that a binary is the same for Windows and Linux (not sure if it has a different format)
Then you have read wrong. They are completely different formats.
What are the differences between binaries for Linux and binaries for Windows (when speaking about format)?
Windows: Portable Executable (PE)
Linux: Ex... |
72,804,408 | 72,804,483 | How check instantiation of one type by another with templates? | In my case there is func:
// msg can be std::string, std::wstring, const char*, const wchar_t*, ...
template<typename StrType>
void Log(StrType msg) {
if std::string(msg) can be created from msg {
// do smth
}
if std::wstring(msg) can be created from msg {
// do smth
}
else {
// wrong argument
... | Since C++17, you may use a constexpr if to check whether std::string or std::wstring can be constructed from the argument you pass to Log:
template <typename StrType>
void Log(StrType msg) {
if constexpr (std::is_constructible_v<std::string, StrType>) {
// do smth
} else if (std::is_constructible_v<std:... |
72,805,295 | 72,805,586 | Why does my python function run faster than the one in c++? | I have been writing a simple test to compare the speed improvements of c++ over python. My results were unexpected with c++ being almost trice as slow as the program written in python. I guess there is something in the loop inside the python function using iterators or something.
C++ code
#include <ctime>
#include <chr... | There are many reasons why this performance test does not give useful results.
Don't compare, or pay attention to, release timing. The entire point of using a language like C or C++ is to enable (static) compiler optimizations. So really, the results are the same. On the other hand, it is important to make sure that a... |
72,805,585 | 72,805,672 | Why doesn't the .exe file generated by Visual Studio Code show program output? | enter image description hereThe program outputs the number of the leftmost column with only positive numbers. Everything works fine in the Visual Studio Code terminal.
I think double-clicking on the automatically generated .exe file in a separate window should launch a full-fledged program that reads the input, process... | If you are using Microsoft Windows, then the console window will disappear as soon as your program ends. If you don't want this to happen, then you can
run your program from the Windows command prompt cmd.exe instead of double-clicking it, or
add something to the end of your program that prevents it from closing immed... |
72,805,813 | 72,886,872 | Get the smallest Euler angle from a rotation matrix | I have a 3D rotation matrix with small XYZ angles. Angles are between -20° < angle < 20°.
Rotation matrix is constructed with :
I want to get angles back from the rotation matrix, but several angles are possible.
How to recover the smallest angles allowing to build this rotation matrix in C++?
For the moment I use Eig... | I have found how to do for angles between pi/2 and -pi/2 (so work with small angles).
For a rotation ordering of xyz, you can do:
//mat is the 3*3 rotation matrix
double rx = atan2(-mat(1, 2), mat(2, 2));
double ry = asin(mat(0, 2));
double rz = atan2(-mat(0, 1), mat(0, 0));
Found more info on https://www.geometrictoo... |
72,806,079 | 72,806,134 | Getting random numbers on vector operation c++ | I'm getting weird numbers as output in this code :
#include <iostream>
#include <vector>
int main(){
std::vector<std::vector<int>> vec = {{0,1},{2,3}};
vec.push_back({4,5});
vec.push_back({5,6});
for (int i = 0; i < vec.size(); i++){
for (int i2 = 0; i2 < vec.size(); i2++){
... | The output you are seeing is due to undefined behavior in your code.
The outer vector object has 4 inner vector<int> objects added to it. Each of those inner vector<int> objects is holding 2 int values.
Your inner for loop is going out of bounds of the inner vector<int> objects, by trying to access 4 int values when th... |
72,807,283 | 72,807,412 | constexpr_assert on embedded (--fno-exceptions) | Is it possible to implement a thing such as "constexpr assert" on bare metal?
I would normally use a throw statement as it is mentioned here for example. But the compiler rejects the code because of --fno-exceptions even though throw is used only in a constant evaluated context.
My implementation:
inline constexpr void... | Since you know you're being constant evaluated, all you need to trigger a failure is to do something that's not valid to do during constant evaluation.
The easiest of these is to invoke a non-constexpr function:
void on_error(char const* msg) {
// some code here... or not
}
Which you can then:
if (std::is_constant_... |
72,807,349 | 72,840,893 | ImGui has no member RenderPlatformWindowsDefault error | When i try to build my old code i dont remember what version is imgui but i'm getting this error. i searched whole internet but i can't find nothing.
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
ImGui::UpdatePlatformWindows(... | That code uses the docking branch of imgui, and you're probably using the master branch.
You could either switch to the docking branch, or remove those lines of code if you don't need it.
|
72,807,569 | 72,807,851 | set default value of unordered map if key doesn't exist | In my program I want that the default value, if a key doesn't exist in my unordered map, is going to be std::numeric_limits<double>::max() Instead of just 0.
my code looks like the following:
class Pair
{
public:
Graph::NodeId node;
bitset<64> bits;
Pair(Graph::NodeId node1, double bits1)
{
node = n... | One possibility would be to create a tiny class for the value type:
class dproxy {
double value_;
public:
dproxy(double value = std::numeric_limits<double>::max())
: value_{value} {}
operator double &() { return value_; }
operator double const &() const { return value_; }
};
std::unordered_map<Pair... |
72,807,801 | 72,808,782 | How to check if ball colides with edge of window in c++ with raylib | i am new to raylib and wanted to make a little 2d ball thing, and i don't know how to stop the sprite from going of the screen, it only works with 2 edges and not the others, would anybody please help?
My C++ file:
game.cpp:
#include <raylib.h>
int main() {
InitWindow(800, 600, "My Game!");
// Vector2 ballPo... | Took me a while but your problem is a combination of the offset for drawing the ball texture and how you check for the bounds of the screen (assuming the image is a 50x50, you didn't specify).
Notice I've locally added a circle directly at the ballposition (right after the DrawTextureCall):
DrawCircleV(ballPosition, 2... |
72,808,881 | 72,809,029 | C++ How to map string keys to class method invocations for a specific object? | In C++, I am trying to map a user-provided string to a class method invocation for a specific object. I was successful in mapping user-provided strings to function calls for another application, but I do not know how to extend this approach to work for class methods being invoked for a particular object. I would greatl... | Since all of the methods belong to the same class, and have the same signature, you can use Pointers to member functions, using the member access operator.* to call them (no std::function needed), eg:
void read_input(std::string& input_filename, Class_Name& my_object)
{
// Map string keys to object member invocation
... |
72,809,713 | 72,809,967 | C++ output printed twice and error exit code: -1 | I am learning and practicing with C++. I an error when I tried to run the program. I tried different things like changing the sign (<=,>=,<,>) but I don't think they are the problem. I was planning to create different classes for each range of bonus salary but I don't think it is needed to add different classes. I trie... | As identified already in the comments, you have a few issues. I'm going to spell them out for you as an answer.
The first issue is that your final else is only controlling a single line because it does not enclose the multiple statements in brackets.
else
bonus = oldSalary * 0.05;
total = bonus + oldSalary;
... |
72,810,401 | 72,810,504 | Do while loops execute all lines of code if their conditional is no longer met in the middle of a block? | I'm new to programming and I had a question for a project I'm working on.
So if I run this code, does the while loop exit after sending the string "world" to the terminal? Or would it exit before that code is ran?
while (conditionalStatement == false)
{
std::cout << "hello ";
conditionalStatement = true;
std:... | The answer is yes. The condition is only checked at the start of each loop iteration. If you want to end loop execution early, you must execute a break statement.
|
72,810,480 | 72,824,237 | How to update assembly version of c++ project in Azure Devops Pipeline? | I have a c++ project solution which i am building using azure devops pipeline and i want to update the file version everytime my build is sucessful. I have found different extensions but none is working for me.
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "xxxxx"
BEGIN
VALUE "CompanyName... | Try using the Replace Text in Source Files extension. Just add two Replace In Files Text By Text tasks to replace the FileVersion and ProductVersion separately.
You can set your file and product version variables for the update. Also search the *.rc file by a pattern or specify the particular *.rc file in the Advance o... |
72,810,620 | 72,810,651 | Creating serial text output with a text | Hello I want to know how can I make a code like i want to input a number XXX it will output
ChinaXXX
BeijingXXX-CHINA-XXX
+180243189(XXX)
Like this. Advance thanks
Sorry for the title. I dont how can i said about on title.
| #include <iostream>
#include <string>
int
main()
{
std::string number;
std::cin >> number;
std::cout << "China" << number << " Beijing" << number
<< "-CHINA-" << number << " +180243189(" << number << ")"
<< std::endl;
}
|
72,811,201 | 72,811,239 | How can I use a string read from `std::cin` to look up an existing variable by name? | I'm currently trying to make a sort of a shopping cart. When the program asks for items, i type them in; but it needs to remember the values so it can use them later in the code.
I have this code so far:
#include <iostream>
int main() {
int item{};
int apple = 5;
std::cout << "what item do you want to buy?... | You could create a map with string keys and int values, store the necessary data in that map (instead of separate variables), and use the value read from std::cin as an index.
The code looks like:
std::map<std::string, int> fruits;
fruits["apple"] = 5;
std::string choice;
std::cin >> choice;
std::cout << fruits[choice]... |
72,812,148 | 72,816,735 | Integer to byte array arduino BLE | I want to convert an interger to bytes array and send it via BLE using the writeValue() function:
int x;
String strx;
x=accel.x();
strx=String(x);
byte bytes[4];
strx.getBytes(bytes,2)
Serial.print(sizeof(bytes));
accelxCha... | I found out that I have to be careful on how I declare the characteristic there are these options in the documentation:
BLECharacteristic(uuid, properties, value, valueSize)
BLECharacteristic(uuid, properties, stringValue)
BLEBoolCharacteristic(uuid, properties)
BLEBooleanCharacteristic(uuid, properties)
BLECharCharac... |
72,812,328 | 72,901,817 | ICC compile options for evaluating macros in GDB while debugging | I would like to evaluate and print the macro while debugging using GDB. While the GDB documentation has steps to do that by compiling using -g3 flag in gcc compiler, I am using Intel Icc compiler. Their debugging compilation options seem to have no information about macros. Is it possible to do that using icc? If yes w... | icc --help prints almost 2000 lines of output, among which there's
-debug [keyword]
Control the emission of debug information.
Valid [keyword] values:
[snip]
[no]macros
Controls output of debug information for preprocessor macros.
but passing -debug macros results in a... |
72,812,520 | 72,812,655 | C++ unordered_map implementation problem previous values in map get forgotten | In the below code why map size is always 1, it is not saving previous values of root->val in the map as I can see in stdout. I was expecting that it should remember all the values put in the map.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right... | Your code looks like you make an recursive call, to make a depth first search on the tree, but in fact it does not.
Because you are not using a normal member function, but the constructor, and a constructor can not be called recursive.
The syntax that look like recursion is instead the creation of additional temporary ... |
72,812,599 | 72,812,720 | Iterating over std::optional | I tried to iterate over an std::optional:
for (auto x : optionalValue)
{
...
}
With the expectation of it doing nothing if optionalValue is empty but doing one iteration if there is a value within, like it would work in Haskell (which arguably made std::optional trendy):
forM optionalValue
( \x ->
...
)
Why c... | std::optional does not have a begin() and end() pair. So you cannot range-based-for over it. Instead just use an if conditional.
See Alternative 2 for the closest thing to what you want to do.
Edit: If you have a temporary from a call result you don't have to check it explicitly:
if (auto const opt = function_call()) {... |
72,813,046 | 72,813,148 | getLine() does't seem to work after first input - C++ | I'm currently new to C++ and learning the basic syntax.
I'm exploring how getLine() works and I'm trying to compare the standard input and a getline().
#include <iostream>
#include <string>
using namespace std;
int main(){
string name1;
string name2;
cout << "Type your name please: ";
cin >> name1;
cout << "Your nam... | As you can see cin >> name1; reads only up to the first whitespace. What remains in the input buffer is Doe\n. (Notice the first character is a space).
Now cin.ignore(); will ignore 1 character (the white space in this case). The input buffer now contains Doe\n. See here for more details: https://en.cppreference.com/w... |
72,813,066 | 72,813,067 | How to parse a .yml file without %YAML:1.0 header [C++] | I need to parse a .yml file which doesn't have a header, which on the other hand is required by OpenCV.
How OpenCV wants a .yml file to look like:
%YAML:1.0
---
data:
- coordinates: [....]
filename: "..."
- coordinates: [....]
filename: "..."
How our files look like:
data:
- coordinates: [....]
... | Update - I prepared a ready to use function to read OpenCV Yaml without %YAML:1.0 header
cv::FileStorage readFileStorage(const std::filesystem::path path)
{
std::ifstream file(path, std::iostream::binary | std::ios::ate);
if (!file.good())
{
return "";
}
file.exceptions(std::ifstream::badb... |
72,813,269 | 72,820,960 | Get link of the page that createWindow() opens | Im trying to make a tab system
This code gives me the link of the page that i am currently on, i would like to get the link of the page i clicked on. In this code if i change return nullptr; to return this;, the clicked page will open in the same tab.
QWebEngineView* createWindow(QWebEnginePage::WebWindowType type)
{
... | This little change worked for me:
QWebEngineView* createWindow(QWebEnginePage::WebWindowType type)
{
if(type == QWebEnginePage::WebBrowserTab)
{
MyWebView *webView = new MyWebView();
emit new_tab(webView);
return webView;
}
return nullptr;
}
this code creates a new MyWebView obje... |
72,813,551 | 72,813,821 | Choose class specialization using default template parameter | Can someone please explain why in the following code C choses the specialization but A does not? They look the same to me
#include <iostream>
template <typename T=int>
struct C {
int i=3;
};
template<>
struct C<int> {
int i=4;
};
template <typename T=int>
struct A {
A(int, int) {}
};
template <>
struct ... | Without an explicit template argument list (as in A a instead of A<> a) class template argument deduction (CTAD) will be performed.
CTAD basically tries to find a matching constructor for the declaration from which it can deduce the template arguments. But it always considers only constructors in the primary template, ... |
72,813,805 | 72,820,405 | C++ warn when storing 32 bit value in a 64 bit variable | I recently discovered a hard to find bug in a project I am working on. The problem was that we did a calculation that had a uint32_t result and stored that in a uint64_t variable. We expected the result to be a uint64_t because we knew that the result can be too big for a 32 bit unsigned integer.
My question is: is th... | The multiplication behavior for unsigned integral types is well-defined to wrap around modulo 2 to the power of the width of the integer type. Therefore there isn't anything here that the compiler could be warning about. The behavior is expected and may be intentional. Warning about it would give too many false positiv... |
72,814,644 | 72,814,709 | How can I check if template type is any type of std::vector<> | I have a template function like this:
template <typename T> void MyClass::setData(const std::string& name, const T& value)
{
...
// if the template type is a vector of strings, add instead of overwrite
if constexpr (std::is_same_v<T, std::vector<std::string>>)
{
auto temp = someData.get<T>(... | You can use partial specialization:
#include <type_traits>
#include <iostream>
#include <vector>
template <typename C> struct is_vector : std::false_type {};
template <typename T,typename A> struct is_vector< std::vector<T,A> > : std::true_type {};
template <typename C> inline constexpr bool is_vector_v = is_v... |
72,815,476 | 72,838,168 | Nodejs/c++ addon - getting error "undefined symbol: speech_config_from_subscription" from Microsoft speech SDK on ubuntu 18.4 server | Actually, I want to do speech transcription with passing MULAW (g711) audio format to microsoft-speech-sdk (Nodejs), but MULAW streaming audio format is not supported to microsoft-speech-sdk (Nodejs).
So, for this required GStreamer with C++.
So, I'm going to create node/c++ addon for this. but I am facing below error.... | I got the solution, Just coped this libMicrosoft.CognitiveServices.Speech.core.so library into /usr/lib folder and modified binding.gyp file. it is working fine.
{
"targets": [
{
"target_name": "transcription",
"sources": ["src/streamingAsr.cpp"],
"cflags": ["-Wall", "-std=c++17"],
"cflags... |
72,815,993 | 72,823,331 | C++ variadic templates pass modified arguments to function | I'm struggling with the following code. It's meant to be a very simple, hopefully constexpr, gradient-descent solver.
My current code looks like this:
typedef std::function<double(double, double, double)> residual_function_t;
double gradient_descent(const residual_function_t& res_fun, double step_size, double& x, doub... | If you want all the arguments to be of type double, then you might consider using std::initializer_list as follows:
double gradient_descent(const residual_function_t& res_fun,
double step_size,
std::initializer_list<double> args,
double epsilon = 0... |
72,816,593 | 72,827,414 | template std::boost function given to a thread invalid static_cast | I am writing an util class to facilitate thread management into ROS environment. I would like to pass a callback ROS function coded with the boost lib lambda expression style in argument to my thread handler object (TriggeredProcess class). Here is my code :
my code
#include <boost/function.hpp>
#include <boost/thread.... | I think the issue is caused by two core mistakes:
&run, which takes the address of a template
calling a nonstatic memberfunction without this
You static_cast the address of the template to a different type (probably in order to resolve the type ambiguity), but that is what you'd do with an actually overloaded functio... |
72,816,624 | 72,816,993 | Is there a stratified enum, or base class for enum in C++? | I encountered a situation where I need to write many enums, but wish to separate, or stratify all the enums into groups of enums of smaller length, as the following shows:
enum class health {HP,Shield};
enum class battle {STR,AGL,INT};
// such struct DOESN'T WORK, either with instantiated object or direct struct refer... | You may want to ask yourself if you need enums, particularly, or if you actually just want some kind of tag. Enums allow runtime switching based on an object of the enum type, whereas for the use case you've shown (health::HP, battle::STR) the property type is known at compile time, and a type-based tag approach may su... |
72,817,191 | 72,825,277 | In OpenGL is it possible to select from multiple indices with the same vao? Or share a vbo across vaos? | Suppose we are drawing a cube in 3 ways: points, wireframe and shaded. The same 8 points are used for both drawing commands, but the points can just be drawn from the vbo, the wireframe is connecting pairs of points, and the shaded version needs triangles.
This can be achieved using two index arrays. For wireframe:
ui... | Yes, you can put multiple sequences of indices within one index buffer.
The last argument of glDrawElements() (void* indices) is actually not a pointer to memory but rather a starting byte offset into your index buffer. You can draw a subset of your indices by simply specifying the byte offset of the first index you wa... |
72,817,192 | 72,840,916 | Problem with linking Class into specific memory region using Linker Script | I have a problem with linking class to specific memory region via Linker Script
I've figure out how to link variables and functions that are out of the class but I have no idea how to link the class into the memory region specified in the linker script
My linker script is very simple:
SECTIONS
{
. = 0x1000000;
.tex... | Thanks Peter for the help
Here what I did:
Added MemAssembly section in ASM
section .MemAssembly
global global_MemAssembly
global_MemAssembly:
Link it with 0xb000000
SECTIONS
{
. = 0x1000000;
.text : { *(.text) }
. = 0x8000000;
.data : { *(.data) }
.bss : { *(.bss) }
. = 0xB000000;
.MemAssembly ... |
72,817,516 | 72,876,509 | Properly using QMAKE_POST_LINK in Qt project file | When adding commands to QMAKE_POST_LINK using += operator should I need to add a semicolon?
For example,
QMAKE_POST_LINK += mv somefile1.dat /some_location1; # semicolon
QMAKE_POST_LINK += mv somefile2.dat /some_location2
...
Without the semicolon Qt doesn't separate the commands.
Is this proper functionality?
| You should add $$escape_expand(\n\t) at the end of the each command.
Some examples (just took from my real app):
QMAKE_POST_LINK += "cp -f $$OUT_PWD/$$DESTDIR/crashreporter.app/Contents/MacOS/crashreporter $$MACX_APP_MACOS_DIR" $$escape_expand(\n\t)
QMAKE_POST_LINK += "cp -R" $$VMSCLSHARED_DYLIBS $$MACX_APP_FW_DIR/ $$e... |
72,817,641 | 72,817,685 | float vector and pointer returns different values even though they have same adress | I have a class which returns vector<vector<float>> with its getTemplates() function. My code is as follows for this case:
cout << "Get [0][0] " << s.getTemplates()[0][0] << endl;
cout << "vec addr " << &(s.getTemplates()[0][0]) << endl;
float *embFloat = s.getTemplates()[0].data();
cout << "embFloat: " << embFloat <<... | s.getTemplates() returns a temporary which (in this particular instance) goes out of scope at the end of the statement that contains it.
float *embFloat is therefore a dangling pointer - i.e. it's pointing to an object that no longer exists.
|
72,818,501 | 72,818,858 | Cannot convert argument 1 from 'int' to 'int [][8] | I'm trying to make chess in the c++ console and I have a function that searches for the piece you want to move. The first parameter is the 2d array that stores the board's state. But when I call the function in the move function it gives me this error:
cannot convert argument 1 from 'int' to 'int [][8]
It also tells ... | search_piece function gets a two-dimensional array as its first argument, but in the move function where you call it, you just pass a single integer not an array.
v[8][8] in pair<int, int> pos = search_piece(v[8][8], col, piece, colour); is a single element of v array. if you want to pass hole array simply pass v.
pai... |
72,818,540 | 72,818,710 | C++ Template - passing const value of type T by reference | I have a function with a template parameter T and would like to pass a value of type const T by reference.
The C++ compiler throws an error, (kind of) understandably so. Hence I was wondering if there exists a way to do this in a safe and concise way?
I created a very small example that reflects the issue I am having i... | The issue is in incompatibility between pointers:
pointerToTestConst is of type const int* - non-const pointer to const integer. Therefore T=const int*
myList is of type list<int*>, deducing T=int*.
Since those types are not the same, compilation fails. Rightfully so, because elem would allow changing testConst if T=... |
72,818,787 | 72,825,935 | OpenCV imshow fails with src_depth != CV_16F && src_depth != CV_32S in function 'convertToShow' | Code for operating my camera is giving me images as signed 32-bit integers, and I would like to turn this into an openCV Mat.
When I have 16-bit signed integers, I do the following:
int16_t x[100][100];
Mat A(100, 100, CV_16SC1, x);
imshow("BLAH", A);
This works. Similarly, when I have 8-bit unsigned integers I use ui... | I added your error message for you. It says:
/opencv/modules/highgui/src/precomp.hpp:155: error: (-215:Assertion failed) src_depth != CV_16F && src_depth != CV_32S in function 'convertToShow'
That means imshow does not accept 32 bit signed integers (nor does it accept half floats).
You need to give it anything but that... |
72,818,990 | 72,837,636 | Qt retrieving reference out of a struct inside a QList | i have a struct "Material" which has a referencetype of Item&
Item is a baseclass for many different Materials who can appear in a list.
The struct also has an integer variable and also a QString variable. Those two are just give
the amount to be used and a String of what type item must be casted back.
struct Material
... | For all who stumble on this, i will post my fixed example code.
But i highly recommend to read the comments from Scheff's Cat and sigma below my question. Because they give you some really important infos why this is happening. I my self will consider the idea of sigma to use the std::unique_ptr for my code.
eyeball in... |
72,819,590 | 72,823,104 | How can I determine the index of the top item displayed in the drop-down list of a TComboBox? | How can I find the index of the top item in the drop-down list of a TComboBox?
I know that a TListBox has a TopIndex property, but I can't find anything similar to this for a TComboBox.
I'm using C++Builder in RAD Studio 10.4 Update 2.
| Since FMX's TListBox does not have a TopIndex property, I'm going to assume you are referring to VCL instead.
In the VCL, you can access the HWND of the TComboBox's drop-down ListBox by calling the Win32 GetComboBoxInfo() function on (or sending a CB_GETCOMBOBOXINFO message to) the HWND returned by the TComboBox::Handl... |
72,819,843 | 72,820,224 | Optional argument after template parameter pack of supposedly known length | I am trying to have a kind of "invoke" function with an optional argument at the end:
template <typename... T>
void foo(void func(T...), T... args, int opt = 0)
{
func(args...);
}
void bar(int, int);
int main()
{
foo(&bar, 1, 2, 3);
}
I would have expected this to work, since the parameter pack can be deduce... | You could make it overloaded instead of having an optional argument. You'd need to move the "optional" to before the parameter pack though.
The second overload would then just forward the arguments to the first, with the "default" parameter set.
#include <iostream>
template <typename... T>
void foo(void(func)(T...), i... |
72,820,017 | 72,820,652 | Ant/Make Compilation Error with File Path Having Spaces | Unable to produce some MVC to reproduce the issue. So trying to be clear & concise.
We utilize ant/make
The include path to building the C++ portion utilizes a header (jni.h) from the java installed directory
Example Error (During Build Process)
3)
*File.h(2): fatal error C1083: Cannot open include file: 'jni.h': N... | I'm not sure what ant has to do with this. But make recipes are just shell scripts (or, if you use Windows cmd.exe instead of a POSIX shell, batch files). Just like commands you'd write in a batch file or on the command line directly, you have to add quoting to paths that contain whitespace.
You don't actually show u... |
72,820,497 | 73,077,225 | Why have .a files been installed in Windows with Qt online installer? | I installed Qt 6.3.1 libraries pre-built with MinGW 11.2.0 64-bit using the online installer. The application crashes without entering the main function when I use any of Qt libraries in the Qt Creator while there is no problem if I use only C++ standart library. I guess the problem is in linking. Because I realized th... | After learning that the problem may be due to duplication of some library from here, I saw using dependency walker that my program uses libstdc++-6.dll in system32 instead of qt-mingw installation. So the problem solved when I copied that dll into my app's folder. But I wonder how to solve this by changing the path wit... |
72,821,106 | 72,821,224 | Is calling a private function from a public function good coding practice? | I'm wondering if calling a private function from a public function to achieve a cleaner syntax could cause any type of problems.
#include<iostream>
class tree{
private:
struct node {
int data;
int counter = 1;
node* left;
node* right;
};
node* getnewnode(int x) {
... | For starters the data member
node* root = NULL;
shall not be public.
Secondly the function recursiveinsert should be declared at least as a static member function.
It is better to declare and define it like
static void recursiveinsert( node * &rootPtr, int x )
{
if ( rootPtr == nullptr )
{
rootPtr = ... |
72,821,847 | 72,821,905 | How to merge different operators with the same logic in C++ class for not copypasting | Is it possible to merge some operators of class that have same logic but different operators to not copypasting. For example, I have class with operators +=, -=:
class Matrix {
public:
Functor& operator+=(const Functor& rhs) {
for (int i = 0; i < num; ++i) {
v[i][j] += rhs.v[i][j];
}
... | You can do it by passing a lambda to a common implementation:
class Matrix {
private:
template<typename Op>
Functor& opImpl(const Functor& rhs, Op op) {
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < columns_; ++j) {
Op(v[i][j], rhs.v[i][j]);
}
}
re... |
72,821,884 | 72,821,927 | Replace memcpy with memcpy_s with an unsigned char | Let's suppose we have a legacy code that performs this operation:
unsigned char* dest = new unsigned char[length];
memcpy(dest, source, length);
where the pointer source is passed as input parameter of that method. length is an unsigned long variable.
Now I want to replace the memcpy call, considered not secure, with ... | memcpy_s() is not fundamentally "more secure". It just performs a few sanity checks. In your case, some of these are even redundant. So, if you want to "defend" your function implementation from invalid arguments, you could make sure source is not nullptr; all the other "security" checks are guaranteed to pass anyway:
... |
72,821,999 | 72,822,874 | auto-conversion from struct to long in liinux C++? | I'm converting a C++ Linux program (I don't know what compiler) to Visual C++ 2019. I'm seeing some strange code.
Today's example is:
long offset = timezone;
I also see:
offset = timezone - 3600;
timezone appears to be defined as:
struct timezone;
It should be defined as:
struct timezone {
int tz_minutewest;
i... | The struct timezone you are showing is a Linux/glibc-specific type defined in <sys/time.h>. See man gettimeofday.
There is also a variable named timezone in <time.h> which is specified by POSIX (X/Open). See man tzset for information about the Linux/glibc implementation of that feature.
Of course it is not clear whethe... |
72,822,019 | 72,822,241 | Incorrect results: mapping c++ array to Eigen Matrix | I have used the map feature before to map existing memory into Eigen matrices, however when trying to map an fftw c++ array, I am getting wrong results, almost if a portion (a slice?) of the array is being mapped into an Eigen matrix and not the entire memory block. This is the code I am using:
static const int nx = 10... | You're computing your offsets wrong. [i+nyk*j] is not correct. The largest value of j is (nyk-1). I think you meant for it to be [i*njk+j].
To diagnose this sort of problem, I suggest doing
uhk[j + nyk*i][k] = (k==0)?i:j; // Note I swapped i/j in the offsets
This will create a matrix where the real portions match th... |
72,822,061 | 72,822,733 | How to replace decltype(f()) with std::invoke_result_t, where f is a lambda with non-type template parameter? | How to replace the following with std::invoke_result_t?
decltype(f.template operator()<0>())
Here's more context:
template <size_t I, typename Functor>
consteval void apply(Functor&& f)
{
using ResultType = decltype(f.template operator()<0>())>);
// ... More stuff ...
f.template operator()<I>());
}
void t... | You still need decltype, because invoke_result_t requires the type of the method followed by the type of the class. But here you go:
#include <cstddef>
#include <type_traits>
template <size_t I, typename Functor>
consteval auto apply(Functor&& f)
{
// using ResultType = decltype(f.template operator()<0>());
u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.