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 |
|---|---|---|---|---|
68,719,504 | 68,723,303 | How can I select a subset of tuple types and create another tuple from contents of the subset? | I have a tuple of structs that are defined using variadic arguments:
#include <tuple>
#include <vector>
template<class Type>
struct Pool {
std::vector<Type> components;
};
template<class... Types>
class Storage {
public:
std::tuple<Pool<Types>...> pools;
template<class SelectedType0, class... SelectedTypes>
... | Following seems to do the job (assuming uniqueness of type in Types):
template <typename... Types>
template <typename... SelectedTypes>
std::tuple<std::vector<SelectedTypes>&...>
EntityStorageSparseSet<Types...>::getVectorsFromPools()
{
return { std::get<SelectedTypes>(pools).components... };
}
|
68,719,867 | 68,719,987 | Issue with stringstream/osstream not chaining << operator and never calling flush at std::end | So I have the following logging class
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
struct asDigest {
explicit asDigest(const void* text, size_t len) : _t(text), _l(len) {}
explicit asDigest(const std::string& text) : _t(text.c_str()), _l(text.size(){}
const void* _t;
size... | The problem is that Diagnostics("TAG") << "Message" returns an ostream& reference to the internal m_stream, so subsequent ... << "MoreMessages" << std::endl will go directly to that stream, bypassing all of your class's logic.
To chain your operator<<s correctly, they all need to return Diagnostics& instead of ostream&... |
68,720,537 | 68,721,036 | Why can't we directly use lambdas without mentioning its type in some STL containers? | I was working with STL containers, trying to implement custom comparators/predicates, and I realized when giving the predicate as a Functor there seem to be same syntax for all containers, i.e. you just mention the name of the Functor as the respective argument in the template arguments, and bam it works!
Now coming to... | You have mixed up the function template and the class template. For both cases, for any code to appear, it must be instantiated. Let's look at each case:
The std::sort is a function template which accepts the binary-predicate (i.e. callable compare function/ function objects) as its third parameter.
template< class Ra... |
68,720,562 | 68,720,633 | C++ libcurl returning null? | I'm new to c++ and need to implement a request in a class. But the answer I'm getting is coming null. From what I've been researching, it's a problem with the static WriteCallback function. But I can't solve the problem, how can I solve it?
class AbstractInstanceParser
{
public:
static size_t WriteCall... | std::string value is not allowed to be passed to curl_easy_setopt(curl, CURLOPT_URL, ...);
What you do (I changed your very long hard to read line):
const std::string url = "http://localhost:5000/route/v1/driving/" +
std::to_string(x_coordinates[i]) + "," + std::to_string(y_coordinates[i]) +
";" + std::to_string(x_... |
68,720,595 | 68,720,784 | The difference between const auto& vs as_const? | Basically, I'm trying to learn about C++ 17, and I found as_const.
What's the difference when we use:
MyType t;
auto& p = as_const(t);
instead of:
MyType t;
const auto& p = t;
Are there some advantages here?
| In your case they are the same.
std::as_const is usually used to select the const version from a set of overloaded (member) functions. The following is an example from cppreference.
struct cow_string { /* ... */ }; // a copy-on-write string
cow_string str = /* ... */;
// for(auto x : str) { /* ... */ } // may cause d... |
68,720,753 | 68,720,787 | Why the compiler does not raise an error when not passing address of array element? | I have the following code
# include <iostream>
using namespace std;
void show (int list[], int len) {
for (int i = 0; i < len; i++) {
cout << list[i] << " ";
}
cout << endl;
}
void swap (int* a, int* b) {
cout << *a << ' ' << *b << endl;
int c = *a;
*a = *b;
*b = c;
cout << *a... | You're calling std::swap, not your own swap function.
std::swap takes two reference arguments of any matching type.
(This is why, IMHO, using namespace std; can be a bad idea. I prefer to qualify names with std:: explicitly.)
|
68,720,861 | 68,721,062 | Declare Global Object Inside Function C++ | Suppose there is the following code to initialize an LCD display on an Arduino board:
#include <LiquidCrystal.h>
void LCDInit(){
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
lcd.begin(16, 2);
lcd.setCursor(0, 0);
}
void LCDPrint(String data){
lcd.print(data);
}
When I call LCDInit() it will initialize the ... | #include <LiquidCrystal.h>
#include <memory>
std::unique_ptr<LiquidCrystal> lcd;
void LCDInit(){
lcd = std::make_unique<LiquidCrystal>(12, 11, 5, 4, 3, 2);
lcd->begin(16, 2);
lcd->setCursor(0, 0);
}
void LCDPrint(String data){
lcd->print(data);
}
UPDATE: If you can't use std::unique_ptr, then just u... |
68,721,466 | 68,738,858 | How to reduce build time for a Docker container installing R libraries? | I need to run some code that contains both Python 3.8 and R 4.1.0 in a Docker container. Below is my Dockerfile.
FROM python:3.8-slim-buster AS final-image
# R version to install
ARG R_BASE_VERSION=4.1.0
ARG PREBUILD_DEPS="software-properties-common gnupg2"
ARG BUILD_DEPS="build-essential binutils cmake gfortran lib... | I rewrote the last bit of your packages.R as follows:
install.packages(package_ls, Ncpus=16)
This gave me a 3x speed improvement over a run with Ncpus=1 (189s vs 719s).
|
68,722,510 | 68,726,729 | Could I write a library such that when loaded it first generates a dataset which could later be accessed by other functions? | Normally libraries' functions are only executed when called (unlike normal program which has an entry point like main()), but in this case I would like to ship a library that requires a data set, which the data set is too big that's it'll be better to generate on its own.
Which makes me wonder could I write a library t... | For cases like this I would recommend to use a static local variable
//header
struct Data{
Data() {
//Complex intialization code goes here
}
};
Data& data_gen() {
static Data data;
return data;
}
//caller/main
auto Data = data_gen(); //Initialization code run once
auto Data2 = data_gen(); //Reuse the variabl... |
68,722,691 | 68,722,862 | Why is this value downcast (static_cast to object type) allowed in C++20? | To my surprise, gcc 11.2 accepts this code, but only in C++20 mode:
struct Base {};
struct Derived : Base { int i; };
int f(Base& b) { return static_cast<Derived>(b).i; }
// ^~~~~~~ oops, forgot the `&`
Likewise, MSVC 19.29 accepts it in C++20 mode and rejects it in C++17 mode, but cla... | It is legal in C++20.
[expr.static.cast]/4:
An expression E can be explicitly converted to a type T [...] if T is an aggregate type ([dcl.init.aggr]) having a first element x and there is an implicit conversion sequence from E to the type of x.
[dcl.init.aggr]/2:
The elements of an aggregate are: [...] for a class, ... |
68,723,180 | 68,731,796 | How to force the const find to be called | I'm coding with std::map in C++11.
I've read this link, which told me that the C++11 standard guarantees that const method access to containers is safe from different threads.
As my understanding, it means that std::map::size() is thread-safe, because this function is declared as size_type size() const noexcept;.
Now I... | The general rule is that const is multiple-reader safe, and other operations are not.
But a number of exceptions are carved out. Basically, the non-const operations returning iterators or references to existing objects (no object is created) are also considered "reader" operations, and are multiple-reader safe. Using... |
68,723,338 | 68,723,513 | no instance of overloaded function std::unordermap.insert | I declared a stream class, but when defining its member function, it always reports an error when I want to insert something into the private member unordered_map, I want to ask How to solve this?
stream.h
#include <unordered_map>
class stream
{
private:
std::unordered_map<size_t, std::string> word_count;
public:
... | If build the program with clang++, we get more clear error messages:
source>:17:16: error: no matching member function for call to 'insert'
word_count.insert({ 1,"dfs" });
~~~~~~~~~~~^~~~~~
/opt/compiler-explorer/gcc-11.1.0/lib/gcc/x86_64-linux-gnu/11.1.0/../../../../include/c++/11.1.0/bits/unordered_map.h:557:... |
68,723,412 | 68,723,453 | what is the exact range of long double in c++? | I've been googling for hours and still can't find the exact results of "what is the range of long double in c++". some say long double is the same as double. but sizeof double is 8 bytes and sizeof long double is 16 bytes. note that I'm using gcc.
| Why not ask your compiler? std::numeric_limits<long double> is defined.
long double smallest = std::numeric_limits<long double>::min();
long double largest = std::numeric_limits<long double>::max();
long double lowest = std::numeric_limits<long double>::lowest();
std::cout << "lowest " << lowest << std::endl;
std::cout... |
68,723,618 | 68,724,005 | Operator << in C++, "no operator found which takes right hand-operator" and "already has a body" error | I have some code that is supposed to overload the operator << and be able to print a matrix object, but for some reason, it fails. Here's the code for it: (Matirx.h file)
#pragma once
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
template <int N=1, int M=1, class T = int>
class Matrix {
... | Several problems with this. First in the declaration you have to specify the template arguments. As the whole class is templated, you don't need to explicitly add an other template before, but you need Matrix<N,M,T>.
The second issue is that you treat friend std::ostream& operator<<(...) as if it was a member function ... |
68,723,754 | 68,723,943 | Qml context object is null on app shutdown | This is my code.
I get those errors in the console every time I quit the application.
Properties work just fine during execution, but I get this annoying warning every time.
qrc:/search.qml:17: TypeError: Cannot read property 'isConnected' of null
qrc:/search.qml:18: TypeError: Cannot read property 'scanStatus' of nul... | You have to verify that utility is not null:
property bool connected : utility ? utility.isConnected : false
property bool scanRunning : utility ? utility.scanStatus : false
property var searchedDevice : utility ? utility.device : null
|
68,724,124 | 68,724,371 | suggested alternative: ‘ctime’ in C++ | I was trying to put together a small program to see how the destructor was called and I noticed a strange behavior that I couldn't understand.
Why is it suggesting 'ctime' here that seems to have no context ?
jrangab@ubuntu:~/progs$ g++ --std=c++11 mk_shared_issue.cpp
mk_shared_issue.cpp: In function ‘int main()’:
mk_... | As choice is not declared, you have an error.
Compiler tries to help to fix the "typo" by finding the nearest identifier available.
and Nearest identifier (with some edit distance) for choice seems to be (as you have using namespace std;, std::)ctime (2 replacements, one deletion).
|
68,724,617 | 68,724,715 | Is possible to invoke a templated lambda with explicit specialization? | I'm trying to use a lambda which have two specializations, but it seems I'm doing something wrong. I tried to search here, but I couldn't find nothing, except this:
How to invoke a lambda template?
Which doesn't help too much in my case. Please, could you tell me how should I invoke lambdas with my specializations? I'm... | It is not the class/variable which is template, but its operator:
testLamb.operator()<int, 4>(4);
|
68,724,845 | 68,725,571 | Unable to print to console in C++ | I've been having some trouble with printf, stdout & stderr.
I've seen the questions like this, with the issue being related to \n on here already, but I'm already ending my strings with \n to no avail.
I'm fairly certain that this is due to compiler settings, because printing on the default settings works fine. However... | My issue was that I'd copied some compiler arguments off of google. One of them, "-mwindows" suppresses console output.
@HolyBlackCat found this, but left a comment rather than an answer, so I can't mark it as a solution. If Holy reposts their comment as an answer, I'll delete this, and give them the credit
|
68,725,448 | 68,725,518 | How to convert ostream into a string | In a function i'm passing ostream and wants to convert into a string.
void func (ostream& stream) {
/* Needs to convert stream into string */
}
| void func (ostream& stream) {
/* Needs to convert stream into string */
std::stringstream ss;
ss << stream.rdbuf();
std::string myString = ss.str();
}
|
68,725,621 | 68,728,324 | Queue.empty() is false, but the queue size is 0 | I have a std::queue<std::vector<char>> GLOB_DATA_QUEUE; I'm using to tranfer data from one thread to another. I'm having a strange bug when trying to read from the queue. Here's my read code (updated to be completely self-contained):
#include <vector>
#include <queue>
#include <iostream>
// global data pipe object in... | As @G.M. noted in comments above, replace
if(!GLOB_DATA_QUEUE.empty());
with
if(!GLOB_DATA_QUEUE.empty())
in addition, add -Wall to your compiler flags, this is something a compiler can and will catch if you say "please tell me if I'm doing something obviously wrong".
|
68,725,907 | 68,788,662 | How can I write TMP code of below question C++ | I am quite new to TMP world though I can easily understand the code but have problem writing new. I was given below question which I couldn't solve. Can someone help me understand how could I have done this.
Below is the description of the question
template<int... Xs> struct Vector;
It can be used like this:
Vector<... | Here's a simple way to implement this zip metafunction in c++14 using partial template specializations:
template <int...> struct Vector;
template <typename...>
struct zip;
template <int... Is>
struct zip<Vector<Is...>> {
using type = Vector<Is...>;
};
template <int... Is, int... Js, typename... Vectors>
struct z... |
68,726,743 | 68,727,628 | Static constexpr data member initialized off-class, and a possible workaround? | From elsewhere I know that it's not possible in C++17 to declare a static constexpr data member without its immediate initialization (although yet elsewhere they use such example).
// --- in header ---
struct Data{
LPCTSTR str;
int i;
};
class C{
public:
static constexpr Data MyData; // VS complains: this ... | The key point is that constexpr does not mean "exists only at compile time", but instead "can also be used at compile time. So as long as you don't access the constexpr variable in a way that requires the value to be accessible at compile-time, it can be treated as if it was a const.
In fact, with the code you posted, ... |
68,727,087 | 68,766,937 | Change dialog font at runtime | I'd like to change the font of a few dialogs. The fonts of these dialogs are not to be changed using the ressource editor they are to be changed at runtime.
The dialogs in question are all based on ATL/WTL and they're declared pretty much like the following example:
class CDiscardErrorDlg :
public CDialogImpl<CDiscardE... | just wanted to let you know that I have found a solution to the problem:
Here's what to do:
derive a class from CDialogImpl
overwrite DoModal
load the DLGTEMPLATE template in memory and
take an instance of CDialogTemplate to change the template's font
pass the modified template to DialogBoxIndirectParam
template <... |
68,727,767 | 68,728,119 | Adjusting the speed of 2 different object on console | I'm making a simple game like Google's Dinosaur Game. As you pass the obstacles, their speed increases as well as the Dino. What I wanna do is make Dino's speed constant while obstacles speed increases.
while (1)
{
if (GetAsyncKeyState(VK_SPACE) < 0 || action) // checking if the user press SPACE
{
if (... | You don't want to use sleep_for. It can sleep for longer and offers no timing guarantees. What you want it a fixed update game loop. You can look in popular game engines to see how it's implemented.
But it boils down to the following pseudo-code:
//mainloop
// get a number of frame based on time.
// take a number of fr... |
68,728,832 | 68,733,366 | Why am I getting compiler warnings for these explicit instantiations? | I have this header file and source file that are a part of a static library:
vector2.h
#pragma once
namespace lib2d
{
template<typename T>
struct Vector2
{
Vector2();
Vector2(const T& X, const T& Y);
T x;
T y;
};
}
template <typename T>
lib2d::Vector2<T>& operator +=(lib2d::Vector2<T>& left, const... | As mentioned in my comment: an explicit template instantiation must appear after the template definition.
See https://en.cppreference.com/w/cpp/language/function_template:
An explicit instantiation definition forces instantiation of the function or member function they refer to. It may appear in the program anywhere a... |
68,728,872 | 68,729,002 | std::array member in template class vs vector | I have a class A that needs to hold a container member generators with N elements. This N is typically small, of the order of 1 -- 100 objects in most applications and the contained members are used intensively in the application. Moreover, N is known at compile time. Now I'm faced with a design choice of having the m... | Because N is known at compile time and not really large I'd prefer the template version.
You don't need to include other types in your header. You could make "Generator" a template-parameter, too.
You coulde write:
//A.h
#pragma once
#include <array>
class Generator;
template <
unsigned int N,
typename Gener... |
68,729,032 | 68,729,451 | How to record screentime in c++? | I am a newbie to C++ and wanted to create a Screentime application like in ios for windows. But unfortunately, I am stuck after creating the default bootstrap by using visual studio 2019. Can anyone suggest to me what I should do next and other related resources?
I just wanted to create a simple app (let's say screenti... | The following Windows APIs should help with this:
GetForegroundWindow will return the window the user is currently working in.
GetWindowThreadProcessId will retrieve the process ID corresponding to that window.
There's an answer here which shows how to map the process ID to a process name.
It's then a matter of do... |
68,729,199 | 68,729,300 | C++ - work with file (read file) then show in the console | I would like to read the content from the text file by C++ , I wrote the code as below:
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
ifstream inpu... | Because the operator>> to read std::string from std::ifstream skips leading whitespaces. Newline characters is one kind of whitespace characters, so they are ignored.
|
68,730,353 | 68,731,223 | Open CV has problem with opening webcam stream | So I'm trying to make simple computer vision app that displays different colored square around your face in live webcam feed.
The problem is when I start the app using vscode terminal my laptop webcam just turns on for some time and then closes but no app window appears?
The error in the terminal:
[ WARN:0] global C:\U... | Try to add if successful_frame_read:, to check whether the frame got successfully read or not. The if statement ensures that only readable frames get processed. This works because the return value of successful_frame_read is a boolean which, as you may guess, tells you if the frame was successfully read. You may need i... |
68,730,425 | 68,730,939 | C++ Lookup and retrieve a C++ type based on a run-time byte/char | I receive a large number of different messages. Each message contains a messageType byte, which I use to reinterpret_cast to a corresponding struct.
So there's an implicit, compile-time mapping between the message type and the struct representing the message.
Here's a basic implementation:
const char* bytes = "";
const... | C++ templates cannot generate type-based cases. Instead you can recursively call a static method in a template class. For example, reflect::cast:
#include <cinttypes>
#include <stdexcept>
#include <iostream>
template <char, typename>
struct p;
template <typename ...>
struct reflect;
template <>
struct reflect<> {
... |
68,731,120 | 68,731,417 | Destructor when is this object out of scope | class Entity {
//attributes
public:
float X, Y;
Entity() {
X = 0;
Y = 0;
cout << "Created Entity!" << endl;
}
~Entity() {
cout << "Entity Destroyed!" << endl;
}
void Print() {
cout << X << ", " << Y << endl;
}
};
void func() {
Entity e;
e.P... |
I don't understand when and how e is out of scope
The scope of e is everything from its declaration to the end of its enclosing block scope:
void func()
{ // start of block scope
Entity e; // e created in the enclosing block scope here
e.Print();
} // end of block scope... |
68,731,168 | 68,747,022 | uwp: How download files when app is in suspended mode | There is queue with links of files to download. I'm trying find the way to continue downloading when application goes to suspend mode.
According to official microsoft documentation suitable class for this is BackgroundDownloader, but it's handles only one current downloading process. It looks wrong to call in loop Crea... | I've found the cause of the unexpected behavior:
The line of code TaskDeferral->Complete(); was at the end of the method at first while it should be at the end of async call.
Therefore, initial implementation (published in question) is correct.
All that had to be done was to Rebuild project.
|
68,731,220 | 68,750,985 | gRPC C++ async client completion queue drain | I have created an gRPC async client written in C++ which makes both streaming and unary requests to a server, using a completion queue.
In the destructor of the client class the Shutdown method of the completion queue is called, then I thought I could call Next to drain the queue and obtain the pending tags, but instea... | It should be that 1 tag into the completion queue, 1 tag out, so all the pending ops will get their tags returned from Next (even if the RPC gets canceled).
The symptom that Next blocks is likely due to there are pending events that is not finished.
You may like to use TryCancel to terminate the call quickly
|
68,731,682 | 68,732,132 | Would reinterpreting data be undefined behavior? | Someone recently brought it up that this:
uint8_t a = 0b10000000;
int8_t b = *(int8_t*) &a;
is undefined behavior, because the value of a is outside of what I can represent in int8_t. Can someone explain why exactly this is undefined behavior?
My main issue is that the memory is there, and is valid as the memory for i... | Thanks for all the comments. I went down a rabbit hole of strict aliasing and found that the fast inverse square root is undefined behavior, despite my beliefs, but my initial code does not seem to be. Not because uint8_t is special, but as the standard has a rule for signed/unsigned interchange it:
If a program attem... |
68,731,710 | 68,731,898 | C++ compile time checking of type equality in a preprocessor directive | I'd like to check if two POD types are equal at compile time in C++11. I'm trying to #define function names that are appropriate for the Float_T type. Here is what I tried:
#include <type_traits>
using Float_T = double;
// using Float_T = float;
#if is_same<Float_T, double>::value
#define LOG2 log2
#else
#... | Macros are evaluated when the source code is being parsed, much before compilation kicks in, which is why it is nothing more than a simple copy-paste mechanism. So, doing something like this:
#if is_same<Float_T, double>::value
#define LOG2 log2
#else
#define LOG2 log2f
#endif
Is practically impossible since... |
68,732,075 | 68,732,498 | C++ separate structs in to "groups" but allow `std::variant` to see all structs across the "groups" | Please see code below.
I have 3 structs (A, B and C) defined across 2 groups (in reality I have many more). The groups are to provide context within the real-world domain i'm modelling. These groups are implemented via two std::variants (Group1 and Group2).
I have a function which can return any of the underlying struc... | Here is how you can do a trait which produces a type you want - a combination of variant's alternative types. Unlike the other answers, it works with more than two variants being joined ;)
#include <variant>
template<class Variant1, class Variant2, class... Variants>
struct variant_cat;
template<class... Var1, clas... |
68,732,274 | 68,732,279 | Should I explicitly tell the compiler to move the string in this case? | void SomeClass::setName(std::string name)
{
name_ = std::move(name);
}
Is this explicit std::move() redundant for the compiler?
|
Is this explicit std::move() redundant for the compiler?
No. Without std::move() the operand would be an lvalue and thus you would be using the copy assignment operator.
|
68,732,574 | 68,732,658 | Insertion in map using array - error: cannot bind rvalue reference of type ‘int&&’ to lvalue of type ‘int’ | I want to insert values of two arrays : A and T in an std::unordered_map (named unordered) by following code:
for(int i = 0; i < N; ++i)
{
unordered.insert(std::make_pair<int, int>(A[i], T[i]));
}
I am getting the following error:
error: cannot bind rvalue reference of type ‘int&&’ to lvalue of type ‘int’
I g... |
How to do it otherwise?
You are explicitly providing the template parameters of std::make_pair to make the compiler to forcefully choose the following std::make_pair's overload
template< class T1, class T2 >
std::pair<V1,V2> make_pair( T1&& t, T2&& u );
This is not required, let the compiler do the deduction
unorder... |
68,732,863 | 68,733,932 | Templatize downcasting to the derived class and call the corresponding method | I have a routine in the main.cpp where user will specify which mode to execute in the program. Once the mode is specified, the corresponding block will be executed - first downcast the parent solver to the child solver and call the associated solve method in the child class.
std::unique_ptr<SudokuSolver> solver;
... | You would have much clearer code if solve function was virtual.
Also, either the constructor or the solve method should receive the board reference but not both. Having a single way make the code simpler to understand as each algorithm works the same way.
std::unique_ptr<SudokuSolver> CreateSolver(MODES mode)
{
swi... |
68,732,970 | 68,733,726 | Setting multiple checkboxes in QMessageBox | I am trying to set two QCheckBox in a QMessageBox. Only the second checkbox appears. How do I achieve this? Is it better to just create a custom QDialog?
void TextEditor::actionConfigure_triggered()
{
QCheckBox *checkbox = new QCheckBox("Cursor to end of file");
QCheckBox *geometryCheckBox = new... | QMessageBox by default only allows placing a QCheckBox so if a new QCheckBox is added it will replace the previous one. A possible solution is to inject the QCheckBox to the layout directly:
QCheckBox *checkbox = new QCheckBox("Cursor to end of file");
QCheckBox *geometryCheckBox = new QCheckBox("Save and restore geome... |
68,733,232 | 68,733,513 | Define a relative path to `.h` file (C++/ Arduino) | There is a .h file need to be accessed by 2 Arduino files (aka "sketches").
Using a relative path is needed since code is compiled using 2 platform, Linux and Mac, so path can not be the same.
|-DIR_A
| |-DIR_B (incl. Sketch1)
| |
| |-DIR_C (incl. Sketch2)
| |
| |-libfile.h
Inside one of the ... | The Arduino build system copies all your files into a temporary directory, so you end up with something like this:
- TEMP
- dir_b.tmp123 (contains dir_b sketch files)
- dir_c.tmp456 (contains dir_c sketch files)
libfile.h never gets copied!
Now that you know the problem it's easy to work around it. Here are two su... |
68,733,668 | 68,734,132 | using templates for efficient pixel operations | I would like to build a set of pixel conversion routines that I can add together to efficiently transform pixels in an inner loop.
So, for example
template<typename op1, typename op2, .... typename opN> trans(uint8_t data, uint32_t w, uint32_t h){
uint64_t index = 0;
for(uint32_t j = 0; j < h; ++j)
for(uint3... | Guaranteed inlining is not possible with standard C++. However, if you are willing to use a compiler extension, it is doable. GCC (and Clang) provide an attribute called flatten1 that is supposed to do this*:
template <class... Ops>
[[gnu::flatten]] // Everything in the body will be inlined if possible
void process(uin... |
68,734,346 | 68,734,765 | ld: unrecognized -a option `tic-libstdc++' when using -static-libstdc++ in Makefile? | I am trying to link the "fstream" library to my kernel in C++.
But linker has to have -static-libstdc++ in order for this to work (And G++). But when I go to compile, it says:
ld: unrecognized -a option `tic-libstdc++'
PS: I typed the whole thing (-static-libstdc++)
Does anybody know why this is happening?
Here is my ... | -static-libstdc++ is a compiler option, not a linker option. You already set the linker to link the object files with static libraries (-static). Use -lstdc++:
ld -z max-page-size=0x1000 -Ttext=0x01000000 -static -Bsymbolic -o $(TARGET) $(OBJS) build/GDT/GDTASM.o -lstdc++
Libraries must be listed after object files.
I... |
68,734,672 | 68,742,781 | glGenerateMipmap(GL_TEXTURE_2D) Exception Trhown | I am trying to put texture in my model, but when I try running my code I get the following error:
Exception thrown at 0x00007FFE262AE37C (ig9icd64.dll) in COMP371.exe: 0xC0000005: Access violation reading location 0x000001799C69D000.
Can someone please help me understand why I am getting this error?
Here is my code fo... | It's not glGenerateMipmap that crashes, it's glTexImage2D. And that happens because you're passing it invalid data and/or invalid format specification. The layout of data must match the format and dimensions you pass to glTexImage2D. The depth value returned by stbi_load for example tells you, how many components (each... |
68,734,721 | 68,739,674 | Why do fields in non-mutable lambdas use "const" when capturing const values or const references? | As seen in the question lambda capture by value mutable doesn't work with const &?, when capturing a value of type const T& using its name or [=] in a mutable lambda, the field in the hidden class gets type const T. It could be argued for that this is the correct thing to do for mutable lambdas.
But why is this done fo... |
Did I miss something important, or has it simply been standardised this way to make the standard more simpler somehow?
The original lambda proposal,
N2550: Lambda Expressions and Closures:
Wording for Monomorphic Lambdas (Revision 4)
differentiated between the captured object's type and the type of the correspondin... |
68,734,916 | 68,734,968 | C++: use of Lambda function inside the accumulate method from <numeric> | I have a bi-dimensional vector< vector<int> >, say
contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]
I want to use accumulate to get the sum of the first elements, so I resort to a lambda function in order to access the right dimension in the vector of vectors:
#include <iostream>
#include <vector>
#include ... | The trouble comes from the types of parameters you have in the passed functor. Let's look into the documentation:
... a binary operation function object that will be applied. The binary
operator takes the current accumulation value a (initialized to init)
and the value of the current element b - cppreference.com
That... |
68,735,258 | 68,735,367 | What is difference between allocated memory and existing address in CPP? | int *n=new int;
*n=20;
cout<<n<<endl<<*n<<endl<<&n;
When compiled above code I get output as
0xa41510
20
0x6ffe08
Now what is difference in 'n' and '&n'. If new memory is allocated to 'n' then why its address is different?
Sorry if this is kind of silly.
| n
-----------
| 0xa41510 |
------------
address : 0x6ffe08
--------
| 20 |
--------
address : 0xa41510
When you write
int *n=new int
you are telling that you need a memory to store an integer type so new returns the address of memory location allocated which is then stored in n
After statement
*n=20
You ... |
68,735,260 | 68,735,626 | Memset too slow on large data. Any alternatives? | I have a large cv::Mat with dimensions (100,32768). I update it for every frame in a video stream. Before updating, I need to set everything back to zero so I execute
memset(myMat.data,0,100*32768*sizeof(int))
which takes 5ms on average.
Surprisingly(at least to me) in debug mode I get the same times, if not faster one... | DDR 4 3k ish caps out at a bit under 100 GB/s DDR 3 800 is 6.4 GB/s.
Your speed is about 12 MB/5ms, or 2.4 GB/s.
So depending on your RAM, you might be near max speed for your hardware. A factor of 2 ain't bad.
You are working on a modestly sparse array. It is possible that a non contiguous buffer might be a better ... |
68,736,477 | 68,736,835 | Is accessing memory after a destructor call undefined behavior? | I'm wondering if the following is undefined?
int main()
{
struct Doggy { int a; ~Doggy() {} };
Doggy* p = new Doggy[100];
p[50].~Doggy();
p[50].a = 3; // Is this not allowed? The destructor was called on an
// object occupying that area of memory.
// Can I access it safely?
if (p[50].a == 3);
}
I... | Yes it'll be UB:
[class.dtor/19]
Once a destructor is invoked for an object, the object's lifetime ends; the behavior is undefined if the destructor is invoked for an object whose lifetime has ended ([basic.life]).
[Example 2: If the destructor for an object with automatic storage duration is explicitly invoked, and t... |
68,736,845 | 68,847,320 | reduce_parallel is not a thread-safe function? | I want to call parallel_reduce to sum the vector elements. But I find that if the vector elements is enough, the result is not correct. Please help me how to use this function.
// prepare data
const size_t allNum = 1000000;
std::vector<double> a;
for (int i = 0; i < allNum; ++i)
{
a.push_back(do... | I tried running the above code. It was working fine and got the correct results too!
For more information about parallel_reduce, refer to the below links:
https://software.intel.com/content/www/us/en/develop/documentation/tbb-documentation/top/intel-threading-building-blocks-developer-reference/algorithms/parallelreduc... |
68,736,937 | 68,737,123 | Make a Class variable const after declaration (run time) (with some class method) | I have a template:
template<typename T>
struct Parameter {
T value;
std::string name;
Parameter(std::string name, T value) : name(name), value(value){}
void fix() {
// Fix this->value (make this->value const)
}
void print() { std::cout << value << std::endl; }
};
and I would like at ... | If you want to maintain the same interface, and marshalling access to value through accessors is something you want to avoid, then you could isolate the "fixable" feature in its own dedicated type that implicitly converts to/from T:
template<typename T>
class fixable {
bool fixed_ = false;
T val_;
public:
fixabl... |
68,737,009 | 68,737,086 | Why does overloading a function with std::function require an intermediate variable | #include <functional>
bool f1(int a, int b)
{
return true;
}
int main()
{
// This compiles
std::function<bool()> f2 = std::function<bool()>(std::bind(f1, 1, 2));
std::function<bool()> f1 = f2;
// These don't compile
//std::function<bool()> f1 = std::function<bool()>(std::bind(f1, 1, 2));
... | Variables enter scope as soon as they're declared. That means that they're in scope for their initializer.
In std::function<bool()> f1 = std::bind(f1, 1, 2);, the f1 on the right-hand side of the = refers to the f1 you declared on the left-hand side.
Note that this is not in any way unique to std::function or anything... |
68,737,895 | 68,738,247 | A function returning only one index instead of two or more | C++ | inside Caleb Curry's C++ course I have stumbled upon a piece of code about classes with a function returning an index if found two objects with the same data members. Here's the function:
int indexuser(std::vector<User> &users, User user)
{
for(int i = 0; i < users.size(); i++)
{
if(users[i].fname == us... | The function checks if user(of type User) is present in the vector users. If found it will return index of the user found in vector and if not found, it will insert the user (usingusers.push_back(user)) in the vector and return its index (which will be users.size()-1).
And whenever (any) function finds return statement... |
68,738,915 | 68,739,474 | Pass captures to lambda | Would there be a way to reuse my lambda?
constexpr auto contains(const suit_t& suit) const noexcept -> const bool
{
return std::find(cbegin(), cend(), [suit](card_t* card) constexpr { return card->suit == suit; }) != cend();
}
constexpr auto count(const suit_t& suit) const noexcept -> const long long
{
return ... | How about something along the lines of this:
class MyLambdaReplacement {
const suit_t& _suit;
public:
MyLambdaReplacement(const suit_t& s) : _suit{ s } {}
constexpr bool operator()(card_t* card) {
return card->suit == _suit;
}
};
constexpr auto contains(const suit_t& suit) const noexcept -> const boo... |
68,739,004 | 68,739,207 | C++ capture error "throwing an instance of 'std::out_of_range'" | This will be my 1st question here. I have came across an issue that I would like to resolve in a program that I'm working on (doing some intern/developer shadowing tasks).
I have a std::map data structure. Every time I pass from the cmd line a value that is not mapped I get the:
terminate called after throwing an insta... | you should surround your std::map::at(key) call inside a try/catch block as in
std::map<std::string, int> my_map = {{"one",1}, {"two":2}};
try
{
auto val = my_map.at("three");
std::cout << "my value at 'three' is " << val << "\n";
}
catch(std::out_of_range const & e)
{
std::cerr << "oops 'three' is not in... |
68,739,369 | 68,739,435 | How to set includes to be relative to the relativity of the source file from the root path? | Sorry if my phrasing of the question is a bit confusing:
How do I set includes to be relative to the relativity of the source file from the root path?
I am trying to compile a C++ project (not my own), and there are two folders: src and include.
The .cpp source files are located in src and the header files are located ... | There is no magic compiler option to do what you want.
Solution 1: Change the #include directives to be relative to the include directory.
Solution 2: Don't use separate directories and move the headers into src directory.
|
68,739,569 | 68,739,656 | Why Shell_NotifyIcon not showing balloon notification? | I have written a sample application to see how balloon notifications can be added to a Win32 application. Can someone please point out why Shell_NotifyIcon() is not showing balloon notifications?
GetLastError returns 2147500037 for Shell_NotifyIcon().
#include <Windows.h>
#include "shellapi.h"
int main()
{
NOTIFYI... | Should use NOTIFYICONDATA_V3_SIZE instead of NOTIFYICONDATAA_V3_SIZE, as you clearly use Unicode (seen from lstrcpyW and L"..."), and you use default NOTIFYICONDATA
Should just use nid.cbSize = NOTIFYICONDATA_V3_SIZE; or nid.cbSize = sizeof(NOTIFYICONDATA), you don't want to have size of integer constant.
Should also c... |
68,739,641 | 68,740,778 | error while pushing back pointer vector elements to non pointer vector c++ | I am trying to push back elements of pointer vector ptrVctor to nonpointer vector myvector2 through below for loop in function full when the input words size is greater than or equal to 5 but its not happening. When I enter less than 5 words program runs fine. But when I enter more than 5 words program didnt worked as ... | when you enter 5, in the function int full(int i ), your program deletes ptrVctor.
When you then enter 6, the ptrVctor is already deleted, but you use ptrVctor->size() so it just terminates.
|
68,740,131 | 68,740,296 | What is the best way to select sub-class to instantiate at compile time via #define | I currently have an IoT gadget that has different Display subclasses depending on what hardware I am compiling for. There is a base class called Display and have various subclasses like D_oled32 and D_oled64. At compile time I set a build flag via #define so that when I instantiate the the Display object it will pick... | You should not "define" a type but use using to set an alias for a type:
#if defined(MAX7219)
#include "Displays/D_max7219.h"
using DISPLAY_CLASS = D_max7219;
#elif defined(EPD)
#include "Displays/epdfeather.h"
using DISPLAY_CLASS = D_epdfeather;
#elif defined(OLED32)
#include "Displays/D_oledy32.h"
using D... |
68,740,550 | 68,740,758 | Could someone explain the meaning of vector<Node*>() | I'm solving the Clone Graph in Leetcode, but I encountered a problem inside the following codes
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
... | Actually this statement in the constructors of the class Node
neighbors = vector<Node*>();
is redundant.
There is used the move assignment operator that assigns an empty vector created by calling the default constructor vector<Node*>() of the class std::vector<Node *> to the already created empty vector neighbors that... |
68,741,182 | 68,741,430 | Accessing member array of class using containing class array through pointer - contained array of class object is private | I have as a class member an array of that class (obj) and I would like to create array of the Box class (which is the containing class) and access xyz obj[5]; through a p pointer object member of that Box class.
The obj array is private but I think I can access it using pointer. Am I correct?
#include <iostream>
#incl... | There are a number of issues in your code. First, I'm not sure what you are trying to accomplish using the parentheses around obj but the member access operator (->) doesn't work like that – it must be followed immediately by the member's name.
Maybe what you want is something like this: ( (b + 2)->obj )->x = 5; ? Howe... |
68,741,183 | 68,741,280 | an error while use sizeof(boost::lockfree::queue<std::string>) | I got an error about sizeof(boost::lockfree::queuestd::string). My code is as below:
Global.h:
extern boost::lockfree::queue<std::string> &imgPendingQueue;
class Initializer
{
// do something
};
Global.cpp:
#include "Global.h"
static char imgPendingQueueBuf[sizeof(boost::lockfree::queue<std::string>)];
boost::lockf... | lockfree::queue<T> requires T to have a trivial destructor (among other requirements, see here)
std::string is not trivial. Hence queue<std::string> is ill-formed and your reinterpret_cast trick will not help.
|
68,741,277 | 68,742,743 | Cmake cant find the required Packages for me | So My Workspace Screenshot After Trying a while i cant Get Cmake To find the required packages even after i did everything as shown in vcpkg
cmake_minimum_required(VERSION 3.0.0)
project(TEst VERSION 0.1.0)
include(CTest)
enable_testing()
set(CMAKE_TOOLCHAIN_FILE "N:/Vc-PKG/vcpkg/scripts/buildsystems/vcpkg.cmake")
fin... | You can't set CMAKE_TOOLCHAIN_FILE after the call to project(). That's the command responsible for loading the toolchain file in the first place. Move it before the call to project() or better yet: set it at the command line or in a preset.
Also, unless you're actually using CMake 3.0.0, you shouldn't set it as a minim... |
68,741,621 | 68,741,755 | Why is my r-value deleted after I have successfully assign it to an object? | When exactly is destructor being called? Initially, I thought that destructor were supposed to be called when we use the:
delete [] str;
Then, when I came accross the "move assignment" topic, I notice that the destructor is called directly after I NULL my rhs.str in my move assignment method.
main.cpp
int main() {
My... |
When exactly is destructor being called?
Destructor is called when an object is destroyed of course. When that happens depends on the storage duration of the object.
I thought that destructor were supposed to be called when we use the:
delete [] str;
That's one case where an array of objects with dynamic storage d... |
68,741,991 | 68,742,080 | C++: Identifier of class name in same namepace undefined | I have two classes SHCalculator and SphericalLightProbe in separate files. I completely stripped them down to present the error I'm getting so these are the four files:
SHCalculator.h
#pragma once
namespace SphericalHarmonics
{
class SHCalculator
{
private:
public:
void Test();
Spherica... | You are missing the includes in your SHCalculator.h header;
Try something like:
#pragma once
#include "SphericalLightProbe.h"
namespace SphericalHarmonics
{
class SHCalculator
{
private:
public:
void Test();
SphericalLightProbe Test2();
};
}
Note that if your SHCalculator.cpp fi... |
68,742,051 | 68,773,379 | Communicating between coroutines in ASIO | I have a coroutine that listens asynchronously on an asio UDP socket. When it receives a message it co_spawns a new co-routine to handle the message and then goes back to listening on the port. This new coroutine may need to do additional communication on the same UDP socket. What is a good way to make sure the replies... | I figured out a decent solution but I would love to find a better one. I can create a future class that contains an asio::steady_timer. Then I can handle timeouts in a neat way and I can just call cancel the timer when the original coroutine gets a reply. Seems pretty overkill and steady_timer is huge (112 bytes?!) but... |
68,742,140 | 68,742,219 | Product Array Puzzle | Problem: You are given an array of ‘N’ integers. You need to return another array ‘product’ such that ‘product[i]’ contains the product of all the arrays except the element at the ith position in the given array.
Note:
As the product of elements can be very large you need to return the answer in mod (10^9+7).
My Code
v... | You will have to take modulo every time you calculate multiplications to prevent overflow.
Also casting to a 64-bit (or more) type is required if int is not capable to store the product before taling modulo.
vector < int > productPuzzle(vector < int > & arr, int n) {
const int MOD_BY = 1000000007;
vector<int>... |
68,742,552 | 68,742,714 | Bitwise leftshift as power of 2 | Why x = 1<<n gives x = 2^n ?
I am learning different bit-wise operation and this is one of basic. Can you help me here, what are different bit-wise manipulation I can use?
| In a binary notation, the position of each digit has a value: 1 for the rightmost position, 2 for the next position to the left, 4 for the position left of that, and so on. When the positions are numbered from right to left as positions 0, 1, 2, 3, and so on, then the value of position i is 2i.
A binary numeral represe... |
68,742,911 | 68,743,139 | Can Arduino ESP8266 sscanf handle %lld? | I'm having an issue with Arduino ESP8266 and the sscanf function. I'm trying to parse a 64 bit integer from the string I received from the serial port like this:
int64_t temp_freq = 0;
sscanf(buffer, "FOUT = %lld Hz\r\n", &temp_freq);
EDIT: I also tried `"FOUT = %" SCNd64 " Hz\r\n", with the same result
I know I got t... |
is it simply not implemented correctly on the platform?
Your toolchain is using newlib as a C standard library implementation and most probably you are using it's nano version. Newlib-nano does not come with long long support in printf/scanf family functions.
You can:
Use full newlib version instead of nano version.... |
68,743,239 | 68,744,415 | Vulkan validation layer CreateDebugUtilsMessengerEXT Allocator is NULL | I am trying to follow https://vulkan-tutorial.com/ and a Udemy course on my journey to understand Vulkan.
So far I was able to follow everything but the validation layers are not working and I have no idea why.
Tried the following:
check for typos
check validation layer present in vulkan configurator
installed sdk on ... | You are enabling Debug Report extension, but then you try using Debug Utils messenger instead.
|
68,743,251 | 68,743,389 | Libcurl C++ Ldap Request | i am new to cUrl.
What i need todo is a curl request to an ldap server.
So far the request works fine over the command line:
$curl ldap://XXXXXXXXX:389/DC=XXXXXXXXX,DC=DE?mail?sub?(sAMAccountName=XXXXXXXXX) --user s_ad_XXXXXXXXX:Password
After trying to get this done in my C++ CMake Project. I issued this error Code f... | You cannot just bung everything into the CURLOPT_OPT_URL field. The --user bit should be separated into a separate parameter:
curl_easy_setopt(curl, CURLOPT_URL, "ldap://XXXXXXXXX:389/DC=XXXXXXXXX,DC=DE?mail?sub?(sAMAccountName=XXXXXXXXX)");
curl_easy_setopt(curl, CURLOPT_USERPWD, "s_ad_XXXXXXXXX:Password");
|
68,743,609 | 68,759,833 | Full C++ LibTorch API on Moblie [Android] | I'm trying to compile a programme which uses LibTorch for android.
But the libraries built by script/build_android.sh in the pytorch repo, contain only the torch.jit Module. I need the torch.nn Module.
Is it possible to access the full C++ LibTorch API ? If so how can I build it ?
| It would seem that by setting NO_API to OFF and BUILD_MOBILE_AUTOGRAD to ON in the root CMake file, your can build the api and thus torch.nn.
|
68,744,580 | 68,744,750 | how does a pointer know its at the end of a heap memory? | I am quite confused about how to go about the problem below any tip would be beneficial, thanks in advance!
For instance
int * p = new int [5];
if I choose not to use p[0] for initialization using a for loop that looks like
for(int i = 0; i< 5;i++){
p[i] = i;
}
How can I initialize values in the block of memory on ... |
how does a pointer know its at the end of a heap memory?
A pointer is "dumb". It doesn't know such thing.
How can I initialize values in the block of memory on the heap using the dereference and increment operators? I don't think the code below is correct.
Here is a corrected version:
int* it = p;
int* end = p + 5;... |
68,744,591 | 68,744,717 | C++: How to iterate over a list of class types for typeid verification and downcasting? | I would like to perform a down casting at execution time.
For what I read, if I want to do it, I need to compare the typeid of my polymorphic pointer with those of my derived classes, then do the casting in the correct type.
Plus, let's assume that I have a large number of derived classes.
This implies I have to write ... | You say "polymorphic" but what you want to do is the opposite of it.
Instead of trying to work against polymorphism you could actually use it. If all subclasses have their own implementation of a virtual function then the caller does not need to care what the actual dynamic type of the object is. That is runtime polymo... |
68,744,868 | 68,744,954 | How to map the Enum template to type template? | I have got a template function that currently looks like this :
#include <string>
enum class Enum { EVENT_ONE, EVENT_TWO };
template<Enum e, typename T>
void MyFunc() { }
int main(int argc, const char* argv[])
{
MyFunc<Enum::EVENT_ONE, int>();
MyFunc<Enum::EVENT_TWO, std::string>();
}
I would like to create... | You can write a enum_to_type trait and specialize it accordingly:
#include <string>
enum class Enum { EVENT_ONE, EVENT_TWO };
template <Enum e> struct enum_to_type;
template <> struct enum_to_type<Enum::EVENT_ONE> { using type = int; };
template <> struct enum_to_type<Enum::EVENT_TWO> { using type = std::string; };
... |
68,745,215 | 68,745,324 | Why does int addition though pointers take one less x86 instruction than int multiplication through pointers? | I have the following C/C++ code (compiler explorer link):
void update_mul(int *x, int *amount) {
*x *= *amount;
}
void update_add(int *x, int *amount) {
*x += *amount;
}
Under both clang and gcc compiling as C or as C++ with at least -O1 enabled, the above translates to this assembly:
update_mul: ... | The IA-32 architecture specification (alternative single-page link) shows that there is simply no encoding for IMUL where the destination (first argument) is a memory operand:
Encoding | Meaning
IMUL r/m8* | AX ← AL ∗ r/m byte.
IMUL r/m16 | DX:AX ← AX ∗ r/m word.
IMUL r/m32 ... |
68,745,453 | 68,838,155 | How can I use library in cmake-base project if sources and CMakeLists.txt file for this library I have to generate by external tool | I have to generate sources by external tool (I generate c++ classes from IDL-files for fastDDS messages), this tool also generate CMakeLists.txt file that allows me to compile generated files to <msgs_lib>.a file.
In my big superproject for one exec-target I wonna check existence of generated files and their building r... | To solve your problem, I suggest not relying on a cmake script from an external tool, but instead managing the generation from IDL files and building the library. I assume that your project has a folder with IDL files, let's call it idl. In this folder also place a CMakeLists.txt file to generate and build the library.... |
68,745,573 | 68,745,603 | Prevent pointer from being passed as array | So while it is common/typical to accept an array that has decayed to a pointer like the following
#include <iostream>
void example(int* data)
{
std::cout << data[0] << ' ' << data[1] << ' ' << data[2] << std::endl;
}
int main()
{
int data[3] = {1, 2, 3};
example(data);
}
I noticed that you can also seemi... | In fact,
void example(int data[3])
is
void example(int data[])
or
void example(int* data)
You need
void example(/*const*/ int (&data)[3])
to have array reference, (and so rejecting pointer or array of different size).
|
68,745,645 | 68,745,785 | How I can specialize template when a method is available? | I wonder how I can have a specialized template for when my type has a specific method. Let's take the following code as an example:
template<typename T, typename... Args>
void foo(T&& arg, Args&&... args)
{
std::cout << "called 1\n";
}
template<typename T, std::enable_if_t<std::is_member_function_pointer_v<declty... | You are on the good track, but, with forwarding reference,
decltype(&T::log) becomes decltype(&(Y&)::log) which is invalid.
Using std::decay solves your issue:
template<typename T,
std::enable_if_t<
std::is_member_function_pointer_v<decltype(&std::decay_t<T>::log)>,
int> = 0>
void foo(T&& v)
{
... |
68,745,680 | 68,745,758 | when should i use '&' when overloading an operator? | lets say I got a class A and I want to overload an operator, when should I use
A& operator+(const A& b)
{
A c;
c.val = this->val + b.val
return c;
}
or
A operator+(const A& b)
{
A c;
c.val = this->val + b.val
return c;
}
without the '&' thing?
|
when should i use '&' when overloading an operator?
You should use & on a type when ever you want that type to be a reference.
Typically, a reasonable rule of thumb is to do what the corresponding built-in operators do. If the corresponding built-in operator is a prvalue, then return an object in your overload, and ... |
68,745,729 | 68,898,838 | Qt5 QFileDialog closes parent dialog as well | I have a custom QDialog with a 'Save' button which is supposed to prompt the user with a QFileDialog and save the contents of a Table Widget to a file, but keep the dialog open.
This is the function that opens the dialog and saves the data:
bool ResultsDialog::saveData()
{
QString outfile = QFileDialog::getSaveFile... | You are hooking the termination of the MainWindow to a signal that is sent out while ResultsDialog is still processing. ResultsDialog has MainWindow as its parent so the parent (and its children!!) are destroyed while the child is still running. Nothing good will arise from this construct.
Edit: The Error message you s... |
68,745,828 | 68,747,177 | Function of a C++ DLL does not output text in WPF | I am trying to output text from a C++ function to a textbox in WPF, but when I click the button it outputs nothing.
In the C# Console it worked.
Here the code from the C# console:
namespace ConsoleApp1
{
class Program
{
const string dllfile = "C:\\...";
[DllImport(dllfile, EntryPoint = "main", ... | On Windows (which WPF implies you are using), the BSTR can be created from standard wide-string, and you can try C++ code like:
#include <windows.h> // For BSTR from "wtypes.h" header.
extern "C" __declspec(dllexport) BSTR text_output()
{
return ::SysAllocString(L"something");
}
// ...
Then wrap into string with... |
68,745,874 | 68,746,009 | Match template unconditionally | I would like to call a template function even if std::enable_if_t doesn't resolve to true. It would allow me to reuse one of my existent templates in other context.
Minimal example:
#include <iostream>
#include <type_traits>
template<typename T,
typename = typename std::enable_if<std::is_same<T, int>::value>... | What you want doesn't make sense. Either a call to foo is valid or it isn't. It shouldn't matter who does it. enable_if is used to ward templates from cases where a particular parameter cannot work (or you have an alternate definition where it can). For example, if the definition is going to use a copy constructor, but... |
68,746,373 | 68,753,683 | Unity reduces the number of available OpenMP threads | I use OpenMP in a shared android library. There is a sample method that just checks the number of CPUs and the max number of threads.
int maxThreads = omp_get_max_threads();
int numProcs = omp_get_num_procs();
When I call this method from a basic android application (AppCompatActivity), both values are set to 8 on the... | You don't say which OpenMP implementation you are using, which would certainly be useful to know.
However, assuming that Android behaves like Linux at this level, then what is probably happening is that Unity is setting the process' affinity mask (see sched_{get,set}affinity(...), which reflects the logicalCPUs that th... |
68,746,637 | 68,746,750 | Create a member variable using map cpp | I am trying to call a function using a std::map key value pair. I found this stackoverflow article Calling a function depending on a variable? but the solution
std::map<std::string, std::function<void()>> le_mapo;
does not work and results in a error something like "error: lvalue required as unary ‘&’ operand" using i... | Because ftp is a member function, you are going to have to use a lambda here (well, you could use std::bind, but lambdas have largely superseded that these days).
So you want:
le_mapo["ftp"] = [this](){ ftp(); };
This "captures" this, thus enabling you to call ftp() on the correct object.
&ftp() doesn't work for a num... |
68,747,070 | 68,747,343 | Pascal's triangle - Copying between 2 arrays | #include <iomanip>
#include <iostream>
using namespace std;
int main() {
const int nmax = 15;
int zeile[nmax];
int zeiletmp[nmax];
for(int n = 0; n < nmax; ++n) {
for(int k = 0; k < n; ++k) zeiletmp[k] = zeile[k];
zeile[0] = 1;
zeile[n] = 1;
for(int k = 1; k < n; ++k)... | Your question is ambiguous, but if you want to know where you added the elements in the other array, the following two lines are Your answer.
zeiletmp[k] = zeile[k];
zeile[k] = zeiletmp[k] + zeiletmp[k - 1];
|
68,747,201 | 68,747,491 | Which form is better to use for map | Given a class Ac and a map:
std::map<std::string, Ac> ma;
Which of the following forms is better:
ma["112"] = Ac(); // (1)
or
Ac ac;
ma["112"] = ac; // (2)
Is there any issue using the version 1?
The actual code in context:
struct Ac
{
bool first;
bool second;
};
int main()
{
std::map<std::string, ... | I suppose you do not want to leave the members uninitialized, so lets supply default initializers:
struct Ac
{
bool first = false;
bool second = false;
};
Next, you are looking up the key too often. First you call find and when the element was found you call operator[] which has to find the element again. Inst... |
68,747,489 | 68,747,777 | Is the local variable returned by a function automatically moved in C++20? | Please consider a C++ program, where the function foo builds its returning U object from a local variable of type int using one of two constructors:
struct U {
U(int) {}
U(int&&) {}
};
U foo(int a = 0) { return a; }
int main() { foo(); }
In C++17 mode the program is accepted by all compilers, demo: https://g... | What happens here is that the way that gcc went about implementing P1825.
In this example:
U foo(int a) {
return a;
}
The C++17 and C++20 language rules (no change here) are that we first treat a as an rvalue and if that overload resolution fails (in C++17, it was also required to bind to int&&), then we treat a a... |
68,747,627 | 68,749,684 | Packing unions/structure to avoid padding | I have a structure that looks like this:
struct vdata {
static_assert(sizeof(uint8_t *) == 8L, "size of pointer must be 8");
union union_data {
uint8_t * A; // 8 bytes
uint8_t B[12]; // 12 bytes
} u;
int16_t C; // 2 bytes
int16_t D; // 2 bytes
};
I would like to make this 16 bytes, but GCC is telling... | You could change A to std::byte A[sizeof(uint8_t*)]; and then std::memcpy the pointer into A and out of A.
Worth commenting as to what is going on, and that these extra hoops are to avoid padding bytes.
Also adding a set_A setter and get_A getter may be very helpful.
struct vdata {
union union_data {
std::byte A[... |
68,747,653 | 68,753,187 | Dimension reduction with PCA in OpenCV, wrong dimensions of eigenvectors | I am not sure if this problem is already on stackoverflow, but I could not find it so i decided to open a new question. I am trying to reduce the dimension of a feature Matrix. I have 58 features and 30 instances / measurements. I want to reduce the number of features to 40. But there seems to be a problem with my matr... | Okay, so after finding this thread, I know now what the problem was: I need more instances than features! If I have 58 features, I just need at least 58 samples. This is not a problem for me, because I have enough data, I was just using 30 samples all the time for testing.
|
68,747,763 | 68,820,885 | Boost bjam Jamfile import statement | I have a complex C++ application that is building via bjam (V2) utility (along with some shellscripts to bootstrap the environment)
In the Jamroot file , there are "include(s)" , some of which are documented as builtin , but a lot look like "custom" stuff.
I'm trying to add unit tests and I am having difficulty underst... | So the issue was not so much with boost test framework (although this could be better documented) , the problem was with the linker not being able to find debug variants of various libraries to link against. (Reading the warnings helped.) So while the build worked for the project when run from root , it failed for sub-... |
68,748,006 | 68,748,545 | Can std::span iterators outlive the span object they are created from? | Put it other way, conversely, are std::span iterators invalidated after the span instance is destroyed?
I have a vector I need to iterate over with different layouts. I'm trying to make use of std::span to avoid writing a lot of iterator boilerplate or bringing in an external library dependency. Simplified example:
#in... | I appreciate that this question asks both the positive and negative version of the same question consecutively. Thus...
Can std::span iterators outlive the span object they are created from?
Yes.
Are std::span iterators invalidated after the span instance is destroyed?
No.
This is why you in [span.syn] you see:
tem... |
68,748,114 | 68,748,501 | Red black trees implementation | I am trying to implement insert operation for red black trees. I have written this class with C++ called RedBlack that contains Insert function as follows:
void RedBlack::Insert(int data)
{
printf("init !!!\n");
ColoredNode* myIterator = this->root ; // will iterate throw the tree until it reach... | I hate to say it but a RB insert is rough, wait til you get to deletion! Argh!
If I recall my CS correctly, the root node should always be black and a red node should not have a red node as a child. New nodes should be red. Then after detecting the violation, you rotate the tree and re-color to maintain this invariant.... |
68,749,126 | 68,929,944 | Cannot properly restart application with bash script | here's a problem that is driving me nuts. First off, I am not a Linux expert, so I might just be missing some detail.
I am trying to restart an application (namely rpi-webrtc-streamer, but that shouldn't matter) using a shell script. The reason is that when a configuration change happens I need to update the config fil... | As suggested by jordanm in the comments, I solved the problem by using systemd.
|
68,749,134 | 68,783,064 | eigen: create Vector-like Replicate (access with one index, LinearAccessBit) | I want to create an Eigen::Replicate object that can be accessed like a vector, i.e. with a single index. I got that to work with the fixed-size replicate<Index,Index>(), which I can't use in reality, the non-one factor is not a compile-time constant. It also works when manually creating a Replicate object, but I feel ... | By adding a .reshaped() after the replicate(...) call, the ColsAtCompileTime are set to 1, and therefore, the resulting object can be accessed like a vector:
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
int main(){
Vector3i v (3);
v << 0,1,2;
constexpr int nReplications {2};
... |
68,749,191 | 68,749,288 | C++ in VSCode vs Python | This is my problem, I've been trying to code in C++ in VSCode, so I followed the VSCode tutorial and installed Mingw-w64 via MSYS2 and everything works. But when I compile the file and execute the exe file in VSCode terminal, it's so slow, so I made a test speed with Python and Python wins. There has to be something wr... | This is not about the program itself. This is all about how IDE and command prompt handle such a huge amount of output strings.
Of course, some difference between C++ streams vs python exists, as well. C++ streams do much more work on strings.
Anyway, the key problem is the amount of strings to be printed.
You may try:... |
68,749,299 | 68,749,558 | Is there a function like "corr" from python, in c++ for finding the pairwise correlation of columns? Whilst working with Armadillo/Mlpack? | I need to get this code (Python)
corr = X.corr()
into C++, where X is a huge dataset with more than 10x10 in my case something like nearly 450x30. So there are a lot of columns to calculate the correlations.
I'm working with C++ and Armadillo/Mlpack.
I found another solution on stackoverflow where someone recommende... | I tend to work most with Armadillo from R so this is wrapped in an R context though the simple example function is plain C++. As the documentation will tell you, 'matrix on matrix' also works returning respective pairwise correlations. Here, for simplicity, it is just two columns. Unsurprisingly, R gets the same num... |
68,750,388 | 68,750,721 | Why was `identifier : expression` form of designated initialization deprecated/obsoleted in GCC? | I'm doing some work on a C++ named parameters feature, specifically labelled argument syntax design, and I've found that there is an old deprecated form of designated initialization that uses the identifier : expression syntax rather than . identifier = expression syntax.
See https://gcc.gnu.org/onlinedocs/gcc/Designat... | GCC of that vintage included release notes in a file called NEWS in the source tree. The GCC 2.5.8 distribution has the release notes of 2.5, which says:
The C syntax for specifying which structure field comes next in an initializer is now .FIELDNAME=. The corresponding syntax for array
initializers is now [INDEX]=... |
68,751,261 | 68,752,326 | Are C++ int, int[], float, and especially char *, char[], char are same as these of C. I believe they are premitive so are they same? | There are some datatypes to contain data (in memory I do think). So I like to know these types,
char,char *, char[], -- especially
int, int[], int *, float, decimal, short, long, if there are any other please mention
are same in C and C++.
If they are same then can I use memory functions and string functions and int, ... |
are C++ int, int[], float, and especially char *, char[], char are same as these of C
Yes.
can I use memory functions and string functions and int, float, decimal,binary,etc functions available in C like memset,memcpy,memcmp,etc. and string functions like strcmp, strstr, strlen,etc. in cpp file and complete C++ libr... |
68,751,648 | 68,751,760 | How to interpret C++ left-associativity logic in a strict technical sense? | New to C++ and am currently reading "Accelerated C++" (Koenig & Moo) but struggling to understand the logic of left-associativity in one particular section. Specifically, on p.62, the expression:
is >> s.name >> s.midterm >> s.final;
Evaluates
( is >> s.name >> s.midterm ) >> s.final;
That is, the first term inside () ... | If you are new to the language I think a good interpretation for is >> x is as follows:
is is an object capable of using low level functions to request an input from the keyboard (or another device, including a file)
the << operator is the one to which you can feed is and x so that is does it's job and puts in x what ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.