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 |
|---|---|---|---|---|
74,175,833 | 74,256,157 | How to replace deprecated RSA low level OpenSSL 3.0 APIs with equivalent EVP functions? | This working RSA OpenSSL code
void SwapBytes( unsigned char *pv, size_t n )
{
unsigned char *p = pv;
size_t lo, hi;
for ( lo = 0, hi = n - 1; hi > lo; lo++, hi-- )
{
char tmp = p[lo];
p[lo] = p[hi];
p[hi] = tmp;
}
}
void RSA(unsigned char *plaintext, unsigned char *ciphertext)
{
... | I'm no openssl expert, but going through the hard to read DOC's I figured out the below conversation which from my testing generates the same output as as your function (assuming no SwapBytes is called as you don't provide that).
It can be broken down into three parts I think.
setting up PARAMS array with the key para... |
74,175,992 | 74,176,039 | shared_from_this() crashes in specific case | Option 1 crashes the app on shared_from_this() with bad_weak_ptr, while option 2 works fine, why? the only difference i see is where the clone is being created - in the Clone() function or in line with creating shared_ptr for the clone, in both cases the shared_from_this requirement of already having shared_ptr with ow... | You can't new an object that derives from enable_shared_from_this and for it to safely work since the new object doesn't actually have a shared_ptr container.
Instead of this:
Base* Clone() override
{
return new Derived(*this);
}
This:
shared_ptr<Base> Clone() override
{
return make_shared<Derived>(*this);
}
... |
74,176,542 | 74,179,444 | Boost log - include object id into logs | I'm currently getting started with boost.log and have a question about how to incorporate object id into the logs. So for instance:
class Sample
{
size_t id() const; // ...
void someMethod() {
// log here, see id() in a message
}
};
So, each object has it's own id and I want to see it in the log... | If your object id doesn't change throughout the object lifetime, you do not need to add and remove the id on every log record. You can just add it to the logger once in the logger constructor. You don't even need a new logger feature to do this as every logger supports a set of logger-specific attributes.
// Define an ... |
74,176,592 | 74,176,608 | Return a smart pointer dereference as a reference type | const string& show_string(){
std::shared_ptr<std::string> p = std::make_shared<std::string>("test");
return *p;
}
A novice question:Will this usage cause dangling reference?
| Yes
std::shared_ptr will delete the object it owns when the last std::shared_ptr sharing ownership of that object is destroyed. In this case, p is the only std::shared_ptr pointing to your string, and it is local to show_string, so that string will be destroyed as soon as show_string returns, leaving the returned refe... |
74,176,863 | 74,176,888 | C++ reference to a variable on its initialization | Consider this example:
#include <iostream>
std::string& fn(std::string& str) {
str = "oh no!";
return str;
}
int main() {
std::string str = fn(str);
std::cout << str << std::endl;
return 0;
}
I have two questions
Why does this compile/why doesn't the compiler warn against it? It seems obvious th... |
Why does this compile/why doesn't the compiler warn against it? It seems obvious that str shouldn't be referenced (in the fn function call) before its initialization. Does the C++ standard not prevent this? And if so what's the purpose of referencing a variable before it's initialized?
It doesn't warn on
std::string ... |
74,179,196 | 74,181,644 | Use of undefined type as a class after adding forward declarations | I'm having an issue compiling that code. I know the code dose nothing, but it gave me an error saying " use of undefined type Humans, how can I make it work? how can I make classes that can access other classes instances in cpp ? Thank you :)
#include <iostream>
class Humans;
class Animals
{
p... | A forward declaration only states that a thing with a particular name exists somewhere; you can't use an instance of it for anything until the definition is also known.
Separate the class definitions and the member function definitions.
(This is the "default" way of writing C++, with class definitions and function defi... |
74,179,685 | 74,180,482 | How many times are arguments calculated in multithreaded function-scope static variable initialization? | Suppose we have a following function, which is executed by multiple threads at the same time:
void foo()
{
static SomeClass s{get_first_arg(), get_second_arg()};
}
My question is how many times will get_first_arg and get_second_arg be executed -- exactly once, or ThreadCount times, or is it unspecified/implementat... | The local static variable s initialized only once and the first time control passes through the declaration of that variable. This can be seen from static local variable's documentation:
Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control ... |
74,180,013 | 74,180,117 | How to assign from one to another related class, custom assignment or cast in c++? | I have a class templated on a floating point type,
template <typename fl_t> class generic {
fl_t a,b;
/// a bunch of getters and setters, etc...
}
and instantiate with float and double
typedef generic<double> dmatrix;
typedef generic<float> fmatrix;
Later, when I want to assign an fmatrix to a dmatrix, I get
error: ... | Your assignment operator takes the current type as parameter:
template <typename fl_t> class generic {
// ...
template <typename f> generic<f>& operator=(const generic& g)
// this is generic<fl_t> ^^^^^^^
// ...
};
If you want to assign from another type, you need to swap the return... |
74,180,278 | 74,181,285 | Is there a way to handle exeption without try catch block? | Sorry for all mistakes, English is not my native language. I have code that contains following lines:
tf::TransformListener listener;
tf::StampedTransform transform;
while(ros.ok()) {
try {
listener.lookupTransform("/map", "/base_link", ros::Time(0), transform);
} catch(tf::TransformException ex) {
//ROS_ER... | As Sam Varshavchik put it,
If an exception gets thrown in a C++ program, there only way to catch it and resume execution, at some point, is a try/catch block. This is the only way to do it, there are no workarounds or exceptions.
As this answer said, the only way for a global error handler is to put the entire progra... |
74,180,443 | 74,180,508 | sort vector of Coordinates(x,y,z) by vector of z value | I have a vector of 3D coordinates:
vector<float64>contourdata;
contourdata={x0,y0,z0,x1,y1,z1,x2,y2,z2,...}
And I want to sort them by the vector of the z value.
How can I do it in c++?
| Like this :
#include <algorithm>
#include <iostream>
#include <vector>
#include <format>
// 3d points have 3 coordinates and
// we need to move those 3 values together when sorting
// It is also good to use "concepts" from real world as
// names in code : so define a struct representing a 3d coordinate.
// (Or use a 3... |
74,181,289 | 74,181,339 | Cant Delete File Unless I Close My Program | I have this code
CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
It works perfectly but the only problem is that I cant read, write, or delete the file unless I exit my program. Any Ideas?
| You should store the return value of CreateFileA in a variable of type HANDLE:
HANDLE hFile = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
Then, when you're done with it, call:
CloseHandle(hFile);
After which you should be able to delete the file.
|
74,181,335 | 74,194,218 | Cannot use LineSegmentDetector from OpenCV in C++ | I am trying to perform line detection, using OpenCV, in order to select rows of vegetation in satellite imagery.
I decided to use OpenCV LineSegmentDetector since it seemed to provide just what I need in a single code line, as opposed to using Hough Transform or other more complex methods that require some additional w... | Thanks to Micka accurate suggestion, I was able to trace the problem. Seems that cv::Ptr was a requirement and standard C++ pointers do not work, even in a fairly simple setup like this one. I was not aware of that.
I am providing the fixed code just in case it can be helpful to someone:
#include "stdafx.h"
#include "o... |
74,181,763 | 74,182,538 | What optimization allows Functors to be inlined? | At compile-time, I want to pass a (stateless) function as efficiently as possible. I see two options:
template<typename Functor>
bool PassAsArgument(int arg1, int arg2, Functor functor);
and
template<bool (*Function)(int, int)>
bool PassAsTemplateParameter(int arg1, int arg2);
The second option seemed like the obviou... | Constant propagation is the key optimization.
When the lambda or functor is called, the compiler still knows which code runs, and thus it's as straightforward as inlining a function by name. If not, it's like a runtime-variable function pointer; the compiler can't inline1.
After inlining PassAsArgument(1, 2, LessThan)... |
74,182,587 | 74,183,277 | Can I form a C++ reference from a pointer of the wrong type? | If I have a pointer T* t and I use reinterpret_cast<T*>(&u) to point to some object u (which is not a T), I know that I cannot access u via t.
Therefore, I think that I cannot form T& rt from t, even if I don't perform any access through rt because:
To form rt I would need to express *t in some way, which is an "acces... |
To form rt I would need to express *t in some way, which is an "access", and I am prohibited from doing this.
No, dereferencing itself is not an access. An access would require reading from or writing to a scalar object.
I would be initializing a reference with something other than "a valid object".
If t points to ... |
74,182,823 | 74,182,986 | Getting a read access violation trying to spin up a Vulkan instance | I am trying to use the vkCreateInstance() method but I am getting a read access violation from vulkan-1.dll. I am using SDL for windowing, and am using Visual Studio 2022, and have both Windows and my graphics drivers up to date
#include <vulkan/vulkan.hpp>
#include <SDL.h>
#include <SDL_vulkan.h>
#include <vector>
#i... | The most likely cause for this is that your VkInstanceCreateInfo does contain uninitialized values. You declare it as VkInstanceCreateInfo inst_info; without initializing the structure. Later on you only set some members of it to defined values, thus passing uninitialized values to the implementation, which then fails ... |
74,183,574 | 74,183,679 | std::accumulate won't' perform sum of elements with std::plus functor | I have a class which contains an integer among some other things:
class Foo
{
public:
Foo() = default;
Foo(int x)
:
x(x)
{}
int operator+(const Foo& rhs)
{
return x + rhs.x;
}
private:
int x;
float whatever = 0.0f;
};
I also have a vector of these objects:
std::v... | You are trying to add an int and a Foo with a function that takes two Foos.
You could use a function that adds int to Foo:
// in Foo
friend int operator+(int lhs, const Foo& rhs)
{
return lhs + rhs.x;
}
Or you could use a function that adds two Foos
// in Foo
Foo operator+(const Foo& rhs)
{
return { x + rhs.x ... |
74,184,464 | 74,184,540 | How to validate the input of an array? | How do I validate input for the array to only accept integers?
#include <iostream>
#include <iomanip>
#include <string>
#include <string>
using namespace std;
int main()
{
int TheNumbers[10];// An array of 10 indexes
int i;
for (i=0; i<10; i++) // accepts input 10 times
{
cout << "Enter a num... | You could try adding another nested loop:
static const int MAXIMUM_NUMBERS = 10;
//...
for (int i = 0; i < MAXIMUM_NUMBERS; ++i)
{
std::cout << "Enter a number: ";
while (!(cin >> number[i]))
{
std::cout << "Invalid number. Try again.\n";
std::cout << "Enter a number: ";
std::cin.cl... |
74,185,163 | 74,185,211 | Speeding up a program that counts numbers divisable by 3 or 5 | I'm trying to write a simple program that counts numbers that are divisible by 3 or 5 in a specific range. However, the program still fails to meet the desired execution time for some inputs.
Here is the code:
#include <cstdio>
using namespace std;
int main(){
unsigned long long int a=0, b=0, count=0;
... | The divisibility of numbers by 3 and 5 repeats every 15 numbers.
See, illustration
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
X X X X X X X
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
X X X X X X X
Now, you need to use this fact to only check up to 15 numbers... |
74,185,797 | 74,186,822 | Why does `monotonic_buffer_resource` appear in the assembly when it doesn't seem to be used? | This is a follow-up from another question.
I think the following code should not use monotonic_buffer_resource, but in the generated assembly there are references to it.
void default_pmr_alloc(std::pmr::polymorphic_allocator<int>& alloc) {
(void)alloc.allocate(1);
}
godbolt
I looked into the source code of the hea... | The assembly tells the story. In particular, this:
cmp rax, OFFSET FLAT:_ZNSt3pmr25monotonic_buffer_resource11do_allocateEmm
jne .L11
This appears to be a test to see if the memory resource is a monotonic_buffer_resource. This seems to be done by checking the do_allocate member of the vtable. If it is not such... |
74,185,842 | 74,185,969 | type casting unsigned integer | Consider val being a user input. I expect val to be between 0-65535
Instead of checking if val is not withing acceptable range before denying it, I was wondering if
is this :
uint16_t count = atoi(val);
the same as this :
uint16_t count = (uint16_t)atoi(val);
Is this an acceptable way of "securing" the user input? I ... |
Is this:
uint16_t count = atoi(val);
The same as this:
uint16_t count = (uint16_t)atoi(val);
They behave exactly the same. For the former, by assigning an int to a uint16_t, it is being implicitly converted anyway.
Since a uint16_t cannot contain any more than 65536 or less than 0, the conversion safely stores the ... |
74,186,160 | 74,186,389 | How to receive string result from Delphi DLL in C++Builder? | Calling a function from a DLL returning a string gives a memory error. What am I doing wrong?
Note: Following codes show me the first character of the returned string and then gives a memory error.
I am using Delphi 11.2 and C++Builder 5.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
HINSTANCE MyDll;
... | Delphi's String type is an alias for AnsiString in Delphi 2007 and earlier, but is an alias for UnicodeString in Delphi 2009 and later. Since you are using Delphi 11.2, string is going to alias UnicodeString, not AnsiString. So, you have a type mismatch between your C++ and Delphi codes.
However, neither type is safe... |
74,186,548 | 74,186,701 | Summing recursive functions return values to a variable | I'm currently learning C++ and I'm trying to complete a recursive function, which first reads a data-structure and then returns itself n-amount of times to the main function. These returns are supposed to be summed up in the main-function and assigned to a variable.
In my program I have a little trickier data-structure... | You're just discarding the values returned from all the calls to recursive_function. You need to add them up.
Example:
int sum = 0;
for (auto& name : data_structure[id])
{
sum += 1 + recursive_function(data_structure, name);
// + 1 for the associate
// + the sum of the associate's associates (recursively)
}... |
74,187,581 | 74,194,810 | Using Boost::optional with ->multitoken and/or ->composing() | I'm trying to use Boost to be able to pass multiple arguments or have multiple occurrences of a flag with ->multitoken and ->composing. However, I want this to be an optional flag using boost::optional<>.
Below is the basic boost example from their site, modified for my purpose. Without the boost::optional wrapper, eve... | Simplicity reduces bugs and improves maintainability.
Simplicity is usually when you reach the "sweet spot" of a library - the way it was designed. In this design, multi-token option are an extension of optionals (an optional is just like container with a maximum size of 1). The design does not expect you to layer both... |
74,187,652 | 74,189,353 | Possible g++ linker bug in Boost on Msys2 | I have already set up my Msys2 and installed mingw-w64-x86_64-boost on it.
I provided a minimal example of c++ with boost which I will build using the command g++ main.cpp -o main.exe -lboost_program_options-mt:
#include <boost/program_options.hpp>
#include <string>
#include <iostream>
namespace po = boost::program_opt... | Yooo! I fixed the issue.
I first tried to run it on a fresh virtual machine to cross out the possibility that this issue is caused by my current environment. Surprisingly enough, it worked perfectly fine on the virtual machine. Knowing that it only happens in my current environment, I did proceed to make the following ... |
74,188,070 | 74,188,159 | Conversion operator with ref-qualifers: rvalue ref and const lvalue ref overloads ambiguity | While answering another question, I noticed something peculiar about conversion operators when dealing with ref-qualifiers.
Consider the following code:
using P = std::unique_ptr<int>;
struct A {
P p;
operator P() && { return std::move(p); }
operator P const&() const& { return p; }
};
int main() {
A a... | When you write p = std::move(a), it is actually p.operator=(std::move(a)). There are two relevant candidates for this function:
P& operator=(P&&) noexcept; // (1) Move assign operator
P& operator=(const P&); // (2) Copy assign operator
The fact that the second one is deleted isn't considered yet.
So, the convers... |
74,188,593 | 74,484,343 | How to hide borders of combox and only show the bottom border in MFC? | I'm want to make a flat design ComboBox which only shows a blue bottom border. But I can only change 4 borders' color. How to hide right,left and top border and show bottom border?
| Finally I made it. Just rewrite OnPaint() function and use CDC::DrawEdge(CRect, BDR_RAISEDINNER, BF_BOTTOM) to drwa a bottom border.
void CCustomComboBox::OnPaint()
{
CPaintDC dc(this);
CRect rc;
GetClientRect(&rc);
dc.DrawEdge(rc, BDR_RAISEDINNER, BF_BOTTOM);
... //draw other parts of ComboBox
}... |
74,188,619 | 74,188,701 | A class pointer does not name a type | I have 3 C++ files:
Main.cpp
#include "FileA.h"
FileA.h
#include "FileB.h"
class FileA{
private:
FileB* b; //It doesn't give error here!
};
FileB.h
class FileB{
private:
FileA* A; //The error is here!
};
When I run the Main.cpp file, the compiler says:
'FileA' does not name a type, did... | Spent too much time commenting and not answering. This is pretty much what Bolov showed, but with more of the gory details.
Let's looks at this the way the compiler does. Whenever the compiler, really the preprocessor, finds an include directive, it replaces the include with the content of the included file.
The compil... |
74,189,699 | 74,189,838 | Problem when deleting specifics nodes in linked list | I am trying to delete specifics nodes by a give data in my pop method, so my linked list code is:
#include <iostream>
#include <string>
using namespace std;
class Node
{
private:
public:
int n1;
int n2;
Node *next;
Node(int n1, int n2)
{
this->n1 = n1;
this->n2 = n2;
this->... | This line:
while (temp != NULL && temp->n1 != n1 && temp->n2 != n2)
Should be
while (temp != NULL && (temp->n1 != n1 || temp->n2 != n2))
Otherwise, it will delete first element that matches either n1 or n2, but not necessarily both.
While we are here, let's simplify your pop() function:
void pop(int n1, int n2)
... |
74,190,943 | 74,357,076 | No line break after while-statement with clang-format | I want to configure clang-format (version 14.0.6) that it leaves single-line while-statement without adding a line break for the trailing semicolon (C++):
For example, clang-format should just leave a "one-liner" as it is:
while (checkWaitCondition() != true);
But unfortunately clang-format adds by default a line brea... | I found the reason, why clang-format ignored the settings for AllowShortBlocksOnASingleLine and AllowShortLoopsOnASingleLine: I had another .clang-format file in a lower directory, which overwrote my test-configuration...
With both flags set to true, the format works as expected, with the following setting in the .clan... |
74,191,067 | 74,306,384 | Using preload-file compiler option for emscripten compiler to load local file in Qt | I am building an Qt Application using WebAssembly. I want to open a local file and read it frin my code which isn't exacty easy with WebAssembly. I tried using the preload-file option (reference) in my .pro file:
CONFIG += preload-file /path/to/file/Settings.ini
However, when compiling my application with WebAssembly,... | I noticed you are using CONFIG += but the emscripten reference says it is a linker flag. Try using instead QMAKE_LFLAGS += --preload-file /path/to/file/Settings.ini.
Personally, I have not tested preload-file option but two other options have been working for me:
The similar embed-file functionality. In the .pro file ... |
74,191,460 | 74,191,695 | How to force terminate std::thread by TerminateThread()? | I called IMFSourceReader::ReadSample and I found it was stuck if it cannot read data.
So I tried to terminate the thread by TerminateThread() but it returned 0 as a fail.
How could I terminate the stuck thread?
This is my sample code:
#include <iostream>
#include <vector>
#include <codecvt>
#include <string>
#include <... | The reason it failed to terminate is that the native handle is no longer valid after detaching, one way you could do this is to OpenThread using the thread id to get a new handle.
To get the thread id, you could use its handle before detaching like this:
DWORD nativeId = GetThreadId(t->native_handle());
t->detach();
A... |
74,191,617 | 74,191,697 | How to return std::array of different size based on compile-time switch? | I need to create an array of static data, where the size (and data) is known at compile time, but differs between build configurations.
This is a very dumbed-down version of what I'm trying to do
(Please ignore glaring bad practices in this code as it is just an example):
constexpr ProductType PRODUCT = ProductType::A;... | The condition you pass to if constexpr does not depend on any template parameters, so both branches are compiled.
From cppreference
Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive
void f()
{
if constexpr(false)
{
int i = 0... |
74,192,257 | 74,195,313 | Enabling the empty base class optimization globally in a C++ project on Windows | MSVC seems to disable empty base class optimization (EBO/EBCO) when using multiple inheritance. Sadly, this means that other compilers targetting windows have to also disable EBO in such scenarios. Now, MSVC provides __declspec(empty_bases) for re-enabling it, but now you have to put this attribute in every class that ... |
Is there a way to disable this behavior globally?
That would break ABI compatibility with every type declared by any C++ code on your platform. Including code from your standard library or any pre-compiled library you link to, as well as any DLLs and the like. So... no, there is no way to do that.
Platform ABIs, even... |
74,192,356 | 74,203,599 | Why does this vector throw a bad allocation exception? | Why does this seemingly innocent function throw a bad allocation exception for noUrls=300,000,000?
#include <string>
#include <vector>
#include <algorithm>
void generateUrls(int noUrls)
{
std::vector<std::string> urls;
urls.resize(noUrls); //this always works
std::size_t i =... | You are only counting characters, but std::string is not just characters. On my platform, sizeof(std::string) is 32. That's about 9GiB for an array of zero-length strings, before you start adding any characters.
If a string is short, most implementations keep the characters inside those 32 bytes to avoid allocations. B... |
74,192,442 | 74,194,588 | Template func with cond. const argument + template arg deduction | I am implementing a wrapper class that wraps some base class object. I want the wrapper to be as unnoticeable as possible and therefore, I have already overloaded the -> operator to return a reference to the wrapped object in order to provide immediate access to the base-class's interface.
Additionally, I want my wrapp... | You might turn your template functions in non-template friend function of your class:
template <typename T>
struct Wrapper
{
// ...
friend void myFunc(typename cond_add_const<Wrapper<T>, true >::type lhs, T rhs)
{ /*...*/ }
};
Demo
There are some caveats:
the friend function can only be found via "ADL" (... |
74,192,646 | 74,192,876 | Downcasting to base type of vector of shared_ptr | #include <vector>
#include <memory>
class Base {
public:
virtual ~Base() = default;
virtual int f() = 0;
};
class Derived : public Base {
public:
~Derived() = default;
int f() override { return 0; }
};
int main() {
const std::vector<std::shared_ptr<const Base>> vec{std::make_shared<const Derived>()}... | There is no problem with having a polymorphic type here, but you need to explicitly say that std::make_shared<const Derived>() is supposed to be an element, and not an argument of some fancy constructor.
std::vector doesn't have any constructor that takes a single std::shared_ptr, but you can redirect the name lookup w... |
74,193,198 | 74,193,247 | Run function every 5s inside loop running every second | I need to run my function MyFunc() every five seconds using the parameters in the code (i.e. minimum code changes).
There are two parameters in the code: ts and std::chrono::system_clock::now()
What do I write in condition so that I can run my function at the interval?
auto ts = std::chrono::system_clock::now() + std::... | The way in my mind is to check whether the time passed is greater than 5 seconds. You could do something similar to this, where there is a separate variable to keep track of 5 seconds after the last time that the function was run:
auto ts = std::chrono::system_clock::now() + std::chrono::seconds(1);
auto fiveseconds = ... |
74,193,446 | 74,195,111 | Code to convert decimal to hexadecimal without using arrays | I have this code here and I'm trying to do decimal to hexadecimal conversion without using arrays. It is working pretty much but it gives me wrong answers for values greater than 1000. What am I doing wrong? are there any counter solutions? kindly can anyone give suggestions how to improve this code.
for(int i = num; i... | There's a couple of errors in the code. But elements of the approach are clear.
This line sort of works:
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
But is confusing because it's using 48 and 55 as magic numbers!
It also may lead to overflow.
It's repacking hex digits as decimal character values.
It's also unco... |
74,193,587 | 74,193,822 | Function that accepts any pointer type | I have a function void Foo(MyType* mt). I want callers to be able to pass any pointer type to this function (e.g. unique_ptr, shared_ptr or iterator) and not require passing a raw pointer. Is there any way to express this? I could write:
template <typename T>
void Foo(T t);
This will work since it will only compile if... | In C++20, you'd write a concept such as
template <typename P, typename T>
concept points_to = requires(P p) {
{ *p } -> std::common_reference_with<T &>
} && std::equality_comparable_with<std::nullptr_t>
template <points_to<MyType> T>
void Foo(T t);
Prior to that, you could write something involving std::pointer_t... |
74,194,101 | 74,194,210 | Why does the rvalue parameter change to lvalue when used? | I pass rvalue std::move(x) to testForward(T&& v), but it calls print(T& t) inside.
It seems that the rvalue v has changed to an lvalue before it calls print(). I do not know why this happened. Can anyone explain it?
#include<iostream>
using namespace std;
template<typename T>
void print(T& t) {
std::cout << "Lvalu... | The value category of the expression v is an lvalue, because:
... Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression
If you want to forward a forwarding reference as its original category, use std::forward, ie,
template<typename T>
void testForward(T&& v) {
... |
74,194,673 | 74,194,731 | How to use std::get in a tuple wrapper class? | I have an object that must store a tuple for some reason, something similar to this:
template<typename... Types>
class MultiStorer {
public:
tuple<Types...> my_tuple;
MultiStorer(Types... elem) : my_tuple(tuple<Types...>(elem...)) {};
auto getElem(int&& pos) {
return get<pos>(my_tuple);
}
};
... | A function parameter can never be used as a constant expression, so you cannot use it as the non type template parameter of get. What you can do is make your own function a template like
template <std::size_t pos>
auto getElem() {
return get<pos>(my_tuple);
}
and then you would use it like
cout << multistorer.get... |
74,194,702 | 74,194,989 | Non-const reference of Eigen matrix only bind with dynamic types and not with non-dynamic types | I have an Eigen (3.4.0) related question that really troubles me. In this C++ code, there's a function pass_by_nonconst_ref which takes a non-const reference to a eigen matrix, and that does some work on the matrix.
#include <iostream>
#include "Eigen/Eigen"
using namespace std;
// A function that takes a non const r... | Eigen::Matrix<float, 3, 1> is a different type than Eigen::Matrix<float, -1, 1>. The only reason the function call resolves at all when you call it with x2 is that Eigen supplies an implicit cast operator that knows how to create a dynamic matrix from a fixed-size one. However, what this means is that a temporary is ... |
74,194,786 | 74,194,933 | BOOST Asio async_write_some vs asio::async_write , force a single write operation | Some special files have semantics associated with individual writes. (For example, FunctionFS (USB gadgets in userspace) associates a single write to a sequence of USB packets within a single USB transfer. Two writes will never be merged into a single USB packet. Hence the first write may end with a short packet.)
I th... | What would you use in terms of POSIX API? Likely it ends up the exact same underlying API that ASIO hooks into. So, if that API behaves in the way you describe you can expect ASIO to behave in the same way (not resulting in partial completions).
The only place where I readily know ASIO might have opinions on buffer div... |
74,195,031 | 74,195,350 | how to jump a line in file c++ | I want to increase second line in my file but I can't, please help me.
Here is my file content
0
0
I want to increase second 0 by 1, here is my code
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream file;
file.open("file1.txt");
std::string line;
getline(file, line);
... | You are trying too hard. This is the easy way
int main()
{
std::ifstream file_in("file1.txt");
int a, b;
file_in >> a >> b;
file_in.close();
++b;
std::ofstream file_out("file1.txt");
file_out << a << '\n' << b << '\n';
file_out.close();
}
Read the whole contents of the file. Make the mo... |
74,195,215 | 74,195,265 | How to convert a string containing only 0 or 1 into a binary variable? | How to convert a C++ string (containing only "0" or "1") to binary data directly according to its literal value?
For example, I have a string str, it's value is 0010010. Now I want to convert this string to a binary form variable, or a decimal variable equal to 0b0010010 (is 18).
int main() {
string str_1 = "001";
... | std::stoi has an optional second argument to give you information about where the parsing stopped, and an optional third argument for passing the base of the conversion.
int i = stoi(str, nullptr, 2);
This should work.
Corollary: If in doubt, check the documentation. ;-)
|
74,195,991 | 74,197,399 | C++ stringstream question, how can I make each line seperate | I'm sorry the title may be inaccurate.I'm new to C++.
Here is my code and output...
#include <iostream>
#include <sstream>
using namespace std;
class LogLine {
private:
stringstream ss;
string message;
public:
~LogLine() {
ss << "\n";
message = ss.str();
cout << message;
mess... | When I understand you correctly, you want to detect the end of the statement, where log is used, and then append a std::endl.
My solution is similar to that one of @MarekR, but it forces a line break, when log is not rebound:
It does not detect "\n" and flushes it to std::cout, that would be contra productive on parall... |
74,198,046 | 74,198,144 | Overriding protected field members in C++ not working? | In the following, I expected class Child's protected field member _AorB to be of type B, and not A, but reality shows otherwise.
What am I mis-understanding, and how can I adjust the code for the desired behavior?
class A{
public:
void doit(){
std::cout<<" this is A!"<<std::endl;
}
};
... | You can make such changes:
template <typename AorB>
class Parent{
public:
void doit(){
_AorB.doit();
}
protected:
AorB _AorB;
};
class Child: public virtual Parent<B> {
}
Also take a look at What are the rules about using an underscore in a C++ identifier?
Reserved in any sco... |
74,199,536 | 74,262,045 | Computing the outer product of two vectors in Eigen c++ | I have a piece of python code written using numpy that I'm trying to port over to C++ using the eigen library. I haven't really found anything suitable in the eigen library.
This is the python equivalent:
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(n... | To achieve the same behavior as np.outer(a, b), where a and b are both column vectors (i.e. VectorXf for instance) in Eigen it would simply be:
a * b.transpose()
For info, the thread you linked has nothing to do with the outer product. Rather, it's about the "exterior product" (I know the two names are confusingly si... |
74,199,759 | 74,200,039 | Is there a way to pass a brace enclosed list to variadic templates? | I would like to pass a variable list of objects to be passed to a template function as a series of brace enclosed initializers.
So something like this:
enum class E { a, b, c };
template <typename T>
struct Info
{
template <typename U>
Info(E e, U u)
: e(e)
, size(sizeof(u))
{}
E e;
... | Since the plain {}, has no type, it can not be used in the template type deduction.
From what I understood, that you're trying to achieve, I propose the following
template <typename T, typename...Ts>
void fn(E e, T&& val, Ts&&...args)
{
Info<T> ob{ e, std::forward<T>(val) }; // do something with ob
// ....
... |
74,199,956 | 74,201,242 | QSqlQuery fails to get SQL Server stored procedure output value | I am converting web server code written in VB.NET to Qt 5.15.12. The server accesses a Microsoft SQL Server 2012 database. I have several stored procedures that take an output parameter. The output parameter works as expected with VB.net. One stored procedure is giving me issues in Qt. The stored procedure checks if a ... | A bare SELECT in the body of the stored procedure sends a resultset to the client.
SELECT Column1 FROM MyTable WHERE Column1=@Param1
The output parameter is sent after the resultset in the TDS response, and in many client libraries you must consume the resultset before checking the output parameters. You can avoid thi... |
74,200,487 | 74,213,792 | Is there a precedence to type_traits? | I'm pretty new to SFINAE, and was wondering if there's a precidence to which template the compiler will select if multiple std::enable_if_t<true, std::is_...<T>> end up applying to T.
Like in this example:
template<typename T, typename = void>
class Thing {
// Thing A
};
template<typename T>
class Thing<T, std::en... | To also answer the question: no, that kind of precedence does not exist. The action of enable_if, though clever, is to either fail or succeed the substitution. More importantly, the substitution occurs before any potential instantiations are compared with each other. The rules for this comparison are complicated, but i... |
74,200,777 | 74,200,849 | Why does codecvt_utf8 give hex value as ffffff appended in beginning? | for this code -
int main()
{
std::wstring wstr = L"é";
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (auto c : myconv.to_bytes(wstr))
{
ss << std::setw(2) << static_cast<unsigned>(c);
}
string ssss = ss.s... | c is of type char, which is signed on most systems.
Converting a char to an unsigned causes value to be sign-extended.
Examples:
char(0x23) aka 35 --> unsigned(0x00000023)
char(0x80) aka -128 --> unsigned(0xFFFFFF80)
char(0xC3) aka -61 --> unsigned(0xFFFFFFc3)
[edit: My first suggestion didn't work; removed]
You c... |
74,200,954 | 74,201,268 | Can't Pass `std::array` From Within Closure | Using the following declarations:
#include <array>
template <typename V> void makeError(V& v) {}
the following code snippet fails to compile under MSVC 16.11.13 with /std:c++17:
int main() {
[&]() {
std::array bugs{0};
[&]() { makeError(bugs); };
};
return 0;
}
The error message is as fol... | Looks like this is a bug in msvc's legacy lambda processor. Your code compiles if you pass /Zc:lambda: https://godbolt.org/z/91z4chhTx
This seems to be the matching bug report: https://developercommunity.visualstudio.com/t/class-template-argument-deduction-fails-in-the-bod-1/414204
How I found this
I would always recom... |
74,201,108 | 74,242,011 | Implementing a container for both const and mutable types in C++ | Let's say we have a class X that holds a pointer to an object of class Y. X never changes Y in any way, but other objects which might want to change Y can ask X for a pointer to Y. We want class X to be able to hold both const and variable objects. If we write something like this:
class Y;
class X {
public:
const Y*... | You can think about the analogous situation of std::unique_ptr: one that holds a pointer to a mutable Y is std::unique_ptr<Y>, while one that holds a pointer to a const Y is std::unique_ptr<const Y>.
X can similarly be made into a template:
class Y;
template <class T>
class X {
public:
T* getY();
private:
T* p... |
74,201,479 | 74,201,547 | How to initialize a constexpr struct containing arrays without using intermediate variables? | Is it possible to initialize a constexpr struct which contains array-like fields without defining intermediate variables. Using intermediates is the only solution I could find to workaround compilation errors due to passing temporary arrays, but that pattern seems more verbose than necessary.
I'm open to using somethin... | Put your value in a template parameter:
constexpr MyStruct foo{
.a = std::integral_constant<std::array<int, 3>, std::array{1, 2, 3}>::value
};
// or more tersely
template<auto V>
inline constexpr auto static_storage(V);
constexpr MyStruct foo{
.a = static_storage<std::array{1, 2, 3}>
};
And you can use a lambda ... |
74,201,941 | 74,202,004 | Can I call these member functions of std::unordered_map concurrently? | I have a global std::unordered_map<int, int> m.
I also have exactly one thread that is type A and multiple threads are type B running concurrently.
Thread type A:
call insert(), erase() to add/remove some elements (guarantee not the elements read/write in the thread type B concurrently) of m
Thread type B:
call operato... | No. insert can rehash the array which reallocates the bucket array. If that happens right before operator[] accesses it, that's a use-after-free.
This probably isn't the only reason it's unsafe, but we only have to find one, to prove that it's unsafe.
|
74,202,405 | 74,203,036 | How to dynamically create and populate an array of size n? | I am trying to populate an array with varying sizes (ex: A[100], A[1000], etc) with randomly generated numbers. Within the problem statement, vectors are not allowed to solve the problem. These arrays are being generated outside of main and their size, which is given by user input, is being passed as a parameter to the... | Creating an array of an undefined size is incorrect because, in c++, an array is initialized in compile time. When the program compiles the user has not provided the value for n, therefore int A[n]; is incorrect.
To dynamically create an array of size n you must use the new keyword. The new keyword performs a memory al... |
74,202,928 | 74,202,981 | What does it mean to 'instantiate' a class? | I have found this code regarding 3D perlin noise: https://blog.kazade.co.uk/2014/05/a-public-domain-c11-1d2d3d-perlin-noise.html
I created a noise.h file from the first chunk of code.
Then I added the second chunk to my C++ project, included the noise.h header file, and added it to my project via the solution explorer.... | Instantiation means creating an object. The author means you create a Perlin object as follows:
uint32_t seed = 42;
noise::Perlin perlin(seed);
And then you can call the noise methods:
for (double x = 0.0; x < 1.0; x += 0.1)
{
std::cout << perlin.noise(x) << "\n";
}
Similarly for the PerlinOctave class.
It might ... |
74,203,154 | 74,203,344 | How to find Maximum number and negative numbers from a .txt file and also how to output Total result to another .txt file | I want to find Maximum numbers from my "numbers.txt" file and amount of negative numbers. And i want to output the Total result to another .txt file and console and the rest to the console only.
Im very new and just cant figure out how to do it.
This is what i have now
a "numbers.txt" file with
-4
53
-5
-3
2
and
#incl... | You don't need to store the numbers to find the maximum or the amount of negative numbers, but you need to track them inside the loop, like you're already doing with the sum and the total amount of numbers.
int Highest = INT_MIN;
int Negative = 0;
while (file >> n)
{
sum += n;
total += 1;
if (n < 0)
{
... |
74,203,223 | 74,249,259 | D3D12 Pipeline State Object use clarification | I'm working on my own D3D12 wrapper, and I'm in the beginning 'schema' phase.
I understand the purpose of the PSO in a very simple rendering pipeline, but say I've multiple objects, meshes, models, whatever terminology works best, and I would like to use a different pixel shader for each,
for clarification, I would ma... | You need a distinct Pipeline State Object for every unique combination of all states:
VS, PS, GS, etc. Shader Objects
Blend, Depth, and Raster state
Render Target format
Number of render targets (MRT vs. 1)
Sample count (MSAA vs. not)
In practice that means at least one PSO per unique material in your entire scene.
|
74,203,233 | 74,203,302 | Forward declaring a template type parameter | I see this question has been discussed in various places, e.g. here,here,here and here .But, i have still not been able to relate to the questions aforementioned.
My situation:
I am trying to implement a simple generic visitor pattern in C++. The hosts in this pattern are different pets, these are in a file called Pet.... | You need to move the FeedingVisitor to a new header and cpp as well. In header you will have #include "Visitors.h", forward declration for Pet and in cpp #include "Pet.h"
Something like
Visitors.hpp
namespace pet {
class Pet; //Comment 1. Attempted forward declaration.
}
namespace temp_visitor
{
template <... |
74,203,442 | 74,204,807 | CreateProcess on top of other windows applications MFC | I'm developing the MFC Application (C++)
On i want to open the Labview program inside the MFC application and run top of the other windows on the main application.
So, it does not work on CreateProcess() function.
#define DIR_TEMP_MONITER ".\\Application.exe"
STARTUPINFO stStartup = { NULL, };
PROCESS_INFOR... | I used the Labview program to Always on top the all application then it open in the windows CreateProcess function.
That gives always on top of the other windows applications.
thank you.
|
74,203,587 | 74,203,914 | Getting an element of vector which includes enums | I get inputs from user and I put them into a vector. After that I want to get any value of vector at some index. It gives a number. How can I get the exact input value?
enum Enums
{
I, O,T, J , L, S, Z
};
int main()
{
unsigned int index;
Piece piece;
for (index=0; index < 5; index ++)
{
cout << ... | One way to solve this is to fix the underlying type of the enum to unsigned char and also change the type of inputPiece to unsigned char as shown below:
//----------vvvvvvvvvvvvv---->fixed this to unsigned char
enum Enums: unsigned char
{
I, O,T, J , L, S, Z
};
class Piece
{
public:
//--vvvvvvvvvvvvv-----------... |
74,204,004 | 74,204,138 | Can I compile and execute C++ project without copying any license? | Can I just download and execute a C++ project on GitHub licensed under the MIT license without copying that license somewhere? For example, download a single file, g++ it and run? What about bash scripts in this repo? There are considered source code, not binary. Can I also execute them without any attribution?
| The MIT license says no
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
That categorically says all copies. It doesn't matter if you're the only person with access to a copy.
But in practice?
When you execute a file, your computer copies i... |
74,204,311 | 74,204,426 | why is it balance 0 i dont get it | #include <iostream>
static float balance = 30000.0;
void deposit(float amount) {
if (amount < 0.0 && amount > 100000.0 ) {
printf("Error invalid amount entered ");
}
else {
balance += amount;
}
}
float withdrawal(float withdrawal) {
if (balance == 0.0)
printf("NO MONEY ... | You had made some syntax errors, Here is the complete working code:
#include <iostream>
static float balance = 30000.0;
void deposit(float amount) {
if (amount < 0.0 && amount > 100000.0 ) {
printf("Error invalid amount entered ");
}
else {
balance += amount;
}
}
float withdrawal(fl... |
74,204,376 | 74,204,454 | Why adding "variable + 1" doesn't increment its value by one for every loop in a for loop? (C++) | I'm having a hard time understanding why using a increment operator in a for loop in C++ has a different result than doing 'variable' + 1. The variable in the second case simply isn't remembered after each iteration of the loop:
Take the following code:
#include <iostream>
int main(){
int a{0};
for (int i = 0;... |
Why doesn't 'a + 1' preserve its value after every loop?
a + 1 is an expression that doesn't assign anything to a. That is a is not affected in any way. This means when you do just a + 1, the value of a is still 0(the old value).
On the other hand ++a has the same effect as:
v---------->assignment done here implici... |
74,204,399 | 74,205,677 | Is flattening an array of structs undefined behavior in C++? | Is flattening an array of structs that contain an array like in the example below undefined behavior according to the C++ standard, even if there is no padding in the struct S?
#include <iostream>
struct S
{
S() : v{1,2,3,4,5}
{}
int v[5];
};
static_assert(sizeof(S) == 5 * sizeof(int));
void print_array(... | Short answer: this is not defined in the standard so it is UB, and you have no guarantee that it will work
Long answer:
The standard defines undefined behavior as (3.64 [defns.undefined]):
undefined behavior
behavior for which this document imposes no requirements
You are there... The standard never says that a struc... |
74,204,445 | 74,212,125 | Android NDK: CMake fails while linking static library (OpenSSL) | I'm writing a simple proof of concept app that integrates OpenSSL using NDK. Unfortunately, it gives me undefined reference errors during build.
What I did:
Cross-compiled OpenSSL for Android (x86_64 is shown, and similarly for other ABIs):
openssl-1.1.1q $ ./Configure android-x86_64
openssl-1.1.1q $ make
openssl-1.1.1... | OpenSSL consists of (at least) two libraries: libcrypto which has the general-purpose cryptographic functions; and libssl which is a TLS implementation built on top of libcrypto.
So in your case libcrypto would be the appropriate library to link against.
|
74,205,201 | 74,231,238 | C++ COM (non MFC) calling method with pointer argument | I'm trying to reproduce a COM client in c++ in the non MFC way. I'm able to connect to the com interface and call some methods that require simple values as parameter, but I'm not able to call a method with a pointer as argument, the function is this:
short sProdGetCurrentMachineType(short* p_psMachineType)
and in the... | As Simon Mourier said the correct parameter to set on the rgvarg array was VT_I2 | VT_BYREF instead of VT_I2
|
74,205,967 | 74,206,061 | How to find the longest subarray such that its xor has even parity? | I've found a solution in O(n^2) complexity which is as follows:
But is there any way in which I can reduce its time complexity?
This is the bin function
int bin(int n)
{
int i = 0;
while (n > 0)
{
if (n % 2 == 1)
i++;
n = n / 2;
}
return i;
}
This is the code in main
fo... | Note two things:
Xor of two elements have even parity if and only if sum of their parities are even.
Xor of n elements equals to xor of n-1 elements xored with the nth.
If the sum of parities of all elements are even, then you are done. Array itself is the longest.
If not, then you can go through both end of the ar... |
74,206,115 | 74,206,752 | How to define a lambda function to be able to capture the 'this' pointer of a class? | I have a time class which tracks the time.
I want my other classes to be able to register a callback function if the day changes.
I have this working snippet:
#define MAX_CB_CHANGE_FUNCTIONS 50
typedef void (*dayChangeFunc)(int prevDay,int nowDay);
class TimeSystem {
private:
// array for the function poin... | Change the callback type to std::function<void(int, int)>
using dayChangeFunc = std::function<void(int, int)>;
or
typedef std::function<void(int, int)> dayChangeFunc;
and change the function prototype,
void TimeSystem::regDayChange(dayChangeFunc func).
(If you had used your type alias consistently you wouldn't have nee... |
74,206,119 | 74,206,336 | Why aren't the default arguments of my template used in this case | I am leaning the topic templates in C++, it says I can also assign the datatype in the template syntax. But if I pass a different datatype in the object of class and call the method of my class it should throw an error or a garbage output, but it does not whereas it gives the correct output if I assign the datatype whi... | A char can be implicitly converted to an int. Although the type of A will be deduced by C++20 to Abhi<int,char>. That's why when you output it you get an a and not its corresponding integer representation.
See CTAD for a more detailed explanation of the mechanism.
More interesting is why your compiler implicitly conver... |
74,206,509 | 74,206,891 | Idiomatic C++11 for delegating template specialisations to a default implementation | I'm making a struct Box<T> that handles some data. The specifics are unimportant.
An important note however is that Box<T> can store a pointer, but it might not. So both Box<int> and Box<int *> are valid. Obviously, if we own Box.data, we're going to need to delete data if it is a pointer type.
Here's a solution I came... | First off, C++11 already has std::is_pointer, no need to roll your own. You can see that it inherits from std::true_type or std::false_type instead of defining its own value member. The reason for that is tag dispatching, that can effectively replace if constexpr in this situation:
template <typename T> struct Box {
... |
74,207,011 | 74,207,171 | is casting float to unsigned char a valid conversion? | Can someone please explain how float to uint32_t casting works? Is it a valid conversion?
The output of the first line in the below code make sense to me, but the rest are I can't figure out myself.
cout<<uint8_t(256+33)<<'\n';
cout<<uint8_t(float(256+33))<<'\n';
cout<<int(uint8_t(float(256+33)))<<'\n';
cout<<int(uint8... | They are not valid, but are undefined.
In C++17:
4.10 Floating-integral conversions [conv.fpint]
A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represent... |
74,207,064 | 74,207,129 | Why does my code result in a blackscreen? | i"am learning c++ and decided to make a simple calculator and when i compiled the project and ran it all it showed is a black screen. Btw im running MS VSCode 2022. Thanks in advance for help! :)
`
#include <iostream>
using namespace std;
int main() {
int konec = 0;
double cislox = 0;
double cisloy = 0;
... | There is a typo in the while loop:
while (konec == 0); {
The ; on there makes it an infinite while loop that does not execute any code, since it's empty. The correct way should be:
while (konec == 0) {
|
74,207,266 | 74,207,323 | c++ std::set compare function when object is member of the set | I have a set composed of objects; in order to work the operator< must be defined for ordering the objects inside the set. If I define the operator< as a friend function, it works; if I define the operator< as a member function I get the error:
Error C2678 binary '<': no operator found which takes a left-hand >opera... | You need to make the member function const. Because you declared it as 'non-const' the compiler cannot decide if yout operator willl change *this so your operator cannot be used in a when you have a const TEstObj& what is needed for insert
bool operator< (const TestObj& t2) const
{
return m_a < t2.m_a;
}
will do t... |
74,207,355 | 74,207,688 | Several dependent init-statements within one if condition | I need to place two dependent init statements within one if condition. As a raw example:
if (bool x = false; bool y = true) std::cout << "Check!\n";
The whole expression evaluates to true, and that is the problem. Suppose I want to test a pointer in the first statement and dereference this pointer to test something el... | When it comes to several statements within one if, only the last statement is evaluated as a condition. In this case, a ternary operator is a solution:
if (bool x = false; bool y = x ? true : false) std::cout << "Check!\n";
So, in case of pointers:
if (auto ptr = ptr_to_check; auto sth_else = ptr_to_check ? ptr_to_che... |
74,207,456 | 74,207,564 | Why can't I reassign the value of a pointer? | I am using a library for GUI (Qtitan for Qt).
There I have a class called NavigationViewHeader whose pointer I can access by navigationView->header().
Now I want to reassign the content of the pointer, but it tells me (translated)
The function "NavigationViewHeader::operator=(const NavigationViewHeader &)" (implicit d... | The error message is a bit confusingly worded. NavigationViewHeader doesn't declare a copy assignment operator, which is why the compiler implicitly declares one. However, one of its base classes has a deleted assignment operator, so this fails.
I assume NavigationViewHeader inherits from QObject since you mentioned it... |
74,207,537 | 74,208,603 | type checking constexpr function to check non-template type or template type on C++17 | I wrote type checking constexpr function.
It the type is type1 or type2 then returns true, otherwise returns false.
Here is the code. It works as I expected.
#include <type_traits>
struct type1{};
struct type2{};
struct type3{};
template <typename T>
constexpr bool is_type1or2() {
return std::is_same_v<T, type1> ... | This can be solved easily if you change the syntax of the static_assert to accept the type as a function argument, as this will allow function template argument deduction (see Takatoshi Kondo's answer).
However, this can also be solved by writing a template that checks whether a type is an instantiation of a template:
... |
74,207,607 | 74,207,903 | type conversion from int to class behaving weirdly | So. I am trying to convert a uint16_t (16 byte int) to class. To get the class member varaible. But it is not working as expected.
class test{
public:
uint8_t m_pcp : 3; // Defining max size as 3 bytes
bool m_dei : 1;
uint16_t m_vid : 12; // Defining max size as 12 bytes
public:
test(uint16_t vid, uin... | test t = (test)tci;
This line does not perform the cast you expect (which would be a reinterpret_cast, but it would not compile). It simply calls your constructor with the default values. So m_vid is assigned 65535 truncated to 12 bits, and m_pcp and m_dei are assigned 0. Try removing the constructor to see that it do... |
74,208,129 | 74,208,202 | push_back an element into a vector of an another structure vector's back() | struct Thing
{
int id;
std::vector<int> v2;
};
std::vector<Thing> v1;
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
Thing pic;
cin>>pic.id;
v1.push_back(pic);
int x;
cin>>x;
v1.back().v2.push_back(x);
}
}
v1 is not an empty vector. I ca... | v1.back() is the last element of v1 with the type of Thing
v1.back().v2 is the v2 member of that element with the type of vector<int>
So you are calling the push_back() on a vector<int> with an int what is fine
Note that if v1 is empty then v1.back() is UB
Edit:
v1.back().v2.push_back(x); is kind of like
{
Thing& t=v1.... |
74,208,585 | 74,209,101 | What is the difference between using the '*' operator vs the '%' operator when using the rand() function in C++? | Below I am going to show two different versions of rand() implementations.
First, the modulo operator (%):
int r = rand() % 10;
Now, I know that this statement produces a random integer between 0-9.
Second, the multiplication operator(*):
double r = rand() * 101.0 / 100.0;
This is the one I am confused about. I have ... | There is no different implementations for rand() function.
The difference in these two cases is the mathematical operation you do with the value returned by rand() function.
In the first case you just take the number returned by rand() and divide it to 10 using modulo operator (so getting a number between 0 to 9). And ... |
74,208,798 | 74,209,282 | Setting priority on std::async thread | When using std::async, what is the best way to set priority? I realize this is platform dependent, but with a posix compliant operating system, would this work?
// Launch task with priority 8
auto future = std::async(std::launch::async, // async policy required
[] ()
{
pthread_setschedprio(pthread_self(), 8... | I suspect your design is a bad idea.
std::async is required to behave as-if it was a new std::thread. But it doesn't have to be on a new pthread. The implementation is free to (and probably should) have a set of underlying threads that it recycles for std::async -- just clean up thread_local storage and handle stuff ... |
74,208,893 | 74,209,825 | translating pixel unpacking to halide algorithm | I have a buffer filled with pixel data in pattern UY1VY2... and I want to unpack that to another buffer in pattern Y1UVY2UV... So basically if I had a vector of that data I want following operation
for(x=0; x<sizeof(in_buffer); x+=4)
out_buffer.push_back(in_buffer[x+1]+ in_buffer[x+0] + in_buffer [x+2: x+4]) ---> [... | Sure, something like this ought to work:
out_buffer(c, x) = in_buffer(mux(c, {1, 0, c}), x);
Then in the schedule, you'd use set_bounds and unroll to make sure the c loop didn't actually have to check the value of c. See this tutorial for more details: https://halide-lang.org/tutorials/tutorial_lesson_16_rgb_generate.... |
74,209,381 | 74,289,127 | Global initialized variable in a DLL | Is it possible to use a global variable from one DLL module to initialize global variable in other DLL module? If so, how?
I am using Microsoft Visual Studio 17.3.6 and use a C++/CLI wrapper class with some C files. I am in a bigger project but I have put together a smaller example that exhibits the behavior.
I would h... | What I was trying to do is not possible. Address of dllimported symbol cannot be used in an initializer of static data. I solved it by including the .c files with the structures' definition in each module that needed them. Structures themselves may stay extern when it is implemented this way. So with regards to my code... |
74,209,430 | 74,210,218 | C++: is it possible to use "universal" pointer to vector? | Good day, SO community!
I am new to C++ and I've ran into a situation in my project, where I have 2 vectors of similar paired data types:
std::vector<std::pair<int, std::string> firstDataVector
std::vector<std::pair<int, std::string> secondDataVector
and in one part of the code I need to select and process the vector ... | You are trying to create a reference to one of the vectors - and that's certainly possible, but it must be initialized to reference it. You can't defer it.
It's unclear what you want to happen if no match is found in stringValue so I've chosen to throw an exception.
now project has only two of them, but the vectors co... |
74,209,432 | 74,310,525 | Incredibuild: Compiler failed to generate PCH file | Some members of my team, as well as our build server, are getting a compiler error and failed build when using Incredibuild to build our largest Visual Studio solution. We get the following (sanitized) error:
Target ClCompile: stdafx.cpp
IncrediBuild: Error compiling stdafx.obj: Compiler failed to generate
PCH file ... | Apparently it is caused by some recent Windows Updates. There is a support bulletin about it on Incredibuild's support page with links to download an "emergency patch version" (9.6.10) that fixes the issue: https://incredibuild.force.com/s/.
I experienced the same problem - the build would succeed on some computers b... |
74,210,086 | 74,210,251 | Qt Creator fails to start (Qt platform plugin problem), fresh install for C++ development | I recently installed Qt, actually I am developing a C++ project which was written to comply with Qt 5.15.2, so I downloaded that one, and installed Creator 8.0.1 (Enterprise) too. Creator does not start, but it welcomes me with this message:
The application failed to start because no Qt platform plugin could be
initia... | QtCreator 8.0.1 does not support Windows 8.1 (because it is developed in Qt 6, which supports only Windows 10 and newer, see https://doc.qt.io/qt-6/supported-platforms.html).
You will probably need to download and install older versions of QtCreator. You can find some of them here https://download.qt.io/archive/qtcreat... |
74,210,274 | 74,210,562 | How to substitute a function argument with a string in c++? | I'm new to c++, and am trying to make a fullscreen setting in SFML. But nothing I tried works.
Working code:
sf::RenderWindow window(sf::VideoMode(1920, 1080, 32), "title", sf::Style::Fullscreen);
Code that would look like what I am looking for (but doesn't work):
string str1 = "sf::Style::Fullscreen";
sf::RenderWindo... | The 3rd parameter of sf::RenderWindow is a Uint32 (at least that's what the documentation says), but you are trying to pass a string which is rather pointless.
You probably want something like this:
Uint32 mystyle = sf::Style::Fullscreen;
sf::RenderWindow window(sf::VideoMode(1920, 1080, 32), "title", mystyle);
or bet... |
74,210,881 | 74,211,363 | C++, question about references and pointers and about their functioning in function | everybody!
Really, I just want to understand what is going on with this references and pointers. Can you explain me, why in one case all is workking fine, but in another I receive nothing
I will start with working case.
So, there is a program (this is not mine):
#include <iostream>
#include <conio.h>
using namespace s... | This happens because of the following line in the modified code
(t) = new node;
You are assigning memory to your pointer which is being created in a function call, a memory that will be lost after the function call.
Note that if you make changes to a member of a struct in a function call, the change will be reflecte... |
74,211,320 | 74,281,456 | WebRTC: Track.onOpen() is called, but track is not open | Using libdatachannel, I establish a PeerConnection between two partners using some out-of-band signaling. I can create DataChannels and send data between them successfully (with peer_connection->createDataChannel()).
But I am struggling to do the same with a video track. Here is what I do:
I create a track from one pa... | That was a bug in libdatachannel.
|
74,211,453 | 74,225,020 | External openMP build does not set threads equal to OMP_NUM_THREADS | I want to use an external build for OpenMP (not the one that comes natively with the compiler).
For the external build am cloning https://github.com/llvm-mirror/openmp.git and then cmake with the following options:
cmake \
-DCMAKE_BUILD_TYPE=Debug ... | You need the -fopenmp flag; either add set(CMAKE_CXX_FLAGS "-fopenmp") to the CMakeLists.txt file or -DCMAKE_CXX_FLAGS="-fopenmp" to the cmake command.
As a side note, you can also remove the find_package(OpenMP) since you are explicitly linking against the library with the absolute path.
|
74,211,567 | 74,213,705 | How to access BPF map from userspace that was created in kernel space | I am a complete novice at anything ebpf but trying out some random ideas to get some knowledge.
I wanted to have an eBPF module that could filter some packets based on an allowed list of CIDR. A userspace application should be able to update the allowed list so that filtering can happen without reloading the eBPF probe... | Posting an answer myself as I seem to have found a way (although not sure it is the correct thing to do?).
I set the pinning mode of the struct in kernel space to be pinned by name e.g
struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 128);
__type(key, struct ip4_trie_key);
__type(value,... |
74,211,585 | 74,211,840 | Missing wingdi functions when exporting using gcc | So i'm trying to compile this simple piece of c++ code using gcc:
#include <windows.h>
#include <wingdi.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
HWND hwnd = GetDesktopWindow();
HDC hdc = GetWindowDC(hwnd);
RECT rekt;
GetWindowRect(hwnd, &rekt)... | Putting -lgdi32 at the end as suggested by @user4581301 fixed this issue.
|
74,211,950 | 74,212,948 | QT - how to fix link error 2019 with qt VS tools | I'm trying to create a simple qt application in visual studio, I also made sure to install all qt components.
Code:
#include "QtWidgetsApplication2.h"
#include <QtWidgets/QApplication>
#include <QtDataVisualization/Q3DSurface>
#include <QtDataVisualization/QSurfaceDataProxy>
#include <QtDataVisualization/QHeightMapSur... | From the Qt documentation for Q3DSurface here: https://doc.qt.io/qt-6/q3dsurface.html on the qmake line at the top it has qmake: QT += datavisualization the QT += datavisualization part is what you need to add to your .pro file to use the Q3DSurface class. This will setup the linking and any additional include direct... |
74,212,589 | 74,212,606 | Can you get/re-use a promise from a future object when you're done with the future object | is there code that works like this?
promise<type> p;
future<type> f{p.get_future()};
..thread stuff...
f.get();
//now the important part |
// v
p=f.get_promise();
| You cannot get a promise from a future at all. And once a promise's value is set, it cannot be changed.
You could reset a particular std::promise object by move-assigning from a freshly created promise, but no future attached to it would be updated. They would all be looking at the previous shared state, not the new on... |
74,213,511 | 74,213,570 | Iterative Binary Search Tree C++; Why sometimes my program run correctly and other time not? | I am trying to insert new nodes to binary search tree. I get no error, but if I run this program sometimes the tree displays correctly in cmd and sometimes nothing happens and the program doesn't crash, but the console is like waiting for something. I can't figure it out where the mistake is. Here is the code:
#include... | During
while (current != nullptr) {
prev = current;
if (current->data < data)
current = current->right;
else if (current->data > data)
current = current->left;
else
continue;
}
If current->data is equal to data, what will happen? You will cont... |
74,214,333 | 74,214,385 | How to get return value of c++ int main() output using subprocess.check_output() in python script | I am using a C++ script as follows:
int main(){
int x =7;
std::cout<<"print num:"<<x<<std::endl;
if(x>0){
std::cout<<" good"<<std::endl;
return 5;
}
return 0;
}
For this in my python file I am calling the subprocess as follows:
result0_1 = subprocess.check_output(MYCPP_fILE_PATH,shell =True)
print(result0_1.d... | From Python 3 docs
And very similar Python 2 docs
If the return code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and any output in the output attribute.
|
74,214,646 | 74,240,715 | C++ macros - holding keys for certain time | I just started with C++ and I want to make my game character being IDLE in any game. I've tried some code to make him move but it seems that it glitches, how can I make it so that a key are being hold for a small amount of time and then the next key? For example:
Pressing W for 2 sec, then A for 2 sec, then S for 2 sec... | Forget that it was about a game it's just a macros. It's design was to press a key and that's it.
I fixed it by making a method for holding a key and then recalling it for each key I wanted.
void HoldKey(char keyToHold, double repeatingTime)
{
SHORT key;
UINT mappedkey;
INPUT input;
key = VkKeyScan... |
74,214,843 | 74,215,011 | How to save classes and vectors for later, so I don't have to create them every time I start my program in C++? | I have a .txt file with millions of Data points, and I want to organize them into Classes and Vectors. So the data is usable. However this will take a very long time and I don't want to do it every time I start my program. Is there a way to store the created classes and the data inside them so I only have to go through... | It sounds like a premature optimization to me. You say it "will take a very long time", but have not quantified that. How long does it take (as a function of data size), and what are your performance requirements? It sound like you have not yet written this code, so have no real idea of the actual performance. If thi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.