question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,918,614 | 70,918,933 | Sorting a ring buffer class objects | I am trying to make a sorting function for a ring buffer class object, but it gives me the below error and I couldn't remove it:
template placeholder type 'ring' must be followed by a simple declarator-id
argument list for class template "ring" is missing
'arr' was not declared in this scope
(arr) was declared in... | Your friendly compiler showed you already the problem and in which line it happened.
And it gave you 3 error messages telling you exactly what the problem is.
See my compiler output
Your class ring needs a template parameter. So same as in line 49 of the picture.
The below will compile.
#include<iostream>
#include<ini... |
70,918,658 | 70,918,679 | Printing text on screen Unreal Engine C++ | how can i print not debug text (GEngine->AddOnScreenDebugMessage (-1, 5.f, FColor::Red, FString::Printf(TEXT(""));) on screen in unreal engine?
| You'd need to use a widget with text then be able to spawn the widget or always have it open in your level. Create a Widget blueprint and simply add a textbox.
|
70,918,786 | 70,918,928 | Partial specialization tempate c++ | I was exploring the JUCE framework and find this interesting code,
namespace SampleTypeHelpers // Internal classes needed for handling sample type classes
{
template <typename T, bool = std::is_floating_point<T>::value>
struct ElementType
{
using Type = T;
};
template <typename T>
struc... | Look at this function declaration:
void frob(float f, bool g = true) {
// ...
}
As you might know, you can drop parameter name from declarations:
void frob(float f, bool = true) {
// ...
}
You can also set the default value using an expression. This is equivalent as the previous example:
void frob(float f, bo... |
70,918,879 | 70,920,090 | How can a vector of integers hold objects if an integer is not a class? | While I was reading C++ primer fifth edition I came across this definition of a vector:
A vector is a collection of objects, all of which have the same type.
Every object in the collection has an associated index, which gives
access to that object. A vector is often referred to as a container
because it “contains” oth... |
If I have a vector of integer values then what class do all these objects belong?
No class at all. The elements of a vector of integers are objects of the integer type. Integer types are fundamental types.
|
70,918,947 | 70,919,387 | Construct n-dimensional boost point | Problem:
boost/geometry/geometries/point.hpp point template does not provide a way to construct an n-dimensional point type with non-zero values.
For example:
#include <boost/geometry/geometries/point.hpp>
namespace bg = boost::geometry;
...
typedef bg::model::point<double,4,bg::cs::cartesian> point;
auto nDimPoint1 ... | You are right. The model::point class template doesn't afford direct/aggregate initialization and it's not possible to add that (m_values is private e.g., but also there is optional access-tracking debug metadata that would get out of sync).
Note the class is documented
\details Defines a neutral point class, fulfilli... |
70,919,228 | 70,919,291 | Do you always have to declare a default constructor and destructor for unions containing members with user-defined default constructor? | This class containing a union:
struct foo
{
union
{
std::vector<int> vec;
int i;
};
};
cannot be instantiated. If I try, the compiler throws an error saying 'foo::foo(void)': attempting to reference a deleted function. To get it to work, I have to add an empty constructor and destructor to ... |
It seems silly to write an empty constructor and destructor for ...
Not only silly, but actually wrong.
Why [does the compiler doesn't generate one and you need to]?
A union doesn't know which of its members is active. As such if at least one of its members has a non-trivial special method the union can't generate ... |
70,919,341 | 70,919,406 | Declare reference member variable that you won't have at instantiation | Coming from Java, C++ is breaking my brain.
I need a class to hold a reference to a variable that's defined in the main scope because I need to modify that variable, but I won't be able to instantiate that class until some inner loop, and I also won't have the reference until then. This causes no end of challenges to m... |
Declare reference member variable that you won't have at instantiation
All references must be initialised. If you don't have anything to initialise it to, then you cannot have a reference.
The type that you seem to be looking for is a pointer. Like references, pointers are a form of indirection but unlike references,... |
70,919,881 | 70,919,924 | Pointer being freed was not allocated - destructor | Slowly learning about copy/move constructors, rule of 5 etc. Mixed with not-so-well understanding of usage of pointers/reference, I cannot understand why my destructor throws the error below. I know that it's caused by destructor and destructor only, and after the copy constructor.
untitled(19615,0x104a60580) malloc: *... |
I cannot understand why my destructor throws the error below. I know that it's caused by destructor and destructor only
account f(3);
The constructor of this object allocates an array.
account n(f);
The copy constructor that you wrote copies the pointer that points to the dynamic array.
n is destroyed first. It... |
70,919,957 | 70,920,041 | How can I build two executables that share a main function in CMake? | I have a project that's becoming large enough that I want to switch to from a plain Makefile to CMake. My project contains only one application, but supports two different boards (each board has a set of source files, and some defines specific to the board). The (simplified) project structure currently looks like this:... | You already have a src/CMakeLists.txt, so you are part of the way there. Put your overall build settings -- dependencies, C standard version, global compiler flags -- in the top-level CMakeLists.txt. In the subdirectories, put only your CMake commands for the executables, or whatever target makes sense locally.
(As an ... |
70,920,100 | 70,921,790 | Errant segments in cellular automata encryption algorithm | I've been implementing a paper that is targeting IoT encryption using a 64-bit block cipher via elementary cellular automata. The paper is in the repository/linked in the README.
I am trying to verify that an implementation of this algorithm actually works.
Current state
The first and third segments do not decrypt prop... | After iterating through all automata rules, only linear rules work in place of 153 for alternating segments. Rule 29 appears to be the best alternate for diffusion of the plaintext.
RULE 29
P: deadbeefcafebabe
K: f6c78663f3578746
E: ce09bfd34be8a898
D: deadbeefcafebabe
RULE 51
P: deadbeefcafebabe
K: f6c78663f3578746
E:... |
70,920,106 | 70,920,312 | libao: os_types.h.in not converted to os_types.h by autoreconf | I am using libao in my C++ code. To set up the build system, I run the autogen.sh script (which uses autoreconf) in the repo. It works, but the os_types.h.in in include/ao/ doesn't get converted to os_types.h.
os_types.h is needed because when I try to include #include <libao/include/ao/ao.h> the compiler says that it... | Turns out that I needed to run ./configure and then make and I had the os_types.h file. Answer found from: Can't run Makefile.am, what should I do?
|
70,920,136 | 70,920,209 | Get default argument value from a function call c++ | Code will probably better explain my problem better than words:
#include <string>
struct Something {};
struct Context
{
std::string GetUniqueInentifier()
{
return "";
}
// ERROR
void Register(const Something& something, const std::string& key = GetUniqueInentifier())
{
}
};
int... | You can't use non-static member functions or variables as a default value to member functions.
Since the value returned by GetUniqueInentifier() doesn't require an instance of Context, make it static and you can then use it as you tried using it.
static std::string GetUniqueInentifier()
{
return "";
}
|
70,920,177 | 70,920,200 | How to remove extra space in output of code? | Help! I am trying to print my code is giving the correct output BUT with an extra space that is not supposed to be there.
for (int i = i; i <= input; i++)
{
cout << factorial(input)/ (factorial(i) * factorial (input - i)) << " ";
}
return 0;
}
| Dont pad with space at the end on the last element
for (int i = 1; i <= input; i++)
{
cout << factorial(input)/ (factorial(i) * factorial (input - i));
if(i < input)
cout << " ";
}
|
70,920,272 | 70,920,327 | QObject::connect: No such slot QMainWindow::On_clicked_delCare() in ../Gestion_parc_auto/choice_page_2.cpp:91 | oplease, help me to solve this probleme. I don't know the proble but if I put QObject in file.h he generate error !
file.h
#include <QMainWindow>
class choice_page_2 : public QMainWindow
{
public:
choice_page_2();
QWidget* M_Widget = new QWidget();
public slots:
void On_clicked_delCare();
};
#end... | All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration.
|
70,920,364 | 70,920,850 | cmake to link to dll without lib | I've been given a dll without libs.
The dll comes with hpp and h files.
I used dumpbin to create an exports.def file and lib to create a library.
I'm using the following CMakeLists.txt
cmake_minimum_required ( VERSION 3.22 )
project ( mytest )
include_directories("${PROJECT_SOURCE_DIR}/libincludedir")
add_executable... | Assuming that you created the .lib correctly, this is how you would set up something linkable:
cmake_minimum_required(VERSION 3.22)
project(example)
add_library(anewlib::anewlib SHARED IMPORTED)
set_target_properties(
anewlib::anewlib
PROPERTIES
IMPORTED_IMPLIB "${PROJECT_SOURCE_DIR}/libincludedir/anewlib.lib"
... |
70,920,935 | 70,924,135 | is there a "semi-pure" virtual function in c++? | Is there a way to write an abstract base class that looks like it's forcing an implementer to choose among a myriad of pure virtual functions?
The abstract base classes I'm writing define a mathematically tedious function, and request that the deriving code define only building block functions. The building block funct... | Not sure it matches exactly what you want, but with CRTP, you might do something like:
template <typename Derived>
struct MulBy3
{
template <typename... Ts>
int final_result(Ts... args) { return 3 * static_cast<Derived&>(*this).first(args...); }
};
class derived : public MulBy3<derived> {
public:
int first... |
70,921,546 | 70,924,267 | Overloading operators with multiple member fields | I'm trying to overload different operators, such as >, +=, -=, >=, but for some reason I keep getting same error, expression must be bool type (or be convertable to bool)
Example
Money operator>=(const Money& lhs, const Money& rhs)
{
return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
}
I've also tried
Money op... | return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
is parsed as
return lhs.pounds, (rhs.pounds >= lhs.pence), rhs.pence;
so is equivalent to
return rhs.pence;
std::tie is the way to go (in general case), but you don't use it correctly (and your return type is wrong). It should be
bool operator < (const Money& lh... |
70,921,684 | 70,921,711 | Python libclang how do you use a compilation database? | This has been asked twice already one answer seems very popular:
How to use compile_commands.json with clang python bindings?
This other one not as much:
How to use compile_commands.json with llvm clang (version 7.0.1) python bindings?
However neither solution seems to work. If you try the most popular solution, i.e. i... | The correct way seems to be doing this:
index = clang.cindex.Index.create()
token_dict = {}
compdb = clang.cindex.CompilationDatabase.fromDirectory('/home/makogan/neverengine_personal/build/')
commands = compdb.getCompileCommands(path)
file_args = []
for command in commands:
for argumen... |
70,921,712 | 70,921,762 | Finding GCD and LCM giving correct output for some test cases but my submission shows wrong answer | My c++ code of finding gcd and lcm is giving correct output for some test cases but my submission shows wrong answer.
int T;
cin>>T;
int x,y,a,b;
while(T--)
{
cin>>x>>y;
a=(x>y)?x:y; // a will be the greater number
b=(y>x)?x:y; // b will be the smaller number
int product=a*b;
///we will find... | There are few cases on which it might fail:
When numbers x and y are not able to fit in int data type.
What if either x or y = 0?
You are doing product = a*b. This also can lead to overflow resulting wrong output in else part.
|
70,921,779 | 70,921,836 | C++ template function to concatenate both std::vector and std::array types | I have project where I am working with both fixed and variable length arrays of bytes. I want to have a function that can concatenate two arbitrary containers of bytes and return a single vector. Currently I am using
std::vector<uint8_t> catBytes(uint8_t const* bytes1, size_t const len1,
... | In general, generic + arbitrary, means templates.
Something like this?
template<class SizedRange1, class SizedRange2>
auto concat(SizedRange1 const& r1, SizedRange2 const& r2) {
std::vector<typename SizedRange1::value_type> ret;
ret.reserve(r1.size() + r2.size());
using std::begin; using std::end;
ret.... |
70,922,092 | 70,922,192 | Bitwise right shift operator >> didn't worked as intended | I am writing a code to find the number of ones in binary representation of a number
here is the code:
int main(void)
{
int n,tNum,count = 0;
cin >> n;
tNum = n;
while(tNum > 0)
{
int i = 0;
int bit = getBit(n,i);// get bit
if (bit == 1)
{
count++;
}
... |
Bitwise right shift operator >> didn't worked as intended
The bitwise right shift operator >> is working as intended but you are not storing the result of >> operator anywhere. This expression
tNum >> 1;
will right shift the value of tNum by 1 but the result of this expression is unused.
Use >>= operator instead of ... |
70,922,215 | 73,900,773 | Debugging CMake Visual Studio project with PATH environment set by VS_DEBUGGER_ENVIRONMENT | I've created a CMake project using visual studio 2019. It has one executable target, which links to some shared libraries (DLL). I cannot directly set the system environment variable PATH because the DLL path is determined by find_package. Therefore, set VS_DEBUGGER_ENVIRONMENT target property is my choice to debug tha... | This is just to share what I finally ended up with after some painful hours of digging through the web.
First, a variable to store the required debugging paths is needed (example):
list(APPEND VS_DEBUGGING_PATH "%PATH%")
list(APPEND VS_DEBUGGING_PATH "${PostgreSQL_ROOT}/bin")
The next step is to create a ${CMAKE_PR... |
70,922,277 | 70,922,338 | Kth smallest element in a array | I was writing this code for finding Kth smallest element in array where l= starting index and r = ending index is given to us as input parameter in function.
class Solution{
public:
int kthSmallest(int arr[], int l, int r, int k) {
//code here
arr.sort(l,l+r+1);
int count =1,i=1,var =0;
... | arr is type int *, so a primitive type and a primitive type don't have any member function. So arr don't have any sort() member function, so it cause an error.
If you want to sort arr, use std::sort from <algorithm>.
std::sort(arr + l, arr + r + 1);
|
70,922,356 | 70,922,377 | Why I can pass a number to function which accepts const reference? (C++) | I'm new to C++, while I'm learning pass by reference I realized that I can't create a reference to a number directly, it has to be a variable. But if I define a function which accepts const reference, I can pass numbers in it.
int SumVal(const int& a, int b)
{
return a + b;
}
As far as I understand, I can pass a n... | Yes. It's because a const reference can bind to an r-value, but normal reference can't
|
70,922,392 | 70,922,445 | Performance of std::vector::swap vs std::vector::operator= | Given two vectors of equal length:
std::vector<Type> vec1;
std::vector<Type> vec2;
If the contents of vec2 need to be replaced with the contents of vec1, is it more efficient to use
vec2.swap(vec1);
or
vec2 = vec1;
assuming that vec1 will remain in memory but its contents after the operation don't matter? Also, is t... | swap will be more efficient since no copy is made. = will create a copy of vec1 in vec2, keeping the original intact.
If you check the documentation, you'll see that swap is constant while = is linear.
|
70,922,624 | 70,923,186 | What approach should I use in this question? approach I used below is not getting accepted | IPL Auctions are back. There are n players who will go under hammer in the sequence. There prices are given in a form an array in the order. A team wants to buy as much as player they can, but they have a condition that, they can only buy the current player if and only if the price of their last buyed player is less th... | Inner for loop logic that have been used is wrong because the k-th index should always be the last player you have bought in the Auction, instead you are incrementing k-value instead of using the last bought player index.
We can implement below algorithm for this problem:
"We will always have two options during auction... |
70,922,705 | 70,922,782 | How I can write a monotonic allocator in C++? | I'm trying to write a very simple monotonic allocator that uses a fixed total memory size. Here is my code:
#include <map>
#include <array>
template <typename T, size_t SZ>
class monotonic_allocator
{
public:
using value_type = T;
monotonic_allocator() noexcept {}
[[nodiscard]]
value_type* allocate(... | According to cppreference, rebind (which is part of the Allocator requirements) is only optional if your allocator is a template of the form <typename T, [possibly other type arguments]>. But your template is of the form <typename T, size_t N>, so it doesn't match (the size_t argument is a non-type argument).
So you ha... |
70,923,814 | 70,928,447 | Firestore real-time updates with REST API | I'm developing c++ app which connects to Firestore DB via REST API. Is there any workaround to implement real-time updates when some fields in DB are modified? I'm thinking about getting collection document in certain time interval and checking whether there are any updates but it doesn't seem to be very efficient way.... | The Firestore REST API does not implement realtime listeners. If having realtime listeners is a requirement for your use-case, you will have to use one of the SDKs or the gRPC API.
|
70,924,025 | 70,925,793 | C++20 NTTP specialization | There is disagreement between gcc/clang and msvc when trying to compile the following code:
struct foo {
};
// primary template
template<auto>
struct nttp {
static constexpr int specializaion = 0;
};
// specialization
template<foo f>
struct nttp<f> {
static constexpr int specializaion = 1;
};
int main() {
... | This is open MSVC bug report:
Specialization of class template with auto parameter fails to compile for an unclear reason
Your program is well-formed as per [temp.class.spec.match]/2 and [temp.class.spec.match]/3:
/2 A partial specialization matches a given actual template argument
list if the template arguments of ... |
70,924,232 | 70,925,042 | What is the equivalent of python's faiss.normalize_L2() in C++? | I want to perfom similarity search using FAISS for 100k facial embeddings in C++.
For the distance calculator I would like to use cosine similarity. For this purpose, I choose faiss::IndexFlatIP .But according to the documentation we need to normalize the vector prior to adding it to the index. The documentation sugge... | You can build and use the C++ interface of Faiss library (see this).
If you just want L2 normalization of a vector in C++:
std::vector<float> data;
float sum = 0;
for (auto item : data) sum += item * item;
float norm = std::sqrt(sum);
for (auto &item : data) item /= norm;
|
70,924,991 | 70,925,149 | Check if directory exists using <filesystem> | I have a string that contains the path to some file. The file doesn't need to exist (in my function it can be created), but it's necessary that directory must exist. So I want to check it using the <filesystem> library.
I tried this code:
std::string filepath = {"C:\\Users\\User\\test.txt"};
bool filepathExists = std::... | The ansewer provided by @ach:
std::filesystem::path filepath = std::string("C:\\Users\\User\\test.txt");
bool filepathExists = std::filesystem::is_directory(filepath.parent_path());
It checks if "C:\Users\User" exists.
|
70,925,004 | 70,931,748 | How to copy the subsection of the 3 dimensional array in CUDA C++ | I had followed example of Using cudaMemcpy3D to transfer *** pointer
Yet my task is to copy the 3d subsection of the device global memory array to device global memory array for example:
Nx =10;
Ny=10;
Nz = 10;
struct cudaPitchedPtr sourceTensor;
cudaMalloc3D(&sourceTensor, make_cudaExtent(Nx * sizeof(int), Ny, Nz))
.... | The srcPos parameter in your cudaMemcpy3DParams should make this pretty easy. Here is an example:
$ cat t1957.cu
#include <cstdio>
typedef int it; // index type
typedef int dt; // data type
__global__ void populate_kernel(struct cudaPitchedPtr sourceTensor, it Nx, it Ny, it Nz) {
for (it z = 0; z < Nz; z++)
... |
70,925,263 | 70,925,402 | switch statement over performing with char variable in c++ | #include<iostream>
using namespace std;
void fun() {
while(1) {
char choice;
cout<<"(D)isplay, (E)xit"<<endl;
start:
cout<<">> ";
cin>>choice;
switch(choice) {
case 'd':
case 'D':
cout<<"hello world"<<endl;
break;
case 'e':
c... | Your code does what you told it to but not more: cin>>choice; reads a single character. When the user types more than a single character then the other characters are left in the stream and will be read by the next call.
If you want to handle input of more than a single character properly then you need to extract more ... |
70,925,450 | 70,925,563 | cpp/arduino: classes call inherited virtual method | I'm struggling to find the right answer on below question on the internet.
I'm not a native C++ programmer and have more knowledge of OOP programming in PHP, Pascal, and JavaScript, but i can manage.
I want to create a class hierarchy to handle some tasks like displaying content on a LCD screen.
It looks like the follo... | The right syntax is base::display():
class base {
public:
base() { };
virtual void display() { /* Need to be called first from all child objects*/ };
virtual bool keyPress(int state) { /*Need to be called first from all child objects*/ return 42; };
};
class child : public base {
public:
child():ba... |
70,925,635 | 70,928,568 | Gtest on new keyword | new keyword in C++ will throw an exception if insufficient memory but below code trying to return "NO_MEMORY" when new failed. This is bad because it will raise std::bad_alloc exception .
I am writing a unit test(gtest). How to create a scenario to catch this problem.
class base{
public: base(){
std::cou... | Have you looked into EXPECT_THROW?
If you cannot absolutely change your code, (which is required if you want to use gmock), you can globally overload the new operator as the other answer suggested.
However, you should do this carefully since this operator is used by other functions including the ones in google test.
On... |
70,926,139 | 70,926,289 | Issue with a math rule of three in c++ | I started learning c++, but I have an issue.
I'm trying to do a rule of three in c++ but I get a wrong result. Should give me 55.549,38775510204, and I get -41842.000000000000
What I'm doing wrong??
In C# I do this and works fine:
decimal ruleOfThree = decimal.Divide(decimal.Multiply(32000, 76554), 44100);
In C++ I'm ... | I haven't tested this on a C++ compiler, but something like:
long double ruleOfThree = ((32000.0 * 76554.0) / 44100.0);
I.e. make sure the 3 multipliers are doubles, not integers.
|
70,926,826 | 70,926,991 | C++ test for validation UTF-8 | I need to write unit tests for UTF-8 validation, but I don't know how to write incorrect UTF-8 cases in C++:
TEST(validation, Tests)
{
std::string str = "hello";
EXPECT_TRUE(validate_utf8(str));
// I need incorrect UTF-8 cases
}
How can I write incorrect UTF-8 cases in C++?
| You can specify individual bytes in the string with the \x escape sequence in hexadecimal form or the \000 escape sequence in octal form.
For example:
std::string str = "\xD0";
which is incomplete UTF8.
Have a look at https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt for valid and malformed UTF8 test cases.
|
70,927,817 | 70,930,741 | c++ How do I find length of buffer in non-windows platforms using fread() | I have a function using ReadFile() where I append a '\0' at the end of the buffer :
HANDLE InFile;
FILE* InputFile;
DWRD len = ftell(InputFile);
buffer = new BYTE[len + 1];
if (ReadFile(InFile, buffer , len, &len2, NULL))
{
...
buffer [len2] = 0;
}
Now I want to adapt this function for use with non-w... | fread() returns the numbers of items actually read, eg:
FILE* InputFile;
...
DWORD len = ftell(InputFile);
buffer = new BYTE[len + 1];
size_t len2;
if ((len2 = fread(buffer, 1, len, InputFile)) > 0)
{
buffer [len2] = 0;
...
}
else
{
// use feof() and ferror() to check for errors...
}
|
70,928,047 | 70,928,173 | Invoking a tuple containing both the invocable and the arguments | I am trying to invoke the first parameter in a tuple with the second one as a parameter, but can't figure out how to do it.
Example:
#include <tuple>
#include <functional>
struct S {
void operator()(int) {}
};
int main() {
S s;
auto t = std::make_tuple(s, 3);
std::invoke(s, 3);
// std::apply(std::... | Wrapping overload/template function in lambda solves lot of issues:
std::apply([](auto&&... args){ std::invoke(args...); }, t);
Possibly with forwarding:
std::invoke(std::forward<decltype(args)>(args)...);
Else as std::invoke is a template function (taking forwarding reference), you need to correct type:
std::apply(st... |
70,928,300 | 70,936,138 | Beginning on boost::asio : Having problems using io_context | I've been coding in c++ and wanted to try out boost asio to create a TCP asynchronous server.
I read the documentation that boost provides and I used boost 1.75 to try and code this server.
However, I don't seem to understand how to use the io_context from the documentation.
When I am compiling the code for the Day 3: ... | The problem? When you try to initialize the _io_context member you copy the un-copyable io_context object.
The _io_context member needs to be a reference:
boost::asio::io_context& _io_context;
// ^
// Note ampersand, to make it a reference
This is what's done in the full example.
Of course make su... |
70,928,438 | 70,929,005 | Is there a faster, other, different way to use an if statement | This is my first mini project (I'm intermediate c++ programmer)
I wanted to practice using if statements because I wanted to find the extent of the command, and what I could use it for.
However, throughout my program, I constantly became very annoyed that I'm having to write all this code, to perform a simple task.
The... | Sometimes, when you have to handle n different values in different ways, you end up with a switch or if-cascade with n branches.
But often, when you perform the same action (with different data) in all branches, there are other ways, e.g., a look-up table.
What are you trying to do? For each month, print a text. So the... |
70,928,527 | 70,928,566 | Unable to visit a variant if one of its alternatives does not have a specific field | I am trying to visit a variant containing several classes. One of them does not have a specific field value but I handle it with constexpr, however, the compiler still fails to compile.
#include <variant>
#include <iostream>
struct A {};
struct B {
int value = 1;
};
struct C {
int value = 2;
};
int main() {... | You need remove reference and cv-qualifiers of the data:
auto n = std::visit(
[&](auto &data) -> int {
if constexpr (std::is_same_v<std::remove_cvref_t<decltype(data)>, A>) {
return int{0};
} else {
return data.value;
}
},
d);
... |
70,929,336 | 70,929,441 | Function definition with default value (c++) | Consider the following class:
class A{
public:
void fun(int i=0) {cout<<"Base::fun("<<i<<")";}
};
If I understand correctly, when the compiler sees void fun(int i=0), it will define 2 functions for us. One is the function:
void fun() {cout<<"Base::fun("<<0<<")";}
And the other one is the function:
void fun(int i... |
If I understand correctly, when the compiler sees void fun(int i=0), it will define 2 functions for us.
No you do not understand correctly. It only defines one single function returning void and taking an int parameter. Simply if you call it with no parameter and if not function with same name and declared with no pa... |
70,929,696 | 70,930,710 | make std::ostream automatically ident when encountering special characters | I would like to have some facility which makes a std::ostream (or derived) automatically ident on encountering special characters (or special objects). Let's assume that the special characters are < and >. In this case the following input test0<test1<test2, test3<test4> > > should produce the following output:
test0<
... | boost::iostreams makes this fairly easy, you can define filters then chain them together with an output stream to transform the input to the desired output:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
namespace io = boost::iostreams;
struct QuoteOutputFilter {
typedef char ... |
70,929,819 | 70,930,039 | Can const data members have different values between translation units? | I'm wondering if it is permitted to declare the same class multiple times using different values for a const member, or if this would be an ODR violation? Consider this example with two independent translation units that are going to be linked into some libx library:
// x.h
#pragma once
class X {
const int x = VALUE... | Yes, different objects can have different const data members. The issue that the comments are focussing on is in the way that the data member gets initialized, which doesn't really address the issue.
struct s {
const int x;
s(int xx) : x(xx) {}
};
s s1(1);
s s2(2);
What you can't do is define the same name in... |
70,930,072 | 70,933,061 | Using UTF-8 string-literal prefixes portably between C++17 and C++20 | I have a codebase written in C++17 that makes heavy use of UTF-8, and the u8 string literal introduced in c++11 to indicate UTF encoding. However, c++20 changes the meaning of what the u8 literal does in C++ from producing a char or const char* to a char8_t or const char8_t*; the latter of which is not implicitly point... | I would suggest simply declaring your own char8_t and u8string types in pre-C++20 versions to alias unsigned char and basic_string<unsigned char>. And then anywhere you run into conversion problems, you can write wrapper functions to handle them appropriately in each version.
|
70,930,278 | 70,931,237 | How to speed up C++ MySQL connector? | I am using C++ MySQL connector.
sql::Connection * db = nullptr;
try {
db = get_driver_instance()->connect("tcp://localhost:3306", "admin", "admin");
db->setSchema("test_db");
}
catch(exception &e) {
return 1;
}
The MySQL connector is dynamically linked to the application.
LDFLAGS = -L/usr/local/mysql-c... |
how to say to server: give me pointer to DB connection
MySQL connections cannot be shared between processes. If your C++ process starts when an http request is handled, it must open a new MySQL connection at that time.
More typically, a high-performance web app does not fork a new process for every http request. You'... |
70,930,455 | 70,931,213 | How do I handle subdirectory dependencies in CMake? | I have a project where I need to run one application on multiple boards. To do this I have two exectuables that share a main.c, but are compiled with a different board.c. The directory tree is as follows:
CMakeLists.txt
src/
├─ board/
│ ├─ board_a/
│ │ ├─ board.c
| | ├─ CMakeLists.txt
│ ├─ board_b/
│ │ ├─ board... |
My problem is that board.c (as well as main.c) depends on somelib. How can I add this dependency to the subdirectory CMakeLists.txt? Is there a way I can do that without hard-coding a path to somelib? My feeling is that I should create a CMakeLists.txt in somelib, and I feel this would be easy if I were handling the l... |
70,930,812 | 70,930,907 | What does each of these `const`s mean? | Normally people write the main function like this:
int main( int argc, char** argv )
However, this came to my mind:
int main( const int argc, const char* const* const argv )
or maybe I should write it like this cause it seems more intuitive:
int main( const int argc, const char *const *const argv )
What does each of... | The prototype is defined as "int main( int argc, char** argv )"
There is really no point in using a const pointer to access the parameters later unless you don't want to get it changed, which is up to you
The purpose of const pointers is to make sure that they are not changed throughout the code. You can live without t... |
70,931,404 | 70,931,653 | If we convert a value with one constructor, will there also be copy constructor needed to copy the newly created temp object? | I am having a trouble understanding the topic, and so it might be a stupid question but I am still wondering:
When we have a function, for example:
void func(const StringClass & param1, const StringClass & param2);
And then we pass to the function for example, a C string:
func("test", test);
Where "test" is a C strin... | As a first hint you can add a copy constructor that prints something to see if it gets called:
#include <iostream>
struct foo {
template <size_t n>
foo(const char(&str)[n]){
std::cout << "converting constructor\n";
}
foo(const foo& f){
std::cout << "copy constructor\n";
}
};
void b... |
70,931,587 | 70,931,764 | How to initialize std::array member in constructor initialization list when the size of the array is a template parameter | In the following example, I need to initialize the std::array in the A::A(H h) constructor initializer list (because class H doesn't have a default constructor), but I can't do it with an initializer list since the array size is a template parameter.
Is there a way around this?
#include <array>
using namespace std;
st... | std::index_sequence was provided in order to simplify the metaprogramming task of creating and expanding a pack whose size is not fixed. Use std::make_index_sequence and delegate the construction to some private constructor that deduces the pack:
A(H h) : A(h, std::make_index_sequence<N>{}) {}
template <std::size_t...... |
70,932,394 | 70,932,465 | Is Big-O Notation also calculated from the functions used? | I'm learning about Big-O Notation and algorithms to improve my interview skills, but I don't quite understand how to get the time complexity.
Suppose I want to sum all the elements of the following list.
std::vector<int> myList = {1,2,3,4,5} ;
Case 1:
int sum = 0;
for (int it: myList)
{
sum += it;
}
Case 2:
int sum... | If you talk about big-O, you have to talk in respect of some unit of data being processed. Both your case 1 and case 2 are O(N) where N is the number of items in the container: the unit is an int.
You tend to want the unit - and N to be the count of - the thing that's likely to grow/vary most in your program. For exa... |
70,932,785 | 70,932,841 | I have been trying both write and read a file, but have been unable to | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
fstream a_file_that_will_be_working_with("storage.txt");
if (a_file_that_will_be_working_with.is_open()) {
cout << "is open";
}
else
{
cout << "is not open";
}
a_file... | See https://en.cppreference.com/w/cpp/io/basic_fstream for an example.
You need to "rewind" the file to read just written stuff (s.seekp(0);).
|
70,932,913 | 70,933,106 | Type trait to identify classes derived from a CRTP class | I am looking to implement the function is_type_of_v, able to identify the templated instances of type Skill. Please, see the main function in source code below to fully understand the request. It is harder to explain by words than by code.
The solution should work in VS 2017 under c++17. The next link contains the exam... | For Skill, you can write something as
template <template <typename, typename, auto...> class, typename>
struct is_type_of : public std::false_type
{};
template <template <typename, typename, auto...> class C,
typename T1, typename T2, auto ... Is>
struct is_type_of<C, C<T1, T2, Is...>> : public std::true_typ... |
70,932,917 | 70,932,965 | scanf skipping string with a defined size with a proceeding space | I'm trying to read 3 different strings of max 15 characters each. When I try to read them with scanf("%s %s %s", a, b, c), only the last one is picked up (I'm asuming the spaces between every string has something to do with this).
#include <iostream>
#include <string.h>
using namespace std;
#define DIM 15
int main()... | This call
scanf("%s %s %s", a,b,c);
invokes undefined behavior because at least this input "CadenaDe15chars" contains 15 characters. So the appended terminating zero character '\0' will be written by the function outside the corresponding array used as an argument.
You should at least declare the macro constant like
#... |
70,933,076 | 70,943,808 | Access UI components in QT by entering the name of the component? | I have a lot of ui components in my .ui file.
They have a similar name e.g analogRead0, analogRead1, analogRead2 and they have the same data type.
Is it possible for me to acces these fields inside the .ui file by using only the name?
I was thinking of I can make an instance of an object by just entering the name of th... | If you set the object name of the element in the Designer, then you can directly access them via findChild (once you have set up the ui...)
Here is an example, where I change the text for my 3 QPushButtons
ui->setupUi(this);
for(int i = 1; i <= 3; ++i){
auto btn = findChild<QPushButton*>("button"+QString::number(i))... |
70,933,384 | 70,934,176 | pybind11 - Return a shared_ptr of std::vector | I have a member variable that stores a std::shared_ptr of std::vector<uint32_t>. I want to create a Python binding for test_func2() so that I can access that vector without any additional copy. Here is a skeleton code.
#include <vector>
#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include... | According to this issue, it doesn't work because std::vector<uint32_t> is not converted to a python type. So, you will have to return the dereferenced vector. To avoid copies, you can use PYBIND11_MAKE_OPAQUE
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include "test_loader.... |
70,933,410 | 70,944,248 | wxWidgets 3.1.5 MSW - HiDPI scaling problems causing controls to have the incorrect size | Information about my setup
wxWidgets: 3.1.5 (also tried the latest source from github)
wxWidgets: built using gcc-11.2 under msys2 (ucrt64)
Windows 10 Application: build using gcc-11.2 under msys2 (ucrt64)
Monitor native resoultion: 3840 x 2160
IDE: Eclipse 2021-09
My Problem
If I build my application and link agains... | It's a pretty bad idea to use sizes in pixels in general, as this doesn't take the current font size into account, and so using dialog units or just the result of GetTextExtent("something") would be better.
But if you absolutely want to use pixels, you need to at least convert them to the proper units using FromDIP(), ... |
70,933,676 | 70,934,388 | Using sockets to send a string from a C++ client on one computer to a Python server on another. Getting `send: Bad file descriptor` | I'm trying to send a string from a C++ client on one computer to a Python server on another computer.
My error is send: Bad file descriptor
The Python server is killed if it is contacted by the client but it doesn't receive a string. While the Python server is running it does end the program when I attempt to send the ... | You're redeclaring the sock variable in the for loop, so the value of sock when you call sendall() is the original -1. Change
int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
to
sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
so it assigns the outer variable.
|
70,933,726 | 70,934,355 | C++ can't compile code using PROCESSENTRY32 | I'm trying to compile simple lines of code but I'm getting C2664 Error code.
#include <TlHelp32.h>
PROCESSENTRY32 pe32 = { 0 };
if (wcscmp(pe32.something, something) == 0)
Error:
int wcscmp(const wchar_t *,const wchar_t *)': cannot convert argument 1 from 'CHAR [260]' to 'const wchar_t
The definition of wcscmp() ... | Use PROCESSENTRY32W instead of PROCESSENTRY32.
Use Process32FirstW instead of Process32First.
|
70,933,755 | 70,947,008 | Vector of mutex to synchronize access to vector cells | I wrote code to do some parallel operations on a vector, my goal is to protect a single cell of a vector so other cells can be accessed in parallel, so I tried to use a vector of mutex of the same size of the other vector
vector<int> myIntVec(n,0);
vector<mutex> mtxVec(n);
then the critical section, each thread execu... | In order you share this link https://codecollab.io/@proj/InternetDivisionTrucks# in comments. Seems that you try to protect vector<bool> visited(nn); by mutexes vector<mutex> vis_lock(nn);. As i know there is special implementation for std::vector<bool> in which bools stored packed https://en.cppreference.com/w/cpp/con... |
70,933,910 | 70,933,953 | Just started out learning to code and it won't execute | So i am watching youtube tutroials and trying to write hello world but i am already failing
Here is an screenshot
enter image description here
Why won't it execute?
Any help would be really welcome (From Belgium so excuse my broken english)
| You're on Windows. Instead of a.out, the default name for gcc is a.exe. You can see that in the directory listing on the left.
|
70,934,469 | 70,936,291 | How to copy memory from an SSBO to CPU without getting a buffer performance warning? | I'm using a compute shader to generate terrain values. I create my SSBO, I dispatch the compute shader and then I want to copy the values stored in the SSBO into CPU side memory so that I can use it further on. The code works perfectly, I copy into my CPU side buffer with no issues, however I get a performance warning,... | Figured out my own answer in the docs, I have switched to using immutable storage. Instead of using glBufferData I instead am using glBufferStorage
So
glBufferData(GL_SHADER_STORAGE_BUFFER, (mSize*mSize*mSize)*sizeof(float), mData, GL_STREAM_READ);
becomes
glBufferStorage(GL_SHADER_STORAGE_BUFFER, (mSize*mSize*mSize)*s... |
70,934,723 | 70,938,279 | REGEX for first and last names involving dots (.) | I want to be able to get the first and last name always starting with a capital letter... This I've already achieved in a post here on stackoverflow, it's this one:
[A-Z][a-z]+([ ][A-Z][a-z]+)*
However, according to my business rules, I need to be able to validate names and surnames with only the first letter of the fi... | (?:[a-z]|[\.])+ is equivalent to [a-z.]+ (no need for dot to be escaped here)
You want [A-Z](?:[a-z]+|\.) (not sure if + should be *, can name have only one letter (without abbreviation)).
Result would be:
^[A-Z](?:\.|[a-z]*)(?: [A-Z](?:\.|[a-z]*))+$
Demo
"John Doe" // true
"John D." // true
"John D. D." ... |
70,934,849 | 70,934,897 | C++ Polymorphism: How to write function to accept any abstract class implementation | I want to be able to pass whatever implementation of an abstract class into a function defined in a separate file, so that I can use the functionality for other projects and write the child class however it suits me.
main.cpp:
#include "my_process.h"
struct my_guy : V2 {
my_guy(float x, float y)
: V2(x, ... | Your function process currently passes is parameter by value.
Because you currently pass by value, a new V2 value is created as the parameter, which will always have type V2 and act like a V2.
Change it to take a reference to whatever object is passed to it:
void process(V2 & vector)
Since the parameter is also modifi... |
70,934,858 | 70,935,745 | Program Exits Unintentionally When Entering Elements in Array-Based Queue and Does not Continue to Compile the Rest of the Program | I am having this bug where my program unexpectedly exits after entering elements for my array-based queue. It is supposed to run like so:
~ User enters the number of elements they want in the queue (in this case, the size of the array).
~ After user enters their elements, a menu with the methods' corresponding number ... | As Johnny Mopp suggested, you should repeat the process of reading a user choice and handling that choice. The easiest way to do that is to surround the relevant code with a while loop, as shown below:
int main () {
int UserChoice = 0;
cout << "Enter the size of the queue (max is 10 elements)." << endl;
ci... |
70,934,924 | 70,940,132 | Does `wil::com_ptr` overload operator &, aka "address of"? | I found this code snippet here.
wil::com_ptr<IStream> stream;
CHECK_FAILURE(SHCreateStreamOnFileEx(
L"assets/EdgeWebView2-80.jpg", STGM_READ, FILE_ATTRIBUTE_NORMAL,
FALSE, nullptr, &stream));
According to the manual of SHCreateStreamOnFileEx, the type of the last argument is supposed to be IStream **. However ... | The Windows Implementation Libraries (WIL) has its documentation published through its repository's wiki. The wil::com_ptr_t class template1 is described on the WinRT and COM wrappers page.
The section on Object management methods lists three class members that allow clients to get the address of the stored interface p... |
70,935,031 | 70,935,072 | Shall the caller deallocate the return value of `SHCreateMemStream`? | This is a dumb question, but I'm sorry I cannot find this information in the online manual of the function. I came from Linux realm. I'm not familiar with convention in Windows world.
All examples I found use smart pointer, e.g. wil::com_ptr, but GCC obviously doesn't provide those tools. Shall I call Release on the re... | IStream is built on top of the classic COM IUnknown interface, and as such any COM interface pointer returned from a function has had IUnknown::AddRef() called on it, and so you must call IUnknown::Release() when you're done using the interface pointer or else you'll leak memory.
GCC obviously doesn't provide those to... |
70,935,437 | 70,935,490 | Syntax for pointers to a structure | When declaring a pointer to a struct, both the following code snippets compile without error:
A)
struct Foo
{
int data;
Foo* temp; // line in question
}
B)
struct Foo
{
int data;
struct Foo* temp; //line in question
}
What is the significance to repeating the word "struct" in the declaration of the struct pointer ... | In C, struct keyword must be used for declaring structure variables, but it is optional in C++.
For example, consider the following examples:
struct Foo
{
int data;
Foo* temp; // Error in C, struct must be there. Works in C++
};
int main()
{
Foo a; // Error in C, struct must be there. Works in C++
retu... |
70,935,717 | 70,937,435 | ALLEGRO5 change pixel color of text based on background | First attempt:
void Tower::_DrawHealthBarText(std::string text, int x, int y, ALLEGRO_FONT* font)
{
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
ALLEGRO_BITMAP* bmp = al_create_bitmap(196, 17);
int bmpIndex[196][17] = { };
al_set_target_bitmap(bmp);
al_draw_rectangle(5, 20, 200, 20 + 15, al_map_... | The simplest way is to use the clipping rectangle, a common feature of most graphics APIs. When you set the clipping rectangle, nothing can be drawn outside of it.
First, set the clipping rectangle to cover the white part of the progress bar. Draw your text in black.
Then, set the clipping rectangle to cover the black... |
70,935,758 | 70,935,819 | Does the size of the element matter to the speed of std::sort? | Given that they have the same size, would a vector of an element of size 4 byte sort faster than an element of say 128 bytes? Do I have to index them and sort the indicies manually or does std::sort does it under the hood for me?
|
Given that they have the same size, would a vector of an element of size 4 byte sort faster than an element of say 128 bytes?
That depends on CPU architecture but it is quite possible and reasonable to expect that bigger objects would be sorted slower (assuming everything else is equal) as std::sort moves whole objec... |
70,937,314 | 70,937,426 | c++ passing json object by reference | In the below code, I am taking requests from a client, put them together on a json object on my server class and sending it to a pusher(directly connected to a website, putting my data in there so I can search data easily)
The code is working perfectly fine, but my manager said that I need to pass json by reference in ... | The simple answer is to change
void Pusher::jsonCollector(nlohmann::json dump)
to
void Pusher::jsonCollector(const nlohmann::json& dump)
(note that if this is inside the class then Pusher:: is a non-standard visual studio extension).
This will reduce the number of times the object is copied from 2 to 1 however you ca... |
70,937,429 | 70,939,584 | Template arguement for comparator when passing priority queue to a function | I am new to C++ and still learning the concepts. I am trying to pass a priority queue with custom comparators to a templated function. I want to abstract the comparator type in priority queue template argument list when I pass it to the function in the function definition. Below is an example of what I am trying to do.... | It seems that you want to allow any comparator (on your custom type some_type) to be used. To that effect, you can simply use (I'm assuming that you indeed want to passs by value) :
template<class TComparator>
void some_function(std::priority_queue<const some_type*, std::vector<const some_type*>, TComparator> queue)
{... |
70,937,488 | 70,937,586 | The meaning of the symbol ~ on an array when that array is not a class | I'm reading a C ++ code, the code has a line like this:
for(;;)
{
if(~theArray[i] & anotherCondition)
{
DoSomeThing();
}
}
For some values i code goes back to the beginning of the loop, what exactly does this expression ~
on array, do?
Can anybody help?
| ~ operator indicates bitwise complement.
Bitwise complement operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1.
For example:
35 = 00100011 (In Binary)
complement of 35 is
~ 00100011 = 11011100 which is equal to 220 (In decimal)
Please check below resources to learn more about it
B... |
70,937,697 | 70,937,835 | Calculate three angle of triangle using three sides | I want to find three angle of a Triangle using Given three sides but it gives me 'nan' value.
I have tried law of cosines to find the angles but it ain't working. It gives 'nan' value.
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
using namespace std;
double findDegree(double s... | Radian to degrees is "rad * 180 / pi", you're doing it the other way around in findDegree. Why are you doing it anyway?
You also need to put the denominator in parenthesis, for example:
angleA = ((b * b) + (c * c) - (a * a)) / (2 * b * c);
a, b, c should be double probably, as well.
|
70,938,112 | 70,938,940 | How to monitor processes on linux | When an executable is running on Linux, it generates processes, threads, I/O ... etc, and uses libraries from languages like C/C++, sometimes there might be timers in question, is it possible to monitor this? how can I get a deep dive into these software and processes and what is going on in the background?
I know this... | The different things you wanted to monitor may require different tools. All tools I will mention below have extensive manual pages where you can find exactly how to use them.
System calls for this process/thread.
The strace command does exactly this - it lists exactly which system calls are invoked by your program. T... |
70,938,946 | 70,939,155 | QSpinBox prevent the user from enternig thousand separators | In a QSpinBox, when the range is sufficient, the user is allowed to enter thousand separators.
Eg: 1.2.3.4 is a valid entry, en then fixup() just removes the dots. Resulting in 1234.
How can I prevent the user from entering thousand separators?
Previously I made something similar based on QLineEdit which uses validator... | Just override validate and reject input if contains undesired character.
It could be something like that:
QValidator::State MySpinBox::validate(QString &input, int &pos) const
{
if (input.contains(ThousandSeparator)) {
return QValidator::Invalid;
}
return QSpinBox::validate(input, pos);
}
Please do... |
70,939,312 | 70,939,385 | Not able to connect in socket programming in C++ whereas in python, it works | I have a piece of code in python. It is related to client Socket programming. I want to get the NTRIP data from "www.rtk2go.com". The code written in python works well and serves the purpose.
import socket
import base64
server = "www.rtk2go.com"
port = "2101"
mountpoint = "leedgps"
username = ""
password = ""
def ge... | sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0;
means that sockfd is either 0 or 1, which is not a valid socket.
Do this instead:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error creating socket\n");
}
|
70,939,317 | 70,939,438 | C++ : define struct/class template differenty for class and non-class types | in my C++ projet, I use a simple struct template with one template argument (a Vec2, with x and y attributes), and I need to define it differently for two main use cases :
The type is a class, in which case i need special constructor to initialize the two instances that will be held by forwarding arguments to the cons... | You can add extra parameter to enable SFINAE, something like
template <typename T, typename Enabler = void>
struct Vec2
{
T x;
T y;
// ...
};
template <typename T>
struct Vec2<T, std::enable_if_t<std::is_class_v<T>>>
{
private:
T x;
T y;
public:
Vec2(T x, T y) : x(std::move(x)), y(std::move(y)... |
70,939,349 | 70,940,972 | std-ranges for string splitting and permutations | I'm trying to build a view that takes a vector of strings, splits those strings into pieces on char ; and returns permutations for the resulting tokens on each line.
int main()
{
std::vector<std::string> lines;
auto strsplit_view = std::ranges::views::split(';') | std::ranges::views::transform([](auto &&rng)
... | First, you should not convert the split pieces into std::string_view, because it is non-modifiable, which makes it impossible to use next_permutation. You should return std::span<char>.
Second, filesplit_view is a range whose elements are range adaptors. You need to use a for loop to traverse these range adaptors to ge... |
70,940,008 | 70,943,911 | Concept requirement and non-immediate context | I'm learning C++ concepts, and trying to realize why the following does not compile (it's just a trivial and meaningless example demonstrating the point; tested with GCC-11.1):
#include <iostream>
struct non_negatable {
};
template <class T>
auto negate(T a) {
return -a;
}
template <class T>
concept is_negatable... | Firstly, as you referred, negate<non_negatable> is not a substitution failure since the error is not in the immediate context of the function, as such it's ill-formed. From 13.10.3.1/8 of C++20 standard:
If a substitution results in an invalid type or expression, type deduction fails.
An invalid type or expression is ... |
70,940,366 | 70,940,457 | How to start a new jthread on a class member | I think the question is quite obvious. The I have tried so far:
#include <thread>
#include <chrono>
using namespace std::literals::chrono_literals;
class test
{
public:
void member(std::stop_token stoken)
{
std::this_thread::sleep_for(1s);
}
void run()
{
// None compiles correctly... | You can use std::bind_front to bind this to &test::member and pass it to jthread:
#include <thread>
#include <chrono>
#include <functional>
using namespace std::literals::chrono_literals;
class test
{
public:
void member(std::stop_token stoken)
{
std::this_thread::sleep_for(1s);
}
void run()
... |
70,940,640 | 70,940,722 | How to use std::reference_wrapper<T>::operator() | I'd like to use the std::reference_wrapper<T>::operator() "the same" as std::reference_wrapper<T>::get, but following example fails for operator()
#include <cstdint>
#include <functional>
class Foo {
public:
void Print() {
std::printf("Foo\n");
}
};
class Bar {
public:
Bar(Foo &foo): wrapper{foo} {}
void ... |
Is this possible? Where is my misunderstanding?
No. std::reference_wrapper<T>::operator() only exists when T::operator() exists, and it simply calls that, forwarding the arguments provided.
Are you mistaking it for std::reference_wrapper<T>::operator T&?
class Bar {
public:
Bar(Foo &foo): wrapper{foo} {}
void Pri... |
70,940,861 | 70,941,097 | Move assignemnt is called instead of copy, when concepts are used for source type | In the following code, when I change the source from CAssign as source for assignment operators to AnyThing auto, then the move constructor will be called instead of copy.
I'm guessing it has to do with constness but I might be wrong. What causes this and how to achieve what I want?
#include <iostream>
#include <concep... | In
CAssign& operator=(CAssign&& source)
the reference parameter is a rvalue reference. It will be called only if the argument given is a rvalue (which it isn't in a1 = a2;). This is a move assignment operator and how it should normally behave.
With
CAssign& operator=(Anything auto&& source)
or just
CAssign& operator... |
70,941,002 | 70,976,170 | Read all data during single recv() method from a socket | I am trying to continuously read the data using socket programming. I use recv() which receives data on a socket. I store it in a buffer. recv() returns the number of bytes read. Following is the snippet:
while (true) {
try {
char buff[2048];
int bytes = recv(sockfd, buff, 2048, 0);
... | The function strlen will treat the contents of buff as a null-terminated string and return the length of that string.
In the line
buff[bytes] = '\0';
you wrote a null terminating character at the end of the data. That way, you have ensured that the data is null-terminated.
However, it is possible that the bytes that w... |
70,941,517 | 70,948,436 | vk api on boost c++ doesn't work correctly | I wrote a some code that should send GET request and get response.
It works for ip-api.com and returns me json file.
But for api.vk.com it returns html as that:
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>kittenx</c... | Like I commented, that's how HTTP works: Servers can redirect to a better/new location.
I assume the prime reason for this is because your connection is not HTTPS, and that's what the end-points require. So, fix that first.
Next, your query includes the base URL, which is another error.
Live Demo
#include <boost/asio.h... |
70,941,770 | 70,942,702 | Returning a range of references to a std::vector<std::unique_ptr<T>> | I have an abstract base class T and another class holding a vector of unique pointers to T. The class should support two function returning references to the entries. One of them should provide read-access, the other one should be able to modify the values in the unique_ptrs but not the pointers:
class A {
private:
... | If you have boost, much of this is done by the range adaptor indirected
class A {
private:
static auto add_const(T & t) -> const T & { return t; }
std::vector<std::unique_ptr<T>> data;
using indirected = boost::adaptors::indirected;
using transformed = boost::adaptors::transformed;
public:
auto ... |
70,941,875 | 70,942,312 | How does stringstream works with operators << and >>? | Input would be something like : 07:10
I'm getting correct value for hour but for min, I'm getting weird values.
void timeConversion(string s)
{
int hour,min;
stringstream ss;
ss << s.substr(0,2);
ss >> hour;
cout << hour <<endl;
ss << s.substr(3,2);
ss >> min;
cout << min<<end... | Mixing input and output like this is problematic. The initial extraction of hour sets the eofbit, which means when you try to extract min it immediately fails.
You can add ss.clear() to reset the flags.
void timeConversion(std::string s)
{
int hour,min;
std::stringstream ss;
ss << s.substr(0,2);
s... |
70,941,883 | 70,944,485 | boost-ext::sml will not compile visitor example | I am trying to compile from source and experiment with the examples in boost::sml. The visitor example in particular will not compile, so my application with sml is missing a straightforward way to just status which states its state machines are in.
I am running on a machine with the following statuses when doing the i... | C++20 is not required. The current revision on Github contains:
#error "[Boost::ext].SML requires C++14 support (Clang-3.4+, GCC-5.1+, MSVC-2015+)"
And indeed, it compiles fine with -std=c++14, even with GCC 7.5 on my Ubuntu 18.04 box.
However, since your CMake output suggests that C++17 is selected, I tried, and that... |
70,941,992 | 70,942,072 | passing "const ..." as "this" argument discards qualifiers [-fpermissive] | I'm writing a header file to learn more about operator overloading in C++, and I got the following error while implementing the division method for two complex numbers.
Here is the source code:
#ifndef __COMP_H
#define __COMP_H
#include <iostream>
class Complex{
private:
double real;
double imag;
public:
... | This
Complex operator - (Complex const &obj) { ...
and others are non-const member functions. Member functions are non-const by default, meaning they are declared to modify this. You cannot call them on a const instance. Most of your operators do not modify this, hence should be declared as const:
Complex operator - (... |
70,942,530 | 71,083,646 | Is there an "undefined behavior" problem with some APIs in "node-addon-api"? | In <napi.h>, there are some overloads declaration for the static method Accessor in the class PropertyDescriptor.
One of such overloads declaration is here:
template <typename Getter>
static PropertyDescriptor Accessor(Napi::Env env,
Napi::Object object,
... | There is indeed a problem with current implementations of PropertyDescriptor.
See https://github.com/nodejs/node-addon-api/issues/1127#issuecomment-1036394322
Glad I wasn't completely delirious.
|
70,942,644 | 70,942,812 | How to fix warning "Found OpenCV Windows Pack but it has no binaries compatible with your configuration"? | I am trying to use OpenCV in VS Code.
Here's what I've done:
Installed OpenCV for windows.
Added "C:\opencv\build\x64\vc15\bin","C:\opencv\build\x64\vc15\lib" PATH environment variable.
Here's my CMakeLists.txt file.
cmake_minimum_required(VERSION 3.0.0)
project(opencvtest VERSION 0.1.0)
include(CTest)
enable_testing(... | As the error suggests, CMake found your OpenCV installation, but it is not compatible. What is it not compatible with? Your compiler. The OpenCV installation is built with MSVC 15 (it also includes a 14 build). You have asked CMake to use MinGW as your compiler. Libraries need to have been built with the same (wel... |
70,942,654 | 70,943,174 | Generic ranges-compatible functions | I have a function that operates on standard iterators of a common type:
template <typename I>
bool next_combination(const I first, I k, const I last)
I'm trying to use it with std::ranges::views, but I'm not able to pass its iterators as input arguments to the function:
auto view = std::ranges::views::split(';') |
... | You are using a version of gcc that has not yet implemented the P2210, that is, the split subranges obtained by views::split (renamed views::lazy_split in the latest standard) can only be a forward_range.
Since next_combination requires bidirectional_iterators (which support operator--), you cannot pass an iterator of ... |
70,942,887 | 70,943,291 | How can I make a typedef or alias for a template function that can also be used in friend function declarations? | If I have something like this:
mytemplates.h
#ifndef MYTEMPLATES_H
#define MYTEMPLATES_H
#include <iostream>
#include <memory>
#include <string>
class BaseClass;
// Alias (non-working) version:
//class DerivedClass1;
namespace MyTemplates
{
typedef std::unique_ptr<BaseClass> object_up;
template<typename... | Aliases are for types because types are not first class objects in C++. But you do not need aliases for plain functions because you can simply use function pointers.
But a function pointer is just a pointer and you must declare the real function to be friend. It all boil down to:
...
class DerivedClass1 : public BaseCl... |
70,943,108 | 70,943,118 | Conditional inclusion: integral constant expression is unlimited? | Per C++11 (and newer) this code is valid:
#if 1.0 > 2.0 ? 1 : 0
#endif
However, most (if not all) C++ compilers reject it:
$ echo "#if 1.0 > 2.0 ? 1 : 0" | g++ -xc++ - -std=c++11 -pedantic -c
<stdin>:1:5: error: floating constant in preprocessor expression
<stdin>:1:11: error: floating constant in preprocessor express... | Answer from Richard Smith:
This is an error in the standard wording. See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1436 for details and a proposed fix -- though that fix is known to be wrong too (it permits lambda-expressions).
|
70,943,170 | 70,943,292 | What is the proper evaluation order when assigning a value in a map? | I know that compiler is usually the last thing to blame for bugs in a code, but I do not see any other explanation for the following behaviour of the following C++ code (distilled down from an actual project):
#include <iostream>
#include <map>
int main()
{
auto values = { 1, 3, 5 };
std::map<int, int> valMap;... | The evaluation order of A = B was not specified before c++17, after c++17 B is guaranteed to be evaluated before A, see https://en.cppreference.com/w/cpp/language/eval_order rule 20.
The behaviour of valMap[val] = valMap.size(); is therefore unspecified in c++14, you should use:
auto size = valMap.size();
valMap[val] =... |
70,943,365 | 70,945,756 | Is HAL_UARTEx_RxEventCallback Size parameter calculated programmatically or by hardware | I'm realizing UART-DMA with STM_HAL library and I want to know if message size is counted by hardware (counting clock ticks till line is idle for example) or by some program method(something like strlen). So if Size in
HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
is counted by hardware, I can ... | If you are using UART DMA, it is calculated by hardware.
If you check the call hierarchy of HAL_UARTEx_RxEventCallback using your ide, you can see how the Size variable is calculated.
The function is executed in the following flow.(Depending on the version of HAL Driver, it may be slightly different)
UART Idle Interru... |
70,943,406 | 70,943,484 | How to declare a dynamic 2D array in C++ | I'm trying to define a dynamic 2D Array in C++ using the following definition:
int foo(string parameter){
const int n = parameter.length();
int* Array = new int[n][n];
return 0;
}
I receive an error that array size in new expression must be constant, can't understand why because Array is supposed to be dynamic... | (someone posted a shorter version of this in the comments while I was writing it).
What you need for a 2D array allocated with new is this:
int foo(string parameter){
const int n = parameter.length();
int* Array = new int[n*n];
return 0;
}
And then access cells with appropriate indexing.
Another solution i... |
70,943,680 | 70,943,836 | Return an array without getting a Dangling pointer as result in C++ | I want to return an array from a function in C++. I made this simple code to try to achieve it.
#include <iostream>
#include <vector>
std::vector<int> *getx()
{
std::vector<int> a[2];
a[0].push_back(0);
a[1].push_back(1);
return a;
}
int main()
{
std::vector<int>* b = getx();
return 0;
}
It works b... |
Why if i made std::vector a[2] static I solve the warning?
static std::vector a[2];
You may not return a pointer to a local array with automatic storage duration because the array will not be alive after exiting the function and as a result the returned pointer will be invalid.
But you may return a pointer to a local... |
70,944,492 | 70,947,172 | Get string of characters from a vector of strings where the resulting string is equivalent to the majority of the same chars in the nth pos in strings | I'm reading from a file a series of strings, one for each line.
The strings all have the same length.
File looks like this:
010110011101
111110010100
010000100110
010010001001
010100100011
[...]
Result : 010110000111
I'll need to compare each 1st char of every string to obtain one single string at the end.
If the maj... | First off, you show the result of your example input should be 010110000111 but it should actually be 010110000101 instead, because the 11th column has more 0s than 1s in it.
That being said, what you are asking for is simple. Just put the strings into a std::vector, and then run a loop for each string index, running ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.