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,678,576 | 73,680,258 | Does std:: library of c++ have .cpp files? | This may be a naive question since I'm a c++ beginner.
In a typical cpp project, we have cpp files and their header files. So based on my understanding, usually cpp files have definitions, while respective header files have declarations. During compiling, we have to include very cpp files in the project since header f... | Yes, there is compiled code in the standard library. You don't have to compile it because the library comes already compiled with your compiler. And you don't explicitly link to it, because the compiler knows about it. So you don't see it mentioned anywhere when you do normal builds. If you set your compiler to some fo... |
73,678,596 | 73,681,926 | Can't cast void pointer returned by RegGetValueA | I'm trying to access the registry using the RegGetValueA function, but I can't cast the void pointer passed to the function. I just get the (value?) of the pointer itself.
Here's my code:
LSTATUS res;
LPCSTR lpSubKey = "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{071c9b48-7c32-4621-a0... | You are using the function incorrectly.
First off, you shouldn't be accessing Wow6432Node directly at all. The function has flags for accessing 32bit and 64bit keys when dealing with WOW64.
More importantly, you are giving the function a void* pointer that doesn't point at valid memory for your purpose. When reading a ... |
73,678,674 | 73,678,794 | Get a count of numbers in segments | The array has a large size up to 100000 and m is number of gets.
For example:
int array[] = {1, 2, 2, 3, 4, 5, 5, 5, 6, 7};
get(1, 4, array);
And the result:
1: 1
2: 2
3: 1
I wrote this but it uses a lot of memory:
for (int i=1; i<=n; i++) {
ma[a[i]]++;
pref[i] = ma;
}
map<int,int> ans = pref[r];
for (auto ... | What's wrong is you're computing the answer for all of the numbers. Instead, do this:
map<int, int> count(int[] array, int left, int right) {
map<int, int> result;
for (int i=left; i <= right; i++) {
result[array[i]]++;
}
return result;
}
It's pretty simple; it just iterates over all the indexe... |
73,679,033 | 73,691,576 | C++20 range from enum | can an enum be used as (or turned into) a C++20 range?
I am thinking about following use case, cartesian_product() is C++23 unfortunatey:
#include <algorithm>
using namespace std::ranges;
enum Fruit{APPLE, STRAWBERRY, COCONUT};
enum Vegetable{CARROT,POTATOE};
for (auto [fruit, vegetable] : views::cartesian_produc... | You can do this, it's just that you need the help of a library to turn the enum into a range of enumerator names. One such library is Boost.Describe:
#include <array>
#include <boost/describe.hpp>
#include <fmt/ranges.h>
enum Fruit{APPLE, STRAWBERRY, COCONUT};
enum Vegetable{CARROT,POTATO};
BOOST_DESCRIBE_ENUM(Fruit,... |
73,679,355 | 73,680,362 | Is there any way to append initializer list --> std::initializer_list<std::pair<std::string, std::string>>? | In my project there is need to append initializer list at runtime.
I have figured the way to have initializer_list std::initializer_list<std::pair<std::string, std::string>> at runtime in my project, but not able to figure out way to append this list if user passing multiple no. of pairs.
dummy code implementation of t... | The length of a std::initializer_list cannot be chosen dynamically at runtime and list's length here is not a compile-time usable property.
std::initializer_list is the wrong tool for this. It should only be used as parameters to functions or implicitly in e.g. a range-for loop. In any case only directly to store a {/*... |
73,679,723 | 73,679,834 | "undefined reference to `____: :___`" error for pure virtual functions when I seperate my files into cpp and header files | So I have the Book class that inherits from Publication.
Publication has two pure virtual functions which I implemented in Book.
The code worked before I tried seperating into header and cpp files
classes.h
#include <iostream>
#include <string>
using namespace std;
class Publication
{
protected:
// Common attributes... | I realized I was just dumb and forgot that I need to compile both cpp files and not just main.cpp
Running g++ main.cpp task1.cpp caused no errors.
|
73,680,053 | 73,682,087 | How to combine views::enumerate and views::filter? | I have a container that I want to filter.
I also need the index of the items later.
For that I want to use something like this:
auto items_to_remove = items | ranges::view::enumerate | ranges::view::filter(/*???*/);
What type do I have to use for the filter function?
Edit: Here is my code/ error message:
auto f = [](c... | Adding an enumerate::view makes the element that is passed to the filter a
ranges::common_pair<size_t, int&>&
So, just take the common_pair by const&.
auto f = [](const ranges::common_pair<size_t, int&>& pair) {
// filter on pair.first to filter on the index
// filter on pair.second to filter on the actual val... |
73,680,313 | 73,681,822 | Read access violation while deleting multiple nodes from a linked list | I need to implement a doubly linked list in c++ for a small animation running on console. The linkedlist stores clouds and then they move through the console and as each cloud hits the end of screen, it needs to be deleted from linked list. As the cloud hits the end, it has a variable called alive which is set to false... | As @John Zwinck and @Sam Varshavchik pointed out that the implementation of delete method was flawed and temp became useless after the Delete function returned.
I fixed it by using another temp pointer and fixing the delete method to be O(1).
Delete Method
void LinkedList::Delete(Node* del) {
if (del == head) {
... |
73,680,646 | 73,680,745 | how to allow only one specific class to create other class instances | MyDataConatiner is kind of facade to MyData.
I Dont want to allow other classes to create Mydata .
it has some logic of lazy instantiation that I want to keep in MyDataConatiner .
thought about something like private ctor with friend class , but I am not sure.
or is it something with one of factory design patterns
| One way is to make MyDataContainer a friend of MyData as shown below:
class MyData
{
//befriend MyDataContainer so that MyDataContainer can create object of type MyData
friend class MyDataContainer;
//private converting ctor that can be used by MyDataContainer but not normal users
MyData(int)
{
}... |
73,680,994 | 73,686,358 | Error when importing a class/structures from one dll to another dll (c++, lnk2019) | I have 2 DLLs. The first describes the LinkedList data structure. In the second, this structure is used.
LinkedList.h (from first .ddl):
#pragma once
#ifdef DS_EXPORTS
#define DS_LL_API __declspec(dllexport)
#else
#define DS_LL_API __declspec(dllimport)
#endif
#include "pch.h"
#include <iostream>
using namespace std... | 1.Follow drescherjm 's comment.
2.I noticed another problem:
Your project one did not generate lib file, so you have no way to add LinkedList.lib in Linker->input of project two's properties. But you still got the link errors.
I deduce that you did not actually add LinkedList.lib file in Linker->input->Additional Dep... |
73,681,554 | 73,681,595 | C++: instantiating object that is declared in a header file | If an object is declared in a header file like this:
Object obj;
What would be the best way to instantiate it? A simple reassignment like this? Does this destroy the declared object and create a new one and can this lead to errors?
obj = Object(...);
Or should I use a pointer and create the object with new? This way ... | Object obj;
already instantiates the object. SO you really should not have it in a header file
you probably want
Object *obj;
ie a pointer to an object , then instantiate with 'new'.
But better would be std::unique_ptr<Object>
|
73,682,060 | 73,682,289 | Compile error in SFML 2.5.1 sample code in Linux | Compile error
I was looking at a configuration video in yt for linux mint but it doesn't give me the same results in arch.
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
... | As the error message indicate, there is no constructor for sf::VideoMode which takes two int input for width and height. The constructor expect an argument of type Vector2u.
Create the Window as follows:
sf::RenderWindow window(sf::VideoMode({200, 200}), "SFML works!");
|
73,682,188 | 73,682,230 | Why does C++ implicit casting work, but explicitly casting throws an error (specific example)? | I was trying to overload the casting operator in C++ for practice, but I encountered a problem and I can't figure out the issue. In the example, you can implicitly cast fine, but it causes an error when you try to explicitly cast.
struct B
{
B() = default;
B( B& rhs ) = default;
};
struct A
{
operator B()
... | static_cast<B>(a);
This expression is an rvalue, more loosely described as a temporary value.
The B class has no suitable constructor. The B( B &rhs) constructor is not suitable, mutable lvalue references don't bind to temporaries, hence the compilation failure.
|
73,682,305 | 73,814,247 | How to debug missing functions in vtable of base class | By using objects of the following structure(some bits simplified):
class RafkoAgent{
virtual std::vector<double> solve(std::vector<double>& in) = 0;
void solve(std::vector<double>& in, std::vector<double>& out){
out = solve(in);
}
};
class SolutionSolver : public RafkoAgent {
std::vector<do... | The root cause of the problem was that there were compilation macros used in the exported header files.
The main hint for this was that in the same repository it worked flawlessly, but it failed by the exported library.
The faulty structure was as follows:
class A {};
class B
#if(compile_time_macro)
: public A
#endif... |
73,683,086 | 73,683,303 | How to find the smallest number composed of only 1 that can divide by n, given n is a coprime of 10? | I'm writing a program with which to find the smallest number m composed of only the number "1" that can divide by a given number n. n must be a co-prime of 10.
For example:
n = 37 -> m = 111 (111/37 =3)
n = 11 -> m = 1111 (1111/11 = 101)
n = 91 -> m = 111111 (111111/91 = 1221)
My current code:
#include <bits/stdc++.h... | For the new version you found, you can be sure that there's no solution if the new m you computed was already encountered previously - that means you're on an infinite loop.
However, since caching previous values of m can be too much for the scope of this problem, you can resort to the weaker condition: if the loop run... |
73,683,313 | 73,683,581 | Random matrix multiplication | I need to create at least 2 matrix 4x4, multiplicate them and display the result, but I'm getting this thing as as result img
I'm creating matrix a[i][j] and matrix b[k][l], and trying to pass the result to a new matrix called c[i][j]
Besides that, I need to make 2 kinds of matrix multiplication, one like this, and ano... | A common "Beginner's Problem" is writing too much code. One consequence is that there are too many places where bugs and other flaws can hide.
This is in 'C', but the only 'C++' aspect of your code is using cout for output. printf() can also be used with C++.
#include <stdio.h>
#include <stdlib.h>
void fill4x4( int a[... |
73,683,516 | 73,683,846 | "error: too many arguments to function" when trying to access vector elements in a function call | I'm writing a program to populate a vector from a list of numbers in a file, and then check the list to see how many numbers appear more than once. The program works when I hard code the array size based on the number of lines in the file. But I want to use a vector to automate the sizing of the array for each file sin... | In C++, () is a function call operator and is used to call the function. For example, when you write main(), you are calling the function main which in turn causes the main function to start executing.
To access an element of a vector, you should use subscript operator [] not function call operator ().
I've highlighted... |
73,683,693 | 73,683,796 | How to construct derived class from base? | Is there a way to cast base class to derived, calling default constructor?
I'm receiving network data, writing it to packets, then calling protocol function which I wish to parse data differently.
class BasePacket {
protected:
std::vector<char> data;
public:
BasePacket(){data.reserve(2048);}
BasePacket(... | If your instance is initially a BasePacket object, why not just code like ActionPacket::ActionPacket(BasePacket&)? That's because ActionPacket have some members that BasePacket doesn't have, reallocation seems inevitable. Just like this:
class ActionPacket
{
ActionPacket(BasePacket& basePacket) :BasePacket(basePack... |
73,683,986 | 73,684,344 | How do you find the number of occurences of a certain word in a sentence when reading in the sentence character by character? | For example, if I wanted to find the number of times that the word "MY" appears in a user-inputted sentence, how would I do that? Is it even possible to do this if I'm reading in the sentence one character at a time with a while-loop?
Sample input would be something like: "My house is here"
My current output is:
Number... | This can be done in many ways, you almost have one. I will not give you the exact solution but you can try something like this: (written in Java)
// String sentence = "My house is here";
// word = "My"
private int getWordCount(String sentence, String word) {
char[] charArr = sentence.toCharArray();
String currW... |
73,684,176 | 73,684,314 | clang constexpr compile error in lambda, gcc and msvc ok. clang bug? | I ran across a compile error in clang with this code. I don't see any problem with it and it works in msvc and gcc. Am I missing something or is it a clang bug?
#include <iostream>
#include <string>
#include <type_traits>
constexpr bool do_tests()
{
// prints error message at runtime if test is false
auto veri... | There is no problem with the code and Clang also compiles it correctly if you use libc++ (-stdlib=libc++). Compiler explorer by default uses libstdc++ for Clang (-stdlib=libstdc++). There simply seems to be a compatibility issue between the two. My guess is that libstdc++ is implementing the constexpr string in a way t... |
73,685,070 | 73,685,287 | How to download a zip file from a github repo using libcurl? | I have upload a zip file compressed with WinRAR containing a txt file into my github test Repo, how I could download the zip file using curl?
I tried:
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return writ... | The issue
I checked with
curl -I https://github.com/R3uan3/test/files/9544940/test.zip
It gets
HTTP/2 302
...
location: https://objects.githubusercontent.com/github-production-rep...
In other words: this is a redirect and you did not ask libcurl to follow redirects - so you only get that first response stored (which ... |
73,685,911 | 73,691,238 | Is there a way to remove the last template parameter of variadic template methods? | I'm working on creating a simple reflector in C++11, it stores function pointers of instances functions as:
static std::unordered_map<std::string, std::pair<void(EmptyClass::*)(void), int>>* methods;
template<typename ClassType, typename returnType, typename... Args>
static void RegistFunction(std::string name, returnT... | Here's a C++11 implementation depending only on std::string and std::unordered_map. Some mandatory remarks:
As mentioned, this is extremely brittle due to inferring the function type by the provided arguments. This is UB waiting to happen.
method really shouldn't be a pointer.
If your return type is not assignable, th... |
73,686,187 | 73,702,823 | QuickFix C++ - How to established Trading session from client APP? | I have build my quickfix C++ source code with the SSL support using below command. My quickfix library got build successfully.
On Linux (with system openssl),
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DHAVE_SSL=ON -DCMAKE_INSTALL_PREFIX:PATH="install-path" .. make -j 4 install
This is my Initiator code -
if (isSSL.comp... | but this is not related to compilation issue .Its quickfix source code bug.
I found one blog related to that this file has missing entry
#cmakedefine HAVE_SSL 1
I have added in this file
cat cmake_config.h.in
#ifndef CONFIG_H_IN
#define CONFIG_H_IN
#cmakedefine HAVE_EMX
#cmakedefine HAVE_CXX17
#cmakedefine HAVE_S... |
73,686,877 | 73,687,824 | Why is the syntax of the destructor ~classname? | The syntax of the destructor is ~classname. This results in the need to explicitly write the type of object in the destructor call. To avoid this, C++17 introduced std::destroy_at.
So, what was Bjarne Stroustrup's original rationale for choosing the ~classname syntax for the destructor? If the syntax does not depend on... | Constructors and destructors were a part of C++ from the very earliest days. (They predated the name "C++.") They predated templates as well as the standard container types like vector that templates made possible. In those early days there was little or no allowance for manual construction/destruction as a separate o... |
73,686,952 | 73,689,453 | Unexpected behaviour from multiple bitwise shift operators in an expression | I noticed that a program that I was writing was not working correctly so I wrote a simple test to check if the problem was the binary shifting.
The code is the following:
#include <iostream>
#include <Windows.h>
#include <bitset>
using namespace std;
int main(){
BYTE byte = 0b10010000; //This is 2^7 + 2^4 = 144
... | You are experiencing the effects of integer promotion.
The operation byte << 1 does not produce an unsigned char, despite byte being of that type. The rationale is that hardware usually cannot perform a number of operations on small types (below a machine word) so C++ inherited from C the concept of promoting data type... |
73,686,971 | 74,124,253 | Azure TTS generating garbled result when requesting Opus encoding | The following sample code (C++, Linux, x64) uses the MS Speech SDK to request a text-to-speech of a single sentence in Opus format with no container. It then uses the Opus lib to decode to raw PCM. Everything seems to run with no errors but the result sounds garbled, as if some of the audio is missing, and the result D... | I've received no useful response to this question (I've also asked here and here and even tried Azure's paid support) so I gave up and switched from Audio24Khz16Bit48KbpsMonoOpus to Ogg48Khz16BitMonoOpus which means the Opus encoding is wrapped in an Ogg container, requiring the rather cumbersome libopusfile API to dec... |
73,687,220 | 73,687,984 | How can I pass a member function pointer type to a template? | I am trying to delegate a method call using a nested std::invoke. Sample code:
class Executor
{
public:
bool Execute(bool someFlag);
};
template <class TMemberFunction, class TInstance, typename TResponse>
class Invoker
{
public:
TResponse Invoke(TMemberFunction* function, TInstance* instance, bool someFlag) {... | You might write your Invoker class like:
template <typename TMemberFunction>
class Invoker;
template <class C, typename Ret, typename... Args>
class Invoker<Ret (C::*) (Args...)>
{
public:
Ret Invoke(Ret (C::*method) (Args...), C* instance, Args... args) {
return std::invoke(method, instance, std::forward<... |
73,687,747 | 73,687,870 | How to convert c-style define of "<>::value" to "c++ template" | I have a 100% working code, which uses C style #defines, but should be converted to c++ style (using=) because this is the style of the rest of the code.
I am not proficient in C++ and struggling to convert the ::value notation.
My code checks if container (like vector/set/map) and its element use the same allocator.
t... | Is this what you are looking for?
template <typename Cont, typename elem>
constexpr bool allocIsRecursive_v = std::uses_allocator<elem, typename Cont::allocator_type>::value;
template <typename Cont>
constexpr bool allocIsTrivial_v = std::uses_allocator<Cont, std::allocator<char>>::value;
template <typename Cont, typen... |
73,688,015 | 73,688,950 | How to get the compositor instance while handling XamlCompositionBrushBase.OnConnected in a WinUI-3 desktop app | Following this c++ example i'm trying to create a custom brush in a WinUI 3 desktop application but i cannot find out how to get a compositor instance from within the OnConnected Method.
The example uses
Microsoft::UI::Xaml::Window::Current().Compositor()
but Current (and CoreWindow) are always null for desktop apps.
... | Ok, as often it gets easy as soon as the matching documentation is found:
In XAML apps, we recommend that you call
ElementCompositionPreview.GetElementVisual(UIElement) to get a
Composition Visual, and get the Compositor from the visual's
Compositor property. In cases where you don't have access to a
UIElement (for ex... |
73,688,057 | 73,689,847 | Cannot use consteval functions inside initializer list on MSVC | Consider that minimized code snippet:
#include <vector>
class Bar
{
public:
constexpr Bar() {}
};
consteval Bar foo()
{
return Bar();
}
int main()
{
std::vector<Bar> bars{ foo(), foo() };
}
This doesn't compile on latest MSVC compiler (Visual Studio 2022 version 17.3.3), but does on Clang or GCC.
Compil... | From the comments, it looks like this is indeed a bug in MSVC.
Therefore I filled in a bug report on Visual Studio Community.
https://developercommunity.visualstudio.com/t/Cannot-use-consteval-functions-returning/10145209
|
73,688,375 | 73,688,644 | Unable to call dynamic library in Unity 3D | Wrote a library for displaying system messages in C++
.h
#pragma once
#ifndef WINDOW_DEFINDE_DEBUG
#define WINDOW_DEFINDE_DEBUG
#include <Windows.h>
#include <string>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef BUILD_LIBRARY
#define SHARED_LIBRARY_DECLSPEC __declspec(dllexport)
#else
#define SHARED_LIBRARY_DECLS... | C# cannot marshal System.String as std::string because there different classes.
UnmanagedType.BStr in C# is BSTR in Windows SDK.
And you've set SetLastError = true, so when nothing comes out, you should call Marshal.GetLastWin32Error to get error.
In fact you can use this method to call MessageBox.
[DllImport("user32.d... |
73,689,747 | 73,690,534 | Why calling future.get() retrieved from async leads to unexpected output order | Consider the following code:
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <future>
std::mutex mutex;
int generate()
{
static int id = 0;
std::lock_guard<std::mutex> lock(mutex);
id++;
std::cout << id << '\n';
return id;
}
int main()
{
std::vector<std::futu... | What you're seeing in the final output is the order in which the threads produced their results.
Consider these three threads as a simplified version:
+- -+ +- -+ +- -+
Thread | 1 | | 2 | | 3 |
+- -+ +- -+ +- -+
Result | | | | | |
+- -+ +- -+ +- -+
Now... |
73,689,914 | 73,691,046 | How do I check whether an IntegerVector contains NA values in Rcpp? | I wish to check that an Rcpp IntegerVector provided to a C++ function does not contain NA values.
Following another answer, I have written the below:
IntegerMatrix stop_if_na(const IntegerVector I) {
if (Rcpp::is_true(Rcpp::any(Rcpp::IntegerVector::is_na(I)))) {
Rcpp::stop("`I` contains NA values");
}
But I se... | This is so core a feature that we had it more or less since day one, and I am a little surprised that you did not come across the very early Rcpp Gallery posts Working with Missing Values by Hadley from Dec 2012.
Note that the more interesting features are 'Sugar' functions:
> Rcpp::cppFunction("LogicalVector foo(Numer... |
73,689,916 | 73,690,555 | Build initializer list for array by repeating n times | I have a std:array something like this:
class MyClass {
private:
std::array<MyComplexType, 10> myArray;
}
In the constructor, I need to do the following:
MyClass::MyClass() : myArray({
MyComplexType(func(const_arg1, const_arg2, const_arg3).method(const_arg4)),
... repeated 8 more times...
MyComplexType... | If you want to use a std::array you are going to need to build a helper function, namely a delegating constructor. Your default constructor will then call the delegate to actually initialize the member. That can look like
class MyClass {
public:
// default c'tor, create sequence of 10 integers
MyClass() : MyC... |
73,690,149 | 73,848,790 | Why are reference members of closure types needed? | [expr.prim.lambda.capture]/12:
An entity is captured by reference if it is implicitly or explicitly captured but not captured by copy. It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference. If declared, such non-static data members shal... | This wording is talking about the struct layout of the closure type. A lambda-expression corresponds to a struct-whose-name-you-don't-know which is basically
class Unnameable {
~~~data members~~~
public:
auto operator()(~~~args~~~) const { ~~~body~~~ }
};
where all of the ~~~ bits are filled in based on the fo... |
73,690,647 | 73,690,832 | Base class default constructor in derived class constructor initializer list | I have seen a lot of times people adding the default constructor of base class in the derived class constructor initializer list like so
DerivedClass::DerivedClass(int x) : BaseClass(), member_derived(x)
{
//Do something;
}
Derived class constructor by default calls the default constructor of base class. Is the Ba... | It depends on declaration of base class. Constructor of derived class actually initializes base class. It involves default constructor call if such is present. If base class is trivial, it wouldn't be initialized. Consider this code:
#include <iostream>
struct Base {
int c;
};
class Derived : public Base {
public:... |
73,690,983 | 73,713,805 | cxxrt::bad_alloc despite large EPC | I am running the following piece of code inside an SGX enclave:
void test_enclave_size() {
unsigned int i = 0;
const unsigned int MB = 1024 * 1024;
try {
for (; i < 10000; i++) {
char* tmp = new char[MB];
}
} catch (const std::exception &e) {
std::cout << "Crash wit... | If the machine you're running your enclave on has more than 128Mb of EPC AND will allow you to go further (because of a BIOS setting), there is one more setting you must fiddle with, in your Enclave.config.xml file:
<EnclaveConfiguration>
<ProdID>0</ProdID>
<ISVSVN>0</ISVSVN>
<StackMaxSize>0x40000</StackMaxSize>
... |
73,690,998 | 73,694,596 | Redirect cerr using rdbuf: set it once and forget it until app ends | I am attempting to redirect cerr to a file at the start of a program, then at the end of the program set it back to normal. This is along the lines of the accepted answer of Use cout or cerr to output to console after it has been redirected to file
I am running into strange behavior in C++Builder for this. The enviro... | First off, DO NOT use the Form's OnCreate event in C++. It is a Delphi idiom that introduces undefined behavior in C++, as it can be triggered before the Form's constructor, so use the actual constructor instead. Likewise, the Form's OnDestroy event can be triggered after the Form's destructor, so use the actual destru... |
73,691,670 | 73,691,841 | Simple C++ multithreading example is slower | I am currently learning basic C++ multithreading and I implemented a very small code to learn the concepts. I keep hearing multithreading is faster so I tried the below :
int main()
{
//---- SECTION 1
Timer timer;
Func();
Func();
//---- SECTION 2
Timer timer;
std::thread t(Func);
... | Multithreading can mean faster, but it does not always mean faster. There are many things you can do in multithreaded code which can actually slow things down!
This example shows one of them. In this case, your Func() is too short to benefit from this simplistic multi threading example. Standing up a new thread invo... |
73,692,981 | 73,722,142 | Only last wxStaticBitmap is showing | The same image is meant to be shown in different locations but only the second one is shown, why?
void AppFrame::OnButtonClicked(wxCommandEvent& evt) {
Tiles* knots = new Tiles(panel, 1);
string tile = knots->firstTile();
ImagePanel* drawPane = new ImagePanel(panel, tile, wxBITMAP_TYPE_PNG);
wxStaticB... | You don't position your ImagePanel and depending on its size it can overlap the first bitmap. Generally speaking, using hard-coded position in pixels is strongly discouraged, you should let the controls use their natural size and position them using sizers as already mentioned in a comment.
|
73,693,001 | 73,693,166 | How to use std::replace_if to replace elements with its incremented value? | I am trying to write a std::replace_if function that takes in a string and replaces all the vowels with a consonant on its right.
How to capture the current iterating character from the string and replace it with its incremented value using a lambda within std::replace_if function
Example :
input : aeiou
output : bfjpv... | std::replace_if cannot do what you want. It accepts only a single new value.
To do what you want either use std::for_each:
std::for_each(
str.begin(),
str.end(),
[](char& c) {
if (std::string("aeiou").find(c) != std::string::npos) {
c = c + 1;
}
}
);
Demo
Or use a normal lo... |
73,693,061 | 73,693,643 | What's the best way to pass a r-value/temporary collection to a function taking a std::span? | I've been trying to start using std::span<const T> in places where I would have previously used const std::vector<T>&. The only sticking point I have is illustrated in the following:
#include <iostream>
#include <vector>
#include <span>
#include <numeric>
double mean1(std::span<const double> vals) {
return std::ac... | you can use
mean1( {{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }} );
which invoke the raw array constructor.
if you want to specify the type, I'd suggest
mean1( std::initializer_list{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 } )
which prevent the potential construction of another container. (which still construct a initializer_list anyway)... |
73,693,805 | 73,693,839 | Why simple code doesn`t work corectly c++? | #include <iostream>
bool check_number(unsigned short int a, unsigned short int b) {
if ((a || b == 30) || a + b == 30) {
return true;
}
return false;
}
int main() {
std::cout << check_number(15, 16) << std::endl;
std::cin.get();
return 0;
}
Why I get "true" result? Why not false, ... | if ((a || b == 30) is not "either a or b equal 30" it is "either (a) or (b equals 30)". As a is non-zero it is true when converted to bool.
So you have
if ((true || other condition) || just_another_condition)
and because || is short-circuiting the condition as a whole is true.
If you actually wanted "either a equals ... |
73,694,162 | 73,694,408 | How to make `this` pointer constant expression? | This is a follow-up question is my previous question: Why are member functions returning non-static data members not core constant expressions?
The reduced version of the example mentioned in that question is:
struct S {
const bool x = true;
constexpr bool f() { return x; }
};
int main() {
S s{};
static_as... | Because return x; performs lvalue-to-rvalue conversion, the whole kaboodle is not a core constant expression:
An expression E is a core constant expression unless the evaluation of E, following the rules of the abstract machine ([intro.execution]), would evaluate one of the following:
an lvalue-to-rvalue conversion u... |
73,695,128 | 73,696,159 | How to download a zip file from github repo and read her content in memory? | I have uploaded a zip file compressed with 7-zip option add to .zip containing only a file with the name text.txt into this GitHub repo, how I could read the content of the file text.txt without writing it to disk?
I'm downloading the zip to memory using curl:
#include <curl/curl.h>
static size_t WriteMemoryCa... | I'm ignoring everything about curl in the question because we've verified that you've got the zip file stored in memory correctly.
How I could read the zip ... that is on the string data?
Since you have the whole zip file stored in memory, you need to create a zip_source from chunk.data() and open the archive using t... |
73,695,763 | 73,696,520 | How could I do a robust mapping of multiple data types? | I am trying to convert a long list of key and value pairs into a map so that I can just iterate over it instead of defining each of them line-by-line, but I have a mix of data types for the values (uint8_t, uint16_t, uint32_t, and uint64_t).
Here's a sample of the data I am trying to build a mapping of:
static constexp... | You should initialize the map like this.
std::map<std::string, dtypes> mymap = {
{"data1", {.i = 0x01}},
{"data2", {.j = 0x0002}},
{"data3", {.k = 0x00000003}},
{"data4", {.l = 0x0000000000000004}},
};
Using an union or struct with properly named members helps to simplify implementations of encoding an... |
73,696,093 | 73,696,146 | C++ Switch statement using strings | I am fully aware that switch must be used with int but my assignment is requiring me to use switch in regards to user input which will be strings. I've looked and I've seen some mentioning stoi but I'm not sure if that is what my professor is expecting b/c we have not been introduced to it yet. I'm completely new to C+... | For single char responses, you can use the switch/case statement:
switch (userInput)
{
case 'g':
case 'G':
/* ... */
break;
case 'u':
case 'U':
// ...
break;
default:
// ...
break;
}
A single character can be treated differently than a string. A string i... |
73,696,408 | 73,707,739 | How to format double as hex? | How can one format double as hex?
double t = 1.123;
fmt::format("{:x}", t);
It throws exception "invalid type specifier".
I would like to get string 3ff1f7ced916872b
| You can use std::bit_cast to cast double into an appropriately sized integer and format that in hexadecimal, e.g. assuming IEEE754 double:
double t = 1.123;
auto s = fmt::format("{:x}", std::bit_cast<uint64_t>(t));
// s == "3ff1f7ced916872b"
godbolt: https://godbolt.org/z/ehKTrMz7M
|
73,697,257 | 73,697,608 | How 0061 736d represents \0asm? | I just started to learn web assembly . I found this text
"In binary format The first four bytes represent the Wasm binary magic
number \0asm; the next four bytes represent the Wasm binary version in
a 32-bit format"
I am not able to understand this . Can anyone explain me this
| \0 is a character with code 0 (the first 00 in 00617369), the remaining three are literal characters a, s and m. With codes 97, 115 and 109 respectively, or 61, 73 and 6d in hex.
|
73,697,852 | 73,716,727 | Cannot connect to Windows server active directory lightweight service | Am working with windows server I want to create active directory lightweight service user by c++ ie, By c++ using ldap connection. My server runs in virtual box and i set the network adapter to be bridged network and it connects to the network just fine.
Now when i used the code from microsoft documentation the ldap bi... | You're asking for a container (IID_IADsContainer), but the path you give it is to the root of the domain (LDAP://ABC.local). Try specifying the distinguished name of the OU you want to put the user in. For example, if you want to put the user in the Users OU, which is at the root of the domain, it would look like this:... |
73,698,196 | 73,698,285 | Error on Operation of numbers and user input values in cpp | I am a begineer in C++ ! While playing with just learned skils i m trying to create a program that calculates your age by your Birth year passed in command line. I dont know why the program didn't even compile !
MY CODE :
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
if (argc < 2){
c... | The problem is that argc is an int, so we can't use operator[] with it.
To solve this you can use argv and std::istringstream as shown below:
int main(int argc, char *argv[])
{
if(argc < 2){
std::cout <<"Your age is 2022-<YOB>\n";
return 0;
}
std::istringstream ss(argv[1]);
int... |
73,698,496 | 73,698,900 | What's the name of all the square brackets? | In C++, we have square brackets in different places and I think it's sometimes important to distinguish them when talking to other developers. While I can call all of them "square brackets", I think they have better names, depending on what they do.
I am thinking of
array declaration, like int arr[1024];
array assignm... | (2), (3), (4) — arr[13] — It's an operator. So, "subscript operator" or "square brackets operator"? To further point out the lhs type, "{map,vector,array} subscript operator"?
(1) — int arr[1024]; — The grammar doesn't seem to have a name specifically for the brackets. The whole arr[1024] is an "(array) declarator".
M... |
73,698,528 | 73,741,651 | Import .dll for NWJS module causes '#import of type library is an unsupported Microsoft feature' | I have a legacy module for our app. It uses external dll from other software. If I run this command
nw-gyp rebuild --target=0.34.3 --msvs_version=2019 --target_arch=ia32 --arch=ia32
it produces some warnings, but compiles (where 0.34.3 is a nw.js version)
But if I run this command
nw-gyp rebuild --target=0.68.0 --msv... | Finally, I found a way to compile this module. The problem is in clang.
If I try to compile it with --clang=false option - it works perfectly.
So, if someone in the future will stuck with the same error, command for compilation should be:
nw-gyp rebuild --target=0.68.0 --msvs_version=2019 --target_arch=ia32 --arch=ia32... |
73,698,531 | 73,698,917 | C++ error: The right operand of '*' is a garbage value | I finally completed my code and when I submit it I received a couple errors. It keeps telling me
73:15 Incorrect spacing around >=.
73:31 Incorrect spacing around <=.
for this line, I've tried putting it together and no change
if (quantity >=5 && quantity <=9)
I have checked my entire code multiples times (my progr... | If you are asking why is there are The right operand of '*' is a garbage value error, I think it is because program thinks that pricePerDisc/quentity/discount are not initialized.
It happens because you are using switch(case) that is unrecommended in C++. Compiler/IDE not looking inside of switch(case) (you have initia... |
73,698,942 | 73,713,495 | Fastest way to process http request | I am currently working on creating a network of multisensors (measuring temp, humidity ect). There will be tens or in some buildings even hundreds of sensors measuring at the same time. All these sensors send their data via a http GET request to a local esp32 server that processes the data and converts it into whatever... | Creating a websocket instead of using http requests solved the issue for me:
AsyncWebSocket ws("/ws");
void setup()
{
ws.onEvent(onWsEvent);
server.addHandler(&ws);
}
AsyncWebSocketClient *wsClient;
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, s... |
73,699,355 | 73,700,725 | perfect forwarding with brace enclosed initialiser list | For personal education I am coding up a basic implementation of a hash table (although the below is probably relevant to any container that is holding types that can be list initialised) and want to use modern elements of c++ as best as I understand them - in particular in this case, perfect forwarding.
In doing so I h... | {..} has not type, and so cannot be deduced in insert.
You might work around that by providing default template type:
template<typename V = std::pair<T, U>> // default to handle {..}
bool insert(V&& entry)
{
... = std::forward<V>(entry);
// ..
return true;
}
Demo
|
73,699,502 | 73,699,593 | unique_lock same mutex in different thread | i am looking at this piece of code:
#include <chrono>
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
bool flag;
std::mutex m;
void wait_for_flag() {
// std::cout << &m << std::endl;
// return;
std::unique_lock<std::mutex> lk(m);
while (!flag) {
... |
Because right after acquiring a lock on the mutex each thread calls lk.unlock(); and now other thread can acquire a lock on the mutex. Only if a thread tries to lock an already locked mutex (by a different thread) it has to wait for the mutex to be free. As any thread in your code eventually calls lk.unlock(); there... |
73,700,117 | 73,700,231 | How to pass only selected arguments to a function? | Let's suppose I have a struct X and I want to fill out all fields depending on some conditions.
I'd like to distinguish which parameter I want to pass to a function and based on provided parameters create and then return that object. I'm curious if I should use variadic templates in c++?
Pseudo code.
#include <iostream... | You can pass parameters as std::optional and then check if it has value. Something like:
X generateTransaction(const std::optional<std::string> &e,
const std::optional<std::string> &f,
const std::optional<std::string> &g)
{
X one;
if (e.has_value())
{
one... |
73,700,142 | 73,700,755 | Can the ctor be marked noexcept based on allocator type? | How should I make sure that a constructor is noexcept if the allocator does not throw?
Here is an MRE:
#include <iostream>
#include <array>
#include <vector>
#include <memory_resource>
#include <concepts>
#include <cstddef>
template < std::unsigned_integral T, class Allocator = std::allocator<T> >
class Foo
{
std... |
First of all, I wonder why does noexcept( std::allocator<unsigned> { } ) return true?
Because constructing a std::allocator<unsigned> does not throw.
Secondly, what is the proper way of ensuring that the above class's ctor is marked noexcept if it actually never throws?
The proper way is to not mark it as noexcept ... |
73,700,469 | 73,700,518 | Pass block of statements as arguement to the function call | Consider the following example:
func(cond, block_A, block_B) {
if(cond) {
block_A; // Run all the statements in the block A
} else {
block_B; // Run all the statements in the block B
}
}
int main() {
block_A = {
y = 1;
std::cout << (y);
// statement continues ...... | You can pass callables to func and use lambda expressions:
#include <iostream>
template <typename F,typename G>
void func(bool cond, F a, G b) {
if(cond) {
a(); // Run all the statements in the block A
} else {
b(); // Run all the statements in the block B
}
}
int main() {
auto block_A... |
73,700,487 | 73,700,653 | CPP how to format strings to align to the right side | I am looking for a simple CPP solution to align a string to the right size.
What do I mean by this?
here is an example:
the normal output would be
hello [message]
foo [message]
I would like it to output like this:
hello [message]
foo [message]
note: this is not for aligning a table but rather to know how to align... | Like this ?
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setw(10) << "Hello" << " [message]" << std::endl ;
std::cout << std::setw(10) << "foo" << " [message]" << std::endl ;
}
|
73,701,833 | 73,742,038 | What is the optimal way to synchronize frames in ffmpeg c/c++? | I made a program that read's n number of video's as input, draws those videos to the GLFW window and finally encodes it all as a singular video output. The problem is frames of each video in question can be different, it's dependent on the user's input.
For example: the user can put two video's which has an FPS of 30 a... | For those who are struggling in a similar situation: The problem was my encoder's time base: I was passing it as an int rather than a formatted AVRational. My fps variable was a float, and when I pass that to my encoder it rounds it to the closest integer. As an example I was passing 23.797 and it rounded to 23. So wha... |
73,701,904 | 73,702,893 | float outputs differently in different consoles | I am running the same OpenGL executable in CLion and cmd, but they show different outputs. CLion shows the right number, cmd shows inf and sometimes the number. cout does the same.
(I've mitigated all ogl calls from the code since they're unnecessary)
The code to that is:
int i = 0;
auto lastTime = std::chrono::high_re... | As Peter pointed out, the problem is that some iterations take less time than the resolution of the clock being used and that time in turn depends on the environment where the program is executed.
A solution to such problems could be to measure the time for X iterations (10000 in the following example) and then calcul... |
73,702,189 | 73,702,247 | Template a member variable in a class | I am doing some refactoring on some older/messy code. I am trying to improve things little by little. Because it fit the project, I started implementing CRTP (for static polymorphism) on some class, let's call it sensor. Through CRTP, there is now a real and a fake implementation.
Now, I am trying to put templates in ... | you can use std::conditional_t:
class interface_actions
{
std::conditional_t<SOMETHING, sensor<real>, sensor<fake>> _detector;
};
if SOMETHING yields true, _detector will be of type sensor<real>, sensor<fake> otherwise.
but this only works if SOMETHING is outside of the scope of class interface_actions, otherwise... |
73,702,736 | 73,702,935 | C++ implicit cast - How to force a warning | I am following a C++ training and I found out a behavior I find weird in C++ when learning about explicit keyword.
About the following snippet, it will compile and execute without any error or warning (compile with G++).
When calling Foo(5), it will automatically do an implicit conversion and actually call Foo(A(5)).
I... |
Is there a way to make G++ warn about implicit casts like that if I forgot to do so?
No, the fact that you have a choosen to have a non-explicit conversion constructor says that you want implicit conversion from int to Foo allowed.
If that is not desirable, then you always have the option of making this converting ct... |
73,703,378 | 73,718,381 | Yaml node.size() returns 0 | I've been experimenting with serialization and to get the hang of it I made a simple Test. I first call a function to Serialize my custom Color struct (a simple struct having the == operator and floats for r, g, b, and alpha values), this works, I can look into the file on my computer and the values are there:
YAML... | Your code constructs the following YAML:
- Material
- color: [1, 2, 3, 4] # don't know the actual values
You can't do data["color"] on this structure because the root node is a sequence. Do
data[1]["color"]
instead.
|
73,703,496 | 73,703,817 | Show video while saving it | I have a folder full of images, I need to save these images into the video while doing so I want to show the user the video being played from these images (frames). I can run two separate processes one for the saving and one for the showing but this is not what I am looking for, I want to do both in one step. If you kn... | here's my quick brew using SFML. You have to link SFML and include the include folder. Simply set directory to your target folder, I use std::filesystem to add all files from that folder to a std::vector<std::string>.
#include <SFML/Graphics.hpp>
#include <vector>
#include <string>
#include <iostream>
#include <filesys... |
73,703,611 | 73,706,601 | print callstack on every C++ exception throw in lldb | I'm using lldb and I'd like to catch all C++ based exceptions and print the callstack of the current thread for each breakpoint automatically, and continue.
This will stop on all exceptions break set -E C++, but how can set an automation that will print the callstack (bt command) and automatically continue?
Thnaks
| These are all available as options to the break set command (see help break set for even more options). You want:
break set -E C++ -G 1 -C "bt"
You can also change the commands on a breakpoint after creation with the breakpoint command add command.
|
73,703,746 | 73,703,833 | Is there a way for a class template to deduce the size of a parameter pack passed to the constructor? | If I have a class template like such:
template<typename T, size_t N>
struct foo
{
template<std::same_as<T>... Ts>
foo(Ts... ts);
}
Is there any way whatsoever to deduce the template parameter N from the size of the parameter pack passed to the foo constructor? So that foo can be instantiated like so:
auto f = ... | Yes, a deduction guide for this is straight-forward:
template<typename T, typename... Ts>
requires (std::same_as<T, Ts> && ...) // optional
foo(T, Ts...) -> foo<T, sizeof...(Ts)+1>;
or
template<typename T, std::same_as<T>... Ts>
foo(T, Ts...) -> foo<T, sizeof...(Ts)+1>;
|
73,704,628 | 73,704,736 | Why is the destructor of a function parameter not called at the end of the function, but at the end of the full expression making the function call? | Consider the following example:
#include <iostream>
struct A
{
int n = 0;
A() { std::cout << "A()" << std::endl; }
A(const A&) { std::cout << "A(const A&)" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
};
int f(A a) { std::cout << "f()" << std::endl; return 1; }
int main()
{
A a;
... |
Why is destructor for a function parameter not called at the end of the function but at the end of the full expression containing the function call?
According to [expr.call]/7
It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the ... |
73,704,733 | 73,704,827 | Deducing type of template value parameter | I was wondering if the type of a value template parameter could be deduced or obmitted when writing something similar to this:
enum class MyEnum {A, B}
enum class MyOtherEnum {X, Y}
template <typename T, T value>
struct GenericStruct {};
When using MyGenericStruct both T and value have to be passed, but T would be d... | If you can use C++17, you can use auto as the type of the non-type template parameter. That gives you
template <auto value>
struct GenericStruct {};
Now, value will have its type deduced by its initializer just like if you had declared a variable with type auto and gives you the desired syntax of GenericStruct<MyEnum... |
73,704,804 | 73,836,415 | Adjust translation speed of QML DragHandler | my question is about using a QML DragHandler to move a QML Item. I have successfully implemented position through dragging (when holding the Ctrl modifier) like so:
DragHandler {
dragThreshold: 0
acceptedModifiers: Qt.ControlModifier
}
Now I would like to add another handler that allows me to precisely positio... | Unfortunately Qt doesn't provide any way to change the drag speed AFAIK.
But this is a way to achieve it:
Rectangle
{
id: theDraggableElement
width: 100
height: width
color: "red"
DragHandler
{
id: dragHandlerFast
dragThreshold: 0
acceptedModifiers: Qt.ControlModifier
... |
73,705,774 | 73,705,841 | How can std::reference_wrapper<int> use operator+= if std::reference_wrapper doesn't have operator+=? | Thank you all, I didn't even know about user-defined conversion function and how it works.
Why is it possible to use std::reference_wrapper<int>::operator+=, if such an operator does not exist, are there some implicit conversions?
#include <iostream>
#include <functional>
#include <boost/type_index.hpp>
using boost::... | It's because it's implicitly convertible to a reference to T:
/* constexpr [c++20] */ operator T& () const noexcept;
In your case, it's implicitly convertible to an int&.
This ability to be implicitly convertible to an int& is also what would make it possible for you to define your function to take an int& while pass... |
73,706,697 | 73,706,809 | Difference between template specialization and SFINAE with std::enable_if? | If I have a template function in C++, and want it to behave in a different manner in presence of a specific template parameter, I will use a template specialization:
#include <iostream>
#include <type_traits>
template<typename T> void myFunction(T&& input) {
std::cout << "The parameter is " << input << '\n';
}
te... | These 2 approaches are executed on different stages.
First is overload resolution - on this stage template specialization is not used. Only generic template function prototype is in use.
On the other hand SFINAE approach drops the overloads that failed to be substituted silently on this stage leaving only one candidate... |
73,706,974 | 73,707,256 | When using VS2022 (v17.0.1.0), the complier can not recognize "string", and sends me an error. When I replace the string by const char*, it works | I have tried searching on Google, only to find nothing.
And it seems the manual also doesn't work.
Here is my code:
account.h
#include <string>
#include "Date.h"
class SavingsAccount
{
public:
void show();
void deposit(Date now_date, double money, string ways);
void withdraw(Date now_date, double m... | In account.h, you have #include <string>, but you do not have using namespace std; (and rightly so), so the compiler doesn't know what string is. You have to use std::string instead, eg:
void deposit(Date now_date, double money, std::string ways);
Or, use using std::string, at least (not recommended in a header, thou... |
73,707,192 | 73,707,735 | C++ - Pass member functions of any class to another class | I am in the process of writing a template class that would implement a Listener interface for every component that would need it within my application. I want a component to be able to listen to changes to an individual field within a listened object. The fields of each object are represented by an enum, and I've got a... | Use std::function<void()>
Here's a somewhat simplified version of your AbstractNotifier that will accept callbacks from any class (or no class at all):
template <typename EFieldsEnum>
class AbstractNotifier
{
public:
void addListener(EFieldsEnum listenedField, std::function<void()> listenerCallback)
{
l... |
73,707,348 | 73,707,521 | Meaning of "->second" and self-made comments | I am trying to write a description of each of the actions in the code by commenting on things performed in the code.
Could you please help me understand what does "createdCode->second" do and re-check if my made comments about the other parts are correct?
Here is the code:
#include <map>
#include <string>
#include <i... | find returns an iterator. When you are confused by types, I suggest to stay away from auto for a moment. auto is not to ignore what the actual type is (at least to my understanding).
std::map<char,std::string>::iterator iter = natoAlphabet.find(ch);
If find cannot find the element then it returns natoAlphabet.end(), t... |
73,708,226 | 73,708,435 | gst_parse_launch there is no proper conversion function from string to gchar | I have a simple code with c++ using gstreamer to read rtsp video.
I'm new to gstreamer, I couldn't concatenate gst_parse_launch() with a URL_RTSP variable for my rtsp links.
here is no variable URL_RTSP, that works:
/* Build the pipeline */
pipeline = gst_parse_launch("rtspsrc protocols=tcp location=rtsp://user:pas... | gst_parse_launch takes a const gchar* as the first argument:
GstElement* gst_parse_launch (const gchar* pipeline_description, GError** error)
But, what you provide,
"rtspsrc protocols=tcp location="+ URL_RTSP +
" latency=300 ! decodebin3 ! autovideosink"
results in a std::string. I suggest creating the std::string f... |
73,708,679 | 73,709,470 | How to properly wrap a two dimensional vector using %template | I'm trying to make a basic csv parser in c++ for a particular csv schema, and I'm trying to wrap the function for Python, but I keep getting a "StdVectorTraits not found" warning after wrapper generation. The wrapper is still able to be compiled using g++, but when I try to import the underlying shared object using the... | The function definition should be between %{ and %}. Everything between %{/%} is included directly in the generated wrapper. The function prototype should be at the end of the file after the %template declarations to direct SWIG to generate a wrapper for that function.
Since the function body is in the wrong place it... |
73,708,720 | 73,709,559 | Call a non-default constructor for a concept | I am making a dependency injection system via static polymorphism with C++20 concepts, so I have this example
I have an interface contract for a Logger:
template <typename TLogger>
concept ILogger = requires(TLogger engine) {
{ engine.LogInfo(std::declval<std::string>()) } -> std::same_as<void>;
{ engine.LogErr... | You could take an instance of the logger as a parameter:
template <ILogger L>
class DatabaseAccessor
{
L logger;
public:
explicit DatabaseAccessor(L logger) : logger(std::move(logger)) { }
};
If you need something more involved than this (like your logger isn't move-constructible), then instead of taking an L... |
73,709,270 | 73,709,334 | Template type deduction C++ | I am getting an error qualified-id in declaration before ‘<’ token from the following code:
// g++ -std=c++20 example.cpp
#include <iostream>
template <typename U = int>
struct Example {
template <typename T>
static void execute() {
std::cout << "Hey" << std::endl;
}
};
int main() {
Example::e... | Class template argument deduction only applies when creating objects.
That is Example e; will deduce Example<int> e; via the default argument.
You are not creating an object though, and Example is not a class. You must include a template argument list. In this case, it can be empty though, since the template argument... |
73,710,730 | 73,712,997 | How can both CRect and CRect* be input arguments to GetClientRect? | Beginner question.
In Win32API, the second parameter of ::GetClientRect is LPRECT, but It receives both CRect and CRect*.
I tried to see how LPRECT is defined, but it seems just an ordinary pointer to struct:
typedef struct tagRECT
{
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT, *PRE... | During overload resolution1 the compiler builds a set of candidate functions that match the arguments. If none of the functions' signatures exactly match the arguments the compiler will then try to apply implicit conversions, at most one per argument.
That's what makes both calls possible, though the implicit conversio... |
73,711,949 | 73,712,373 | Object created in Python via Pybind11 not recognized as a derived class by C++ functions | The minimum code to reproduce the issue is as follows:
aaa.hpp
#include <string>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <cmath>
#include <cassert>
#include <utility>
template <typename D>
class BaseClass{
/* The base class. */
protected:
bool skip_nan = true;
};
template <typenam... | You need to declare BaseClass<float> in Python and tell pybind11 that DerivedClass_float extends it.
PYBIND11_MODULE(MyModule, m)
{
m.def("fff_float", &fff<float>);
// declare base class - this simply expose to Python, it's impossible to
// construct a BaseClass_float in Python since no constructor is prov... |
73,712,346 | 73,712,400 | Why is the c++ program outputting a wrong negative number | #include <iostream>
int main() {
int woe; // weight on earth
int wom = woe * 2; // weight on mars
std::cout << "Enter your weight on earth: \n";
std::cin >> woe;
std::cout << "Your weight on mars would be " << wom << " Pounds\n";
}
Hello everyone I just started to learn c++ and when I try to mul... | When you just define an integer variable without assignment in C++ it takes a random number, then you are just doubling that random number in wom variable and after that you take input. A more correct version of your code is:
#include <iostream>
int main() {
int woe = 0; // weight on earth
std::cout << "Enter you... |
73,712,592 | 73,712,706 | Why unordered_map not showing correct index values of a vector? | I have a string "codeforces" and now when i am storing characters of this string as key in an unordered map and index of occurrence of that character in a vector inside unordered map as value , then it is not showing correct indexes .
In this string "codeforces" character 'c' is occurring at index 1 and 8 , i would lik... | your for loop has a wrong range. You start at element 1 and because of <= only stop at the size of codeforces + 1, which is out of bounds.
When iterating arrays the index starts at 0 and should end at size() - 1. This can be easily achieved by saying < size() as the less operator will result in false if the index is at... |
73,713,812 | 73,714,056 | Open with linux context menu opens the app twice QT | I have done the command line processing in my QT application so I can set it as default for audio files. But while I try to open an audio file with my QT application again, it opens a new window.
Is there a way to make it so it opens the new file in the same window, if that file is open from a file manager with my appl... | write a file whenever your app starts. Proceed or exit according to the contents of the file.
or try make your app single instance?
https://github.com/itay-grudev/SingleApplication
|
73,713,872 | 73,714,245 | How to use 'std::enable_if_t' inside templated class, without introducing second template argument | I have a 100% working code, of Vector wrapper which does resizing differently for various types of vectors. However, when defining std::enable_if_t, I use
template <typename C = Vec>
instead of using 'Vec' directly. Is there a way to reuse template argument 'Vec' of the class for its resizeListTo() method?
Full code:... | In C++20, you have requires to add constraint to the method:
template <class Vec>
class MyVectorWrapeer<Vec>
{
private:
static void resizeListTo(Vec& c, uint32_t size) requires(someCondition<Vec>)
{ /*Some Code*/ }
static void resizeListTo(Vec& c, uint32_t size) requires(!someCondition<Vec>)
{ /*Different Code*... |
73,714,507 | 73,715,515 | how to derive a class (from e.g. Eigen::VectorXf) with (only) an extra static method while retaining all the base constructors? | Let's say I need to attach some 'type id' to my Eigen::VectorXf vectors.
So far I have something like this (simplified for brevity):
struct MyVector123
{
Eigen::VectorXf vec;
static int id() {return 123};
};
struct MyVector456
{
Eigen::VectorXf vec;
static int id() {return 456};
};
(Please don't argu... | You need to inherit the constructor (c++ 11)
struct MyVector123 : public Eigen::VectorXf
{
using Eigen::VectorXf::VectorXf;
static int id() {return 123};
};
|
73,714,725 | 73,715,012 | Application crashes if (own) dll try to allocate a few MB of RAM | I'm not a good c++ programmer and I'm not very familiar creating DLLs for other application. My main programming language is Java so I'm having a little trouble with coding c++ and compiling with MinGW. However, as we need some small portion of "native" code for our main application (which is coded in Cobol) I was need... | Yes, that's a stack allocation (and not legal C++ either).
Simple fix is to use a std::string
#include <string>
...
std::string buf
buf.resize(size);
...
return b64_encode(buf.data(), size);
No other code changes needed. Although you could make further changes to use std::string throughout your code, instead of using... |
73,714,951 | 73,715,265 | Why do references to moved values not dangle after the lvalue that the object was moved into goes out of scope? | While playing around with references to lambdas I encountered a scenario where I expected the program to crash due to dangling references. In the following program, I assumed that the lambda argument to fn_x_3 in main is "moved to" the fn_x_3 function because it's an rvalue, where it binds to the lvalue fn.
#include <i... | It does, pretty much second function overload fn_x_3 is ok BUT if you use the return value in any way outside the scope of the function you are invoking UB by using object past its lifetime (the object is the underlying lambda structure of first fn_x_3 overload).
It is not enforced by the C++ compiler to block compilat... |
73,715,505 | 73,715,765 | Implicit conversion of initializer lists and perfect forwarding | I'm trying to make perfect forwarding work with initializer lists. For the sake of the example, I'd like to have a variadic function that calls into another function, and still enjoy automatic conversion of initializer lists of the latter:
#include <iostream>
#include <vector>
void hello(std::string const& text, std... | The compiler is not able to recognize the type you are sending in the third case.
If you use
f("world", std::initializer_list<int>{1,2,3});
everything works.
This post has some detailed explanation and quotes the relevant part of the standard. It is for a slightly different case but the explanation still applies.
|
73,715,574 | 73,716,007 | Data distribution fairness: is TCP and websocket a good choice? | I am learning about servers and data distribution. Much of what I have read from various sources (here is just one) talks about how market data is distributed over UDP to take advantage of multicasting. Indeed, in this video at this point about building a trading exchange, the presenter mentions how TCP is not the op... | The argument on fairness due to looping, in code, is ridiculous.
The whole field of trading where decisions need to be made quickly, where you need to use new information before someone else does is called: low-latency trading.
This tells you what's important: reducing the latency to a minimum. This is why UDP is used ... |
73,715,880 | 73,716,439 | How do I fix the second value of insertion sorting in tuple to work as well with the first value | Basically, I am trying to do Insertion Sorting on a tuple which is stored inside a vector, and I have a function to do it, when I only use the first value (get<0>(tupleVector[i])) it works, but when I try to add the second value (get<1>(tupleVector[i])) it doesn't, here's the whole function code.
void sort(vector<tuple... | Assuming you intend a lexicographical comparison then your comparison operator fails to do so.
Assume you want to compare ordinary strings lexicographically:
Your operator would then accept xx as smaller to zz, as both characters in first string are smaller than the ones in second string – however this requirement fail... |
73,716,490 | 73,716,707 | Translating Swift enums with associated values to C++ | In Swift you can have an enum type with associated values.
enum Thing {
case num(Int)
case two(String, Double)
case other
}
var t: Thing = .num(123)
t = .two("a", 6.022)
t = .other
From what I'm reading, you can can do a similar thing in C++ by using std::variant. It has less syntactic sugar.
But the compile... | Because void cannot be instantiated, you'll need some stand-in type to represent void.
You could make your own, struct void_t{};, or you could use the std::monostate which is provided in C++17 and later.
|
73,716,618 | 73,720,092 | flutter doctor ~ VS Code "Desktop Development in C++" error | The Flutter Doctor is showing this error:
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https:// visualstudio. microsoft .com /downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
I... | VSCode and Visual Studio are two different software by the way :)
|
73,716,747 | 73,716,804 | Universal reference deduction using the same_as concept | I'm trying to implement a push function for a blocking queue which accepts a universal reference as it's template parameter, but requires that the template argument be the same type as the queue's element type:
template <typename ValueType>
class shared_queue
{
public:
template <typename Arg>
requires std::... | You need to remove_reference from Arg for same_as to consider the int& to x and int the same type. You may also want to remove const in case you have const int x and pass that as a parameter. Removing both (+ volatile) can be done with std::remove_cvref_t:
template <typename Arg>
requires std::same_as<std::remove_c... |
73,716,757 | 73,718,009 | How to specify a fractional framerate with ffmpeg C/C++ when stitching together images? | I want to specify fractional frame rate's like 23.797 or 59.94 when creating my encoder. Here is how I do it currently:
AVStream* st;
...
st->time_base = (AVRational){1, STREAM_FRAME_RATE };
But looking at ffmpeg's source code at rational.h we can see that AVRational struct takes int's instead of float's. So my 23.797... | As per the comment, you can make use of av_d2q from the libavutil library. By way of a basic example...
#include <iostream>
#include <limits>
extern "C" {
#include <libavutil/avutil.h>
}
int main ()
{
auto fps = 23.797;
auto r = av_d2q(1 / fps, std::numeric_limits<int>::max());
std::cout << "time base is " << ... |
73,717,088 | 73,717,248 | Cin input of multiple lines not iterating correctly | I came from C so I'm trying to understand C++ input.
I want to read lines of input like so:
3
0 0 1 0
1 4 0 1
0 1 2 3
where 3 is the number of input lines I'm going to read next. My code is
#include<iostream>
#include<string>
int main() {
int n, k = 8;
std::cin >> n;
char lines[n][k];
for(... | you are trying to create variadic length arrays, they are not a part of standard C++.
You should be using a combination of std::vector and std::string:
#include <iostream>
#include <string> //std::string, std::getline
#include <vector>
int main() {
int n;
std::cin >> n;
std::cin.ignore();
std::vector<... |
73,717,296 | 73,717,490 | concept constraints don't apply | I've the following code
#include <cstdint>
#include <concepts>
template <class T>
concept has_id = requires(T) {
T::Id;
std::same_as<uint8_t[16], decltype(T::Id)>;
};
The has_id concepts ensure that a type has the member Id with type uint8_t[16].
However, when writing the following example it works even thoug... | template <class T>
concept has_id = requires(T) {
T::Id;
std::same_as<uint8_t[16], decltype(T::Id)>;
};
Confirms that the expression T::Id compiles, and that the expression std::same_as<....> compiles. It doesn't check whether the latter is true or false.
You can just write
template <class T>
concept has_id = ... |
73,717,892 | 73,718,075 | Stop input loop when input is done | std::cin | I want to write a function that gets a set of integers and saves them to a vector.
To get the integers I'm using a while loop.
Enter the vector elements: 1 2 3 4 5
I want the loop to stop looking for input after the last element is inputted or until a non-numberis inputted, however I'm having trouble with it.
It is an ... | If your intention is to get all the input from a given line, and add individual numbers to the vector, then you want to read a line of input into a string, then use an istringstream to process that line of input.
A simplified example:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.