question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
73,504,974 | 73,507,154 | Why does my c++ xll fail to open when it is linked to another dll? | I have a visual studio c++ solution containing two projects; an xll and a dll (called 'main'). The 'main' dll exports one simple function, like this
#pragma once
// Just for testing exporting from the dll
#ifdef MAIN_EXPORTS
#define PAMAIN_API __declspec(dllexport)
#else
#define PAMAIN_API __declspec(dllimport)
#endi... | By saving the xll and dll in various locations, I established that the xll and dll are fine, but excel doesn't always know where to load the dll from, and when it doesn't it gives the "The file format and extension of xll.xll don't match" error.
|
73,505,580 | 73,505,619 | Can't construct std::function with brace initialization | EDIT: I was being dumb. The functionMaker call is shockingly a function not a constructor, so the braces obviously don't work.
So I have what is basically a factory function for producing a std::function from int to int, a quick minimal example is
std::function<int(int)> functionMaker(int x) {
return [x](int foo){r... | If you'd like functionMaker{} to work, then functionMaker needs to be a class/struct. Functions can only take arguments via (). However, it's relatively easy to make it a class:
struct functionMaker
{
functionMaker(int x)
: f([x](int foo){return foo*x; }) {}
int operator()(int foo) { return f(foo); }
s... |
73,505,645 | 73,519,374 | CMake force include statements to have form #include <mylib/header.h> | I'm currently working on a project with different libraries, where some of their files have similar/equal names or similar/equal names as STL files. This may lead to confusion at a later point in time. Therefore, even it's handy to include my custom library headers by just writing #include<file.h>, I'd like to refactor... | To complete comment from Tsyvarev, you need to modify your header location:
[...]
| |- include
| | |- mylib
| | | |- header1.h
| | | |- header2.h
On a side note, the line:
# link directories
link_directories(../mylib)
is not needed. This function should be used when you need to link with a libra... |
73,505,924 | 73,525,750 | Why does clang-tidy's modernize-use-emplace miss this warning? | a.cpp:
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, int>> a;
a.push_back(make_pair(1, 2)); //caught
vector<vector<pair<int, int>>> b(1);
b[0].push_back(make_pair(1, 2)); //not caught
return 0;
}
clang-tidy -config="{Checks: 'modernize-use-emplace'}" a.cpp
a.cpp:6:4... | Short answer: This behavior is due to bug 56721 in clang-tidy.
Long answer, based on my comment on that bug:
The bug relates to how reference is declared in the container. That in turn causes clang-tidy to not realize that the return value of the accessor is an instance of a relevant container.
The core of UseEmplaceC... |
73,506,037 | 73,506,096 | X-macro driven C++ template class instantiation | I am trying to instantiate a templatized class based on an X-macro. However, this is giving me syntax errors error: wrong number of template arguments (0, should be 1). What is the correct way to instantiate a templatized class from an x-macro?
#include <string.h>
#include <iostream>
#define FOO \
X(, aaa) \
X(... | The issue here isn't that your syntax is wrong, but rather that both branches of the if and else get compiled regardless of whether a is empty or not. The compiler error will trigger because the else branch will try instantiating A<>, which isn't legal.
To fix this, you could consider adding a level of indirection. Her... |
73,506,103 | 73,519,464 | How to use quaternions to store the rotation of a camera? | I'm trying to make a "6 degrees of freedom" camera like the ones used in space games. I would like to learn how to store camera rotation as a quaternion but I can't exactly find anything on the internet to help me (or maybe I don't know what keywords I should be using).
What I want to do is use a glm::quat to store the... | I found the answer to my problem of "How to find the right, up and direction vectors for the glm::lookat function"
All I need to do now is change the world up, right and direction vectors by the orientation of the quaternion like so:
right = glm::normalize(orientation * glm::vec3(1, 0, 0));
up = glm::normalize(orientat... |
73,506,238 | 73,506,651 | Better runtime error in C++ for vectors and address boundary error | In Python, when we access an index out of the array range we get an error output that gives the exact location in the code that had this error:
array = []
index = 0
array[index]
IndexError Traceback (most recent call last)
Untitled-1 in <cell line: 3>()
1 array = []
2 index ... |
only give us a generic Address boundary error
No, it isn't even guaranteed to do that. Accessing out-of-bounds with [] causes undefined behavior in C++. If it happens you loose any guarantee on the program's behavior. It may fail with some kind of error, but it might also just continue running producing wrong output ... |
73,506,576 | 73,506,613 | Storing my file of strings into my vector thinks I am trying to put characters in it? | When trying to use fstream to enter csv data into my program I am having an odd problem using a vector but it works fine with a random-sized array. I am not sure why but the error I am getting from visual studio is that there is no suitable conversion from string to char even though my vector is for strings. I am not s... | Like this
dataStore.push_back(std::vector<string>()); // add a new 'row'
while (std::getline(ss, currentObject, ',')) {
dataStore.back().push_back(currentObject); // push the string onto the last 'row'
std::cout << currentObject << "\t";
y++;
}
x++;
As you can see from this code you don't actually need the... |
73,506,798 | 73,510,627 | BitBlt causes a glitch when called after EVENT_SYSTEM_FOREGROUND | I need to take a screenshot of the foreground window.
To do that, I use SetWinEventHook() (listening to EVENT_SYSTEM_FOREGROUND) and BitBlt(). It's working as expected, except for newly created windows which shows up not fully rendered (transparent parts):
Adding a 10~50ms delay between the EVENT_SYSTEM_FOREGROUND eve... | EVENT_SYSTEM_FOREGROUND might notify from deep inside the foreground change code in the window manager and the new foreground window might still be waiting to paint by the time you BitBlt.
Call RedrawWindow(.., RDW_UPDATENOW) or UpdateWindow first to make the window paint its invalid areas.
|
73,507,059 | 73,507,300 | Round long double to unsigned long long in c++ | Is there any built-in function in C++ to convert long double into unsigned long long?
As per this answer, it looks like double is not sufficient to represent some unsigned long long values. Correct me if long double is also not enough.
I also know that there's a function called, roundl that rounds a long double but... | TL;DR use std::llroundl, assuming the initial value is smaller than 2^64. If it is bigger, then it wouldn't fit anyway, so up to you to decide what to do with it.
IEEE 754 floating point numbers can represent any integer up to a certain point. If you convert an integer to such a number, and then back to the same integr... |
73,507,769 | 73,507,832 | if statement followed by return 0 | I have some code like:
#include <iostream>
#include <string>
int main() {
std::string question;
std::getline(std::cin, question);
if (question == "yes") {
std::cout << "Let's rock and roll!" << std::endl;
return 0; // This line
} if (question == "no") {
std::cout << "Too b... | Control flow is your issue here:
if(question == "yes"){
std::cout<<"Lets rock and roll!"<<std::endl;
return 0;
}if (question == "no"){
std::cout<<"Too bad then..."<<std::endl;
} else{
std::cout<<"What do you mean by that?"<<std::endl;
}
Let's format this a bit bet... |
73,507,922 | 73,508,084 | Do sets with transparant comparators need to form an equivalence class? | Say I have a set with a comparator like this:
struct prefix_comparator {
using is_transparent = void;
struct prefix {
std::string_view of;
};
bool operator()(std::string_view l, std::string_view r) const {
return l < r;
}
bool operator()(std::string_view l, prefix r) const {
... | From the draft standard.
[associative.reqmts.general]/24.2.7.1
Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering ([alg.sorting]) on elements of Key.
there is no "top level" requirement that non-Key type elements are strict weak ordered.
There are r... |
73,508,060 | 73,508,123 | std::pair with reference to unique pointer | Currently using C++20, GCC 11.1.0
I'm trying to create a class method that returns a std::pair of uint32_t and a reference to a unique pointer. The unique pointer comes from a vector of unique pointers stored as a variable in the class. However, it keeps saying:
error: could not convert ‘std::make_pair(_T1&&, _T2&&) [w... | std::make_pair() will automatically decay any references given to it to their value types.
The deduced types V1 and V2 are std::decay<T1>::type and std::decay<T2>::type (the usual type transformations applied to arguments of functions passed by value) unless application of std::decay results in std::reference_wrapper<... |
73,508,092 | 73,508,179 | C++, 3D arrays, find target and its occurrences. My problem is, my elements only displaying zeros but i want to display 0-9 random numbers | #include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int count_occurrences(int array[3][3][3], int size, int target)
{
int result = 0;
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
for (int k = 0; k < size; ++k) {
if (target == arr... | This doesn't work properly because you're not initializing the list with enough elements. You're passing in one element, rand() % 10, but nums is a 3D array where each dimension has length 3, so you need to initialize it with 3×3×3 = 27 elements.
Doing that with the inline initializer looks like this:
int nums[a][a][a]... |
73,508,295 | 73,654,766 | How to use docker to test multiple compiler versions | What is the idiomatic way to write a docker file for building against many different versions of the same compiler?
I have a project which tests against a wide-range of versions of different compilers like gcc and clang as part of a CI job. At some point, the agents for the CI tasks were updated/changed, resulting in ... | I would separate the parts of preparing the compiler and doing the calculation, so the source doesn't become part of the docker container.
Prepare Compiler
For preparing the compiler I would take the ARG approach but without copying the data into the container. In case you wanna fast retry while having enough resources... |
73,508,453 | 73,508,527 | Pass curried function result as parameter in C++ | Background
I'm trying to pass a std::function object as a parameter to evaluate the sum of its returned value over a range.
However, for some reason, the function depends on a functor, Bar, whose state depends on a parameter, a.
My approach was to create a lambda inside a curried function, foo and ask it to captur... | You are in UB world. Because bar is a local variable here which is captured by reference:
function<double(const double &)> foo(const double &a) {
auto bar = new Bar(a);
function<double (const double &)> result = [&](const double &b) {
cout << "address of bar: " << bar << endl;
return (*bar)(b);
... |
73,508,484 | 73,508,966 | Auto Rounding From Something While Dividing and Multiplying | #include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int(main){
std::vector<int> vObj;
float n = 0.59392;
int nCopy = n;
int temNum = 0;;
while (fmod(nCopy, 1) != 0) {
temNum = (nCopy * 10); cout << endl << nCopy << endl;
nCopy *= 10;
... | yeah , so you have 3 major problems in your code , first of all : it's int main() not int(main) . second : the variable named **nCopy ** is not supposed to be a integer data type , third one : you have to know what the actual representation of the float number , but first this is my solution for your problem , it's not... |
73,508,538 | 73,508,597 | c++ 2D Array in If statement logic failing tic-tac-toe | TLDR: I am making a tic tac toe game in c++. My win condition checking if statements are failing and I don't know why :(
The board state is maintained by a global 2D board array
int board[3][3]{ {0,0,0}, {0,0,0}, {0,0,0}};
As the game plays on, a 1 or 2 is inserted to represent an X or O. Periodically I check for a wi... | Sigh. After pulling my brain out for 4 hours. It appears that you can't logically compare 3 things in an if statement ie:
if (A == B == C)
You must instead do 2 comparisons...
if (A == B && B == C)
Maybe this will help someone someday...
|
73,508,627 | 73,508,729 | Recursively count number of triangles in Sierpinski triangle | I have this function that returns the number of triangles in a Sierpinski triangle based on the order.
I need to calculate it by summing the amounts from the recursive calls.
I'm not able to use static variables, modify the function parameters, or use global variables.
I tried using int count but I know that won't nece... | Your current implementation of drawSierpinskiTriangle will only return 0 or 1:
0 if order == 0,
or:
1 otherwise (because count is initialized to 0 and you use count++ once after all the recursive calls).
Instead of using count++, you should accumulate the result from the recursive calls:
count += drawSierpinskiTriangle... |
73,509,488 | 73,514,245 | Can I inspect coredump on Cloud Run? | I'm thinking about migrating some of my services from GCE VMs to Cloud Run. And I want to see how it would be like when I have to troubleshoot, especially in (hopefully rare) case that my C/C++ program segfaults.
When segfault occurs, I usually detach the VM from production and take a look at coredump, using sudo cored... |
Can I collect coredump files and get them from somewhere like Cloud
Storage?
No. Cloud Run runs container-hosted applications. If your application throws an exception, your container will be killed.
Capturing a core dump for an application in a container requires the host operating system to be configured to enable t... |
73,509,789 | 73,512,065 | Why can relaxed operation be reordered? Doesn't program order imply happens-before? | In the book C++ Concurrency in Action, when introducing relaxed ordering, the author says:
Relaxed operations on different variables can be freely reordered provided they obey any happens-before relationships they’re bound by
but in this page on cppreference, it gives an example about relaxed ordering
// Thread 1:
r1... | This is a common misunderstanding. It is true that load C happens before store D. That is not saying that C has to actually be executed, or become visible, before D.
At the end of the day, the only relevance of the happens-before relation, or any other element of the memory model, is what it tells you about what your... |
73,509,937 | 73,510,510 | Is there any theoretical difference in performance in an inline constexpr function that compares an `int` & `int` VS a `const char* & `const char*`? | Is there any theoretical difference in performance in an inline constexpr function that compares an int & int VS a const char* & const char*, when optimization is enabled?
Example 1 (int equals int)
struct some_struct {
int m_type;
...
inline constexpr
void somefunc() {
if (m_type == 0) {
... | Constexpr functions are computed at compile-time only when required, I mean in constant expression.
So in constant expression, there are no difference in performance at runtime (compilation time might differ).
In non-constant expression, functions are computed at runtime as any regular functions (With as-if rule, optim... |
73,510,278 | 73,510,331 | How to correctly set an utf8 window title using xcb? | EDIT: it was a typo, see answer below.
I'll leave this question up anyway, because it might help people in the future who are looking for an answer to the question stated in the title (it wasn't trivial to find it).
If I go to a website with UTF8 characters, then Chromium shows the correct title in its window (I'm usin... | Argh - mere seconds after I posted the question I see it...
It should be:
xcb_intern_atom_cookie_t utf8_string_cookie = xcb_intern_atom(m_connection, 0, 11, "UTF8_STRING");
I passed 12 as string length, so the type wasn't UTF8_STRING, but something with a literal 0 appended, while still displaying the same with xprop... |
73,510,549 | 73,510,586 | Does the memory allocated by new, is automatically deallocated when the thread ends? | Memory allocated for new, is deallocated automatically when thread joins main thread or I must deallocated them using delete()
Here is the example code,
#include <iostream>
#include <thread>
using namespace std;
class thread_obj {
public:
void operator()(int x)
{
int* a = new int;
*a = x;
... | Memory obtained by new is shared among all threads. When a thread exits nothing happens with it. It is not freed. Either the exiting thread or another thread must call delete explicitly to destruct the object that was created with new and to free the memory it allocated for that object. Otherwise the object continues t... |
73,510,735 | 73,512,088 | Sprite not showing sfml | I want to display my player in the window but my player sprite is not showing in the window. I am new to c++. I want to learn classes, inheritence, composition, etc in this way.I have 3 files Player.cpp, Game.cpp and main.cpp. I am using main.cpp to call Game.cpp using a fuction called Run().
Got nothing to try.
Player... | The problem was with image I dont know why. I used another image and it worked fine.
|
73,511,176 | 73,511,312 | Memoizing Vector not taking values in a recursive function's return statement | With this code I was trying to calculate unique ways to reach a certain sum by adding array elements with a dynamic programming approach, the program works correctly but takes more time than expected so I checked if it is storing calculated values in the my vector, but it not storing any values at all.
#include <iostre... | It does store the values, your checking code is not correct.
Try this version in your check
for (int y=0; y<N+1; y++){ // N+1 not N
|
73,511,713 | 73,540,060 | How to create different filters for the same files in different projects? | I have this file structure:
My Solution(dir)
+-- CMakeLists.txt
+-- MainProject(dir)
+-- File1.cpp
+-- File1.h
+-- File2.cpp
+-- File2.h
+-- Subdirectory(dir)
+-- File1.cpp
+-- File1.h
... | I got some help over on the CMake forum:
I put CMakeLists.txt in sub-folders and got this in the end:
CMakeLists.txt in the root directory:
cmake_minimum_required(VERSION 3.10)
project("CMake Subdirectories Filters Example")
set(main_project_name "MainProject")
set(main_project_path "${PROJECT_SOURCE_DIR}/${main_proj... |
73,511,892 | 73,512,256 | Why does the standard disallow a pseudo-destructor call with a name of scalar type? | The standard rules:
[expr.prim.id.unqual]/nt:unqualified-id:
unqualified-id: ...
~ type-name
~ decltype-specifier ...
[dcl.type.simple]/nt:type-name:
type-name:
class-name
enum-name
typedef-name
A name of scalar type isn't a type-name, so the standard disallows the use of it.
It disallows std::destroy_at from b... | In your implementation of destroy_at the identifier T used in p->~T(); is a type-name per [temp.param]/3. Therefore the call is allowed. Substitution is not relevant.
So the premise that this rule hinders straight-forward implementation of destroy_at is wrong. p->~T(); is just fine.
In fact the only reason pseudo-destr... |
73,512,024 | 73,512,106 | Why I am not getting the second string s2 on the display? | In this program I convert a String (user defined type) to a C-string and then I display it. I have derived a class Pstring from the String class that also check whether the string passed by the user does not exceed the size of the String object. If it then only size-1 characters will be copied in the C-string else the ... | You call the constructor of the parent class String(s); but that in itself does not save the content s in str.
Change it so something like this:
Pstring::Pstring(char s[]) { // 1-argument constructor
if (strlen(s) > SZ - 1) {
...
} else {
strcpy(str, s);
}
}
|
73,512,265 | 73,512,366 | Cmake error : set_target_properties Can not find target to add properties to: lib_opencv | I am tying use log for debugging in my cmake ndk project,but when i am trying to add the log-lib library it gives error on compilation time:
CMake Error at CMakeLists.txt:21 (set_target_properties):
set_target_properties Can not find target to add properties to: lib_opencv
If i remove the set_target_properties(lib... | A library cannot be both imported and non-imported and you cannot declare 2 targets with the same add_library command. You need to separate those:
# create native_opencv target built as part of this project
add_library(native_opencv SHARED
# Provides a relative path to your source file(s).
../ios/Classes/Aruco... |
73,512,602 | 73,512,852 | Using Vulkan memory allocator with Volk | I'm currently trying to use Vulkan memory allocator with the meta loader Volk
here is the link of the two: https://github.com/zeux/volk
https://gpuopen.com/vulkan-memory-allocator/
But I have trouble with creating the VmaAllocator, here is my code:
void VulkApp::Init(PipelineFlags t_Conf, entt::registry& t_reg)
{
v... | If you use a loader like Volk, you need to provide all memory related Vulkan function pointers used by VMA yourself.
This is done via the pVulkanFunctions member of the VmaAllocatorCreateInfo structure.
So when creating your VmaAllactor you set the function pointer in that to those fetched via Volk like this:
VmaVulkan... |
73,512,901 | 73,513,192 | Failed parameter pack deduction of template arguments in a template specialization | I'm trying to write a code attempts a deduction of two parameter packs in template and was wondering why the following code doesn't work
t.h (doesn't work)
#pragma once
#include <tuple>
namespace example
{
template<typename ... T>
struct Foo;
template<typename ... T1, typename ... T2>
struct Foo<std::tuple<T1...>, ... | Implicit deduction guides are generated based on the constructors of the primary template, not any of its specializations. Your primary template has no constructors, so no deduction guides exist.
For class template argument deduction, the function arguments to the constructor are compared against the deduction guides t... |
73,513,502 | 73,523,066 | In which case(s) user-defined conversions are not considered during reference initialization? | Consider a case where we've reached into bullet [dcl.init.ref]/(5.4.1) during reference binding:
(5.4.1) If T1 or T2 is a class type and T1 is not reference-related to
T2, user-defined conversions are considered using the rules for
copy-initialization of an object of type “cv1 T1” by user-defined
conversion ([dcl.init... | As far as I know, the bolded sentence is redundant. It may have been added out of an abundance of caution.
The predecessor of the quoted paragraph, in C++11, actually required a temporary of type "cv1 T1" to be copy-initialized from the initializer expression, whereupon the reference to type "cv1 T1" (that we are tryin... |
73,513,661 | 73,513,997 | How to detect by regular Win32 program, that the system just came out of sleep | I need to adjust something by a regular desktop program (not a service) when the system emerges from a sleep state. I expected that the program would get a WM_POWERBROADCAST message, but this message is never received.
According to How can I know when Windows is going into/out of sleep or Hibernate mode?, this message ... | You have to register before you will get WM_POWERBROADCAST messages.
Take a look at Registering for Power Events, you will see that you need to call RegisterPowerSettingNotification() in order to get WM_POWERBROADCAST.
|
73,514,111 | 73,514,144 | How do I properly overload the << operand to produce the desired results? | https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3294/
I'm following this Leetcode course on Arrays and am trying to follow along using C++ as they use Java, but I'm struggling to get past this part. I just want to read items from the pokedex array I made.
The initial error I got was:
No operato... | Your operator overload for << to print to an std::ostream an object of type Pokemon does nothing but return the os parameter. You need to add the logic for printing inside of here, which would look something like this:
friend std::ostream& operator<<(std::ostream& os, const Pokemon& obj)
{
os << obj.toString();
... |
73,514,418 | 73,515,570 | Why do MSVC and Clang produce different outputs for the same function template call? | After messing around with concepts I came across something in visual studio that I didn't understand, although I don't know if the issue here is anything to do with concepts specifically. I'm sure there's a reason for this behaviour, but it would be great if someone could explain. There are two parts to this question. ... | Clang is correct: the call to TPolicy::Create<type_a> requires the word template because TPolicy is a dependent type.
Specifically, according to the standard, when we have a fragment of the form T::m< where T is a dependent type other the current instantiation, the compiler must assume that < is the less-than operator,... |
73,514,558 | 73,515,032 | Performing class method directly on the output of a function that returns data in that class (C++) | I'm brand new to all of this, and I'm sure I'm not quite phrasing things properly - sorry about any dumb questions and mistakes, and thanks for bearing with me! :)
That aside, here's my situation: I've created a class, a member function for that class, and another (non-member) function that returns values in that class... | Your FindMatchingObject() function returns a Class object by value, thus returning a copy of the object. So, you are calling change() on a copy of second, not on second itself. That is why second doesn’t change, even though second was returned.
To fix that, your function would have to return a Class object by referenc... |
73,514,564 | 73,514,656 | In C++, can the member functions be ONLY accessed by the objects of same class, even if the access specifier for that function is public? | This is a sample code explaining the question.
Why does the "display()" not call the member function rather it calls the non member function ?
#include<iostream>
using namespace std;
class foo
{
private:
int num;
public:
// Constructor
foo() : num(0... | The keyword "public" means that if an object of the class is instantiated, then any function/field defined with that keyword in the class is callable/accessible through the object. In contrast, "private" means that even if an object of the class is instantiated, the function/field is not accessible outside the class. F... |
73,514,864 | 73,514,918 | How to access and modify value of a struct which is a public member of a class (c++) | i would like to know how can i access and modify the struct's attributes in the constructor of my class. Thanks
template <class K, class V>
class AVLTree
{
public:
struct Node
{
Node *parent;
Node *right;
Node *left;
... | structs, by themselves, are not entities of any kind, that have any kind of an attribute, or anything.
A struct, by itself, is just a definition for an object that claims to be that struct.
An object, of the struct's type, will have the attributes and methods that are a part of the struct's definition.
So, for example,... |
73,515,132 | 73,515,190 | Is there any generic conversion from std::string to numeric type? | There are many ways to convert strings to numbers in C++: stoi, stod, stof, etc. Just like how std::invoke is a nice way to call any callable, I am looking for a method that converts string value to a generic numeric value.
For instance, instead of something like this:
int x = std::stoi("5");
long y = std::stol("555555... | This can be considered as a generic conversion:
#include<sstream>
int main() {
int x;
std::stringstream("55") >> x;
long y;
std::stringstream("5555555555") >> y;
}
A function can return only a single type, thus long y = num_convert("5555555555") with a regular function is impossible.
One more hack, help the ... |
73,515,441 | 73,522,772 | Create std::array<T, N> from constructor argument list | The desired behaviour is that of emplace called N times.
Very similar to this question Initializing a std::array with a constant value. Except instead of calling the copy constructor given some T, you are given some argument list for which you call the corresponding constructor of T.
Pseudo code:
template <typename ...... | Jarod commented that this should be implemented with a generator taking the index, and with c++20 templated lambdas we can do away with the helper function
template <std::size_t N, typename Generator>
auto make_array(Generator gen)
{
return [&]<std::size_t... I>(std::index_sequence<I...>) -> std::array<std::decay_t... |
73,515,538 | 73,515,550 | What does this C++ syntax( template<> struct __nv_tex_rmnf_ret<char> {typedef float type;}; ) statement mean? | In the CUDA header file, /usr/local/cuda/targets/x86_64/linux/include/texture_fetch_function.h, there is the following statements:
template<typename T> struct __nv_tex_rmnf_ret{};
template<> struct __nv_tex_rmnf_ret<char> {typedef float type;};
I understand the first statement is the definition of struct template. But... | template<> introduces an explicit specialization of a previously declared (primary) template (here the first line). It has otherwise the same syntax as the primary template uses, except that the name in the declarator (here __nv_tex_rmnf_ret) is replaced by a template-id (here __nv_tex_rmnf_ret<char>) which should be v... |
73,515,684 | 73,517,531 | How to return a value from a function of type `LPCTSTR`? | What is the 'proper' way to return wintitle from the function?
The way i did the compiler is pointing this warning: warning C4172: returning address of local variable or temporary: wintitle
LPCTSTR WinGetTitle(HWND hWnd)
{
TCHAR wintitle[250];
GetWindowText(hWnd, wintitle, GetWindowTextLength(hWnd) + 1);
re... | The compiler diagnostic is spot on: wintitle is an object with automatic storage duration. When the function returns, it's memory is automatically freed, leaving the returned pointer dangling.
If you do wish (you probably don't) to return a pointer, you'll have to have it point into memory that outlives the function ca... |
73,515,688 | 73,515,750 | C++ sequential consistency and happens before relation | #include <atomic>
#include <thread>
#include <assert.h>
std::atomic<bool> x,y;
std::atomic<int> z;
void write_x()
{
x.store(true,std::memory_order_seq_cst); // 1
}
void write_y()
{
y.store(true,std::memory_order_seq_cst); // 2
}
void read_x_then_y()
{
... |
is it possible that operation 2 happens before 1 but operation 4 doesn't see that value change?
It is important to be careful about the terminology here. What you refer to here as "happens before" is not the happens-before relation used in the description of the memory model. What you mean here is occurs before in th... |
73,515,932 | 73,516,032 | Transform ith element of std::tuple | Is there any simple way to implement the following pseudo code? Or do you go down a template meta programming rabbit hole?
template <size_t index, typename Func, typename... Args>
auto transform(std::tuple<Args...> tup, Func fn)
{
return std::tuple{ tup[0], ..., tup[index - 1], fn(tup[index]), ... };
}
| Expand the tuple using the template lambda and choose whether to apply the function based on the index of the current element
#include <tuple>
template<size_t index, size_t I, typename Func, typename Tuple>
auto transform_helper(Tuple& tup, Func& fn) {
if constexpr (I < index)
return std::get<I>(tup);
else
... |
73,516,056 | 73,516,290 | Testing static replacement for std::function for non stateless lambda support | Looking at some static-allocation replacements for std::function, ones that don't involve any std libraries.
Soon to realize that some only support stateless lambdas (any reason for that? ) .
E.g., vl seems to work fine with [&], while etl does not - I get garbage values.
My test code:
template<typename Func, typename... | ETL documents that etl::delegate doesn't own the lambda at all, see https://www.etlcpp.com/delegate.html. It only stores a pointer to the passed object. It doesn't store the lambda at all. See also the code at https://github.com/ETLCPP/etl/blob/master/include/etl/private/delegate_cpp11.h#L117.
Contrary to what the link... |
73,516,544 | 73,516,579 | MergSort won't sort the array | I wrote this code for sorting a array. It wouldn't sort any array and won't give an error either and I can't seem to find to root cause of this issue.
This code was written as a part of learning curve and Code is exactly the same from the YT video , I am learning from.
I have google another code snippet and it works pr... | I think you'll find that this loop
while(i<n1 && j<n2)
{
if(array1[i]<array2[j])
{
arr[k]=array1[i];
i++;k++;
}
else
{
arr[k]=array2[j];
j++;k++;
}
while(i<n1)
{
arr[k]=array1[i];
i++;k++;
}
while(j<n2)
{
arr[k]=array2... |
73,517,938 | 73,518,374 | CMake makes strange error, even after creating all new CMakeLists.txt | I was experimenting with CMake, until i stumped on this error:
CMake Error at CMakeLists.txt:34:
Parse error. Expected "(", got newline with text "
".
-- Configuring incomplete, errors occurred!
I though, ok fine, I'll fix the code at line 34, as suggested:
cmake_minimum_required(VERSION 3.10)
# set the proje... | OK, I fix it! How? For some reason, all I did was this:
cmake . --fresh
Well, it won't work since my CMake wasn't v3.24 (mine is v3.23) and it did complain saying that was not a known argument. However I retried cmake ., and suddenly it can compile the CMakeLists.txt just fine. I guess this is a bit of a bug on CMake, ... |
73,518,333 | 73,530,007 | Access Violation Exception when trying to access bstrVal field of variant object | I'm trying to get hardware information using WMI and the (Win32_Processor) class.
When I try to access the "Name" property of this class through a IWbemClassObject I get the Name of the cpu and the program executes without error.
However when I try to access any other property("NumberOfCores" for example) I get an "Acc... | I'm accessing the wrong property of the VARIANT object.
Instead of "bstrVal", I should access "uintVal" because the property "NumberOfCores" is an unsigned int not a BSTR object.
|
73,518,737 | 73,531,829 | How do I generate machine code with LLVM's new PassManager API? | I'm working on a project and would prefer to use LLVM's new API with specializations of LLVM::PassManager. I tried looking at llc's code, but it uses the legacy PassManager. Is there a way to do it with the new API?
| No. This is currently WIP. Patches are welcome :)
|
73,518,773 | 73,518,931 | how to remove duplicate elements from the linked list | I have to make a program to count the number of occurrences of a given key in a singly linked
list and then delete all the occurrences. For example, if given linked list is 1->2->1->2->1->3->1 and given key is 1, then output should be 4. After deletion of all the
occurrences of 1, the linke... | so , you have a little tiny mistakes in your code , I edited it out , all of the edits are in the function named deleterepeated and here is my solution , not the best but it will work for your case :
EDIT: I removed unnecessary things in the code to be only one big loop , also I found a bug in my previous code and ed... |
73,518,933 | 73,519,248 | Why surround template parameters with parentheses when `require clause` is surrounded by parentheses? | Why surround template parameters with parentheses when require clause is surrounded by parentheses ?
template(typename This, typename Receiver)
(requires same_as<remove_cvref_t<This>, type> AND
receiver<Receiver> AND
constructible_from<std::tuple<Values...>, member_t<This, std::tuple<Values...>>>)
frien... |
Why surround template parameters with parentheses when require clause
is surrounded by parentheses ?
The template(typename This, typename Receiver) part you see is actually a macro, which is defined as:
#if UNIFEX_CXX_CONCEPTS
#define template(...) \
template <__VA_ARGS__> UNIFEX_PP_EXPAND \
/**/
#else
#d... |
73,519,851 | 73,519,975 | How does one allow the user to input feet and inches with an apostrophe inbetween? | For example if we have something like this in the code
int height;
cin >> height;
user inputs
5'9
How would I go about making that work?
It would be easy enough to have
cin >> feet;
cin >> inches;
cout << feet << "'" << inches << "\n\n";
and put it together but it's just not that neat or practical of a program for the ... | This is one way
int feet, inches;
char apos;
cin >> feet >> apos >> inches;
The apos variable is there to read the '. This code has no error checking, you can add that if you like (including checking that apos really is an apostrophe).
if ((cin >> feet >> apos >> inches) && apos == '\'')
{
// do something with f... |
73,519,910 | 73,519,958 | Why cant I insert a struct value in an unordered_map C++ | I have created a very simple example to show the problem:
#include <unordered_map>
int main() {
struct Example {
int num;
float decimal;
};
std::unordered_map<int, Example> map;
map.insert(1, { 2, 3.4 }); // Error none of the overloads match!
}
I should be able to insert into the map ... | The reason for the error message is, that none of the overloads of std::unordered_map::insert takes a key and a value parameter.
You should do
map.insert({1, { 2, 3.4 }});
instead of
map.insert(1, { 2, 3.4 });
You may refer to the 6th overload of std::unordered_map::insert at
https://en.cppreference.com/w/cpp/contain... |
73,519,955 | 73,520,667 | controling another program in c# (filedialogs) | so i have a program (witch is written in c++).
what this program do is that it get the location of 2 file using filedialogs, edit them then give you an result file.
i want to write c# program to control that.
what i mean by control is that i want to open the app, then give it 2 locations, then get the output file and s... | If you read the c++ code, in the _tmain function it specifies in a comment that the dialogs only appear if the program is run without arguments.
You can run an application with c# and passing arguments
(From MSDN)
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child proce... |
73,520,238 | 73,520,356 | Linking C++ library in visual studio, error C2079 | I'm using visual studio for the first time in a project to use the GGPO library (https://github.com/pond3r/ggpo). I built it with visual studio using the install and got a .dll, a .lib and a .h. Following tutorials I saw, I included the .h which is recognised by visual studio and I added the .lib to the linker.
My proj... | As 273K said, GGPOSession* ggpo; makes it possible to compile without error. I still find it strange given it doesn't follow the Programming Guide given with GGPO but I guess my question has been answered, thank you.
|
73,520,691 | 73,520,827 | How do I loop through a unordered_map in C++ without auto? | I am trying to loop through an unordered_map, to find if any of its VALUES is greater than 2. But this syntax is wrong
unordered_map<int, int> mp;
for (int i = 0; i < N; i++)
{
mp[arr[i]]++;
}
for (int i = 0; i < mp.size(); i++ ) {
cout << mp[i].second << " " << endl; //mp[i].second is wrong syntax
... | It seems that you assumed(incorrectly) that mp[i] is std::pair<int, int> when in fact mp[i] gives you the mapped value which is of type int in your example. This can be seen from std::map::operator[]:
T& operator[]( Key&& key ); (2)
Returns a reference to the value that is mapped to a key equivalent to key, performin... |
73,520,696 | 73,522,019 | Reading a single vector from HDF5 in C++ | I have data stored in hdf5 format, the shape of the data is: (10000, 100), 10000 vectors of 100 floats.
I want to extract the data from the file into c++ vectors, so for this data I would have 10000 vectors where each element is a vector of 100 floats.
I am trying to create a memspace with 1 dimension of 100 elements, ... | The dataset dataspace is 2D but you manipulate it with a 1D datacount and offset. Therefore the selectHyperslap method reads garbage beyond the end of the input arrays. Try it like this:
hsize_t dataCount[2] = {1, dims[1]};
hsize_t dataOffset[2] = {0, 0};
const hsize_t memCount[1] = {dims[1]};
const hsi... |
73,521,692 | 73,522,196 | Can you store datatypes in containers in cpp? | I want to use some kind of container in cpp to store custom classes. Not existing objects of the classes, but the class as datatype.
sth like:
vector<????>{int,double,string,bool...}
or in my case:
vector<????>{class1,class2,class3 ...}
Eventually I want to iterate through the container to create an object of each cl... | You may or may not want to do something like this:
class base { ... };
class class1 : public base { ... };
class class2 : public base { ... };
class class3 : public base { ... };
using pbase = std::unique_ptr<base>;
std::vector<std::function<pbase(void)>> objectCreation =
{ []()->pbase { return std::make_unique... |
73,522,128 | 73,523,102 | how to break out of a loop listening on stdin? | I have a while loop in a separate thread listening on stdin, waiting for text coming from another process. When my program is exiting, I would like to exit from this while loop and join the thread.
std::string line;
while (std::getline(std::cin, line))
{
std::stringstream linestream(line);
}
| This is one of the rare cases where detaching the thread could be appropriate. When the program exits the thread will be terminated.
std::thread thr(whatever);
thr.detach();
|
73,522,503 | 73,522,623 | Problem sending text to stdin of running process | I have a c++ program running with process number PROCNO, and I would like to send text to stdin of this program. However, when I run :
echo test > /proc/PROCNO/fd/0
I see test printed in the console. So, it seems that stdin is being redirected to stdout. How can I prevent this ? The reason is that I would like to rea... |
How can I prevent this ?
You can't, because this is how terminal devices work on Linux on a fundamental level. When launched from a terminal device, the Linux process's standard input, output, and error, are really the same device:
$ ls -al /proc/$$/fd/[012]
lrwx------. 1 mrsam mrsam 64 Aug 28 18:01 /proc/5777/fd/0 -... |
73,522,688 | 73,522,727 | How do I reference a vector from a map's value? | #include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
vector<string> examplevector {"one", "two", "three"};
map<string, vector<string>> examplemap {{"vector1", examplevector}};
examplemap["vector1"][0] = "eight";
cout << examplemap["vector1"][0] << endl; // prints "eight"
c... | No, C++ does not work this way, this is not how objects work in C++. This is how objects work in Java and C#, but C++ is not Java or C#. Objects that are stored in some container, a vector, a map, or any other container, are distinct objects of their own and have nothing to do with any other object.
map<string, vector<... |
73,523,486 | 73,524,033 | How to determine if a parameter is a constexpr in compile-time | I have a compile-time string class that helps programs compute various relevant things at compile time, such as hash results and a quick lookup table for find, which is constructed like this:
"hello"_constexpr_str;
Also, my string class supports construction from this type, which allows for fast hash and fast find and... | If I understood your question now after the discussion in the comments correctly, you have a operator""_constexpr_str which is marked consteval and returns a string-view-like type constexpr_str_t with some additional information attached based on the contents of the string.
You then have a function taking an (ordinary)... |
73,523,718 | 73,525,509 | Having problem building project in eclipse Embded system | I am building driver for atmega32, and when I try to build the project I got the error in the console. I am using the latest version of eclipse.
[console output]
04:43:37 **** Incremental Build of configuration Debug for project
Project00 (Dio_Driver) ****
make all
Building file: ../DIO.c
Invoking: AVR Compiler
avr-g... | It seems like a CDT bug, if you didn't do a custom configuration.
The error syntax error near unexpected token ... means the shell(/usr/bin/sh) can't parse the command line.
As a remedy, change your project name to one without any spaces or parentheses, somewhat friendly to your system.
|
73,523,772 | 73,870,238 | VSCode C++ IntelliSense/autocomplete is not working for OpenCV C++ | OpenCV is installed from the source on my Linux (Ubuntu 18.04.6 LTS) machine. The path is a bit different i.e. /usr/local/<blah_blah> and the directory tree looks somewhat like this:
milan@my_machine:/usr/local/<blah_blah>$ tree -L 4
.
├── bin
│ ├── opencv_annotation
│ └── ...
├── include
│ └── opencv4
│ └─... | It turned out that in my settings.json file, the includePaths were set like this:
"C_Cpp.default.includePath": [
"/usr/local/<blah_blah>/include/opencv4/opencv2/**",
"/usr/local/<blah_blah>/include/opencv4/opencv2/core.hpp",
"/usr/local/<blah_blah>/include/opencv4/opencv2/core",
.
... |
73,524,406 | 73,524,434 | Can I use __LINE__ or __FILE__ in inline function in C++? | I faced a problem while implementing the logger.
First, I used to __LINE__ and __FILE__ with standard C Macro function like below
// global.h
..
namespace MyLogger {
class Logger
{
..
void _write(int _level, const char* _file, int _line, const char* _fmt, ...);
};
static Logger logger;
}; // namespace MyLo... | No, inline functions/methods won't work the same as macro in this context.
Macros are simply text replacements, that's why the __LINE__ and __FILE__ will give accurate results. Thus macros are your only choice; See if you can name them better to avoid conflicts.
However the inline functions are systematically compiled ... |
73,524,593 | 73,524,650 | Is it safe to pass stack variables by reference to multithreaded code? | As an example in pseudocode:
MultiThreadedWorker worker;
Foo()
{
const Vector position = CreatePosition();
worker.StartWorker(Position);
}
MultiThreadedWorker::StartWorker(const Vector& myPosition)
{
... Do a bunch of async work that keeps referencing myPosition ...
}
This seems to be working for no... | std::async copies const references
So yes, it is safe. For a discussion of why it does, see Why does std::async copy its const & arguments?
|
73,525,142 | 73,525,430 | const reference to temporary variable does not work for std::function whose type does not match its declaration | class Context {
public:
Context(){
field2values_["age"] = std::vector<int>{1,2,3};
}
const std::vector<int>& field2values(const std::string& field) const {
auto it = field2values_.find(field);
if (it == field2values_.end()) {
return default_ints_;
}
retur... | It's the same reason the following produces a dangling reference:
int f() {
return 42;
}
const int& invoke_f() {
return f();
}
const auto& e = invoke_f(); // dangling!
Basically, when a temporary appears in a return statement, its lifetime is not extended. It gets destroyed at the end of the return statement... |
73,525,567 | 73,525,861 | Issues Installing Intel's Decimal Floating-Point Math Library on Mac OS Monterey | I'm trying to install Intel's Decimal Floating-Point Math Library both on my Apple M1 Mac mini and an older MacBook Pro with an intel CPU both running Mac OS Monterey. In trying to run the recommended RUNOSX bash script from the LIBRARY subfolder I begin encountering several errors. The first of which are
src/bid64_pow... | I don't have MAC os.
However I tried sample code using cygwin(gcc.exe) at windows.
Here goes sample code using raise and your macro.
#include <stdio.h>
#include <signal.h> // TO USE raise
# define DPML_SIGNAL(p) raise(SIGFPE)
void mysig( int sig)
{
switch( sig )
{
ca... |
73,525,630 | 73,525,641 | Error C2259 cannot instantiate abstract class - how to use an interface? | Consider the fallowing code:
class BaseParameter
{
protected:
int value;
public:
BaseParameter(int v) : value(v) { }
virtual void print() = 0;
};
class MyParam : public BaseParameter
{
public:
MyParam(int v): BaseParameter(v) { }
void print() override
{
std::cout << "Param value: " <... | Because BaseParameter has abstract method print(). You need to declare a vector of raw or smart pointers for it, not class itself. For example, following code works:
int main()
{
std::vector<std::unique_ptr<BaseParameter>> paramsVector;
paramsVector.push_back(std::make_unique<MyParam>(1));
paramsVector.pus... |
73,525,947 | 73,526,115 | c++, OpenFileDialog.Filter, file name | I need to use the OpenFileName() dialog box, and want to filter CSV files starting with some specific alphabet, eg, "m"-> "myspecific.csv"
How can I do it?
OPENFILENAME ofn;
ofn.lpstrFile[0] = '\0';
ofn.lpstrFilter = L"CSV Files (*.csv)\0*.csv\0All Files (*.*)\0*.*\0";// How to add "m" in filter and what is role of \0 ... | You must put the letter before the star.
ofn.lpstrFilter = L"CSV Files (*.csv)\0m*.csv\0All Files (*.*)\0*.*\0";
|
73,526,838 | 73,527,130 | For a function that takes a const struct, does the compiler not optimize the function body? | I have the following piece of code:
#include <stdio.h>
typedef struct {
bool some_var;
} model_t;
const model_t model = {
true
};
void bla(const model_t *m) {
if (m->some_var) {
printf("Some var is true!\n");
}
else {
printf("Some var is false!\n");
}
}
int main() {
bla(&... | The compiler does eliminate the else path in the inlined function in main. You're confusing the global function that is not called anyway and will be discarded by the linker eventually.
If you use the -fwhole-program flag to let the compiler know that no other file is going to be linked, that unused segment is discarde... |
73,526,963 | 73,527,029 | c++: do we need to explicitly specify type info for template function, when using NULL/nullptr? | I've got this template function:
template<typename T>
void f(const T* t1, const T* t2) {}
Then in main():
int i = 1;
f(&i, NULL);
It doesn't compile, saying candidate template ignored: could not match 'const T *' against 'int'
If change it into:
int i = 1;
f(&i, nullptr); // same error!
I know I can ... | The compiler uses both parameter to deduce T, and because neither nullptr nor NULL are of type int* there is a conflict between the types deduced from &i and from nullptr / NULL.
Note that nullptr is of type nullptr_t. It can be converted to any other pointer type, but nullptr_t is a distinct type.
Since C++20 you can ... |
73,527,070 | 74,108,574 | Cross compiling code using Paho MQTT C & C++ libraries causing issues when publishing with a nonzero QoS | I have tried cross-compiling some small C++ code for a Raspberry Pi Model 3b using my Windows machine via Ubuntu-20.04 on WSL2. It uses the Paho MQTT C and C++ libraries to subscribe to and sometimes publish some messages. I'm pretty sure that most of it works since MQTT subscriptions work, as well as publishing messag... | Just fixed this issue a few days ago. Inspected the predefined targets of the RPi's gcc and as it turns out, it's slightly different: march is armv6+fp instead of armv8
I also edited my CMakeLists.txt to perform find_package on both the eclipse-paho-mqtt-c and PahoMqttCpp packages, and fixed the target_link_libraries l... |
73,528,161 | 73,528,527 | Not able to compile some shared code using boost::asio sockets in both boost v1.69 and v1.71 | I have to maintain two different legacy projects with some shared source code, one of them is tied to boost v1.69 and the other one is tied to boost v1.71.
The problem here is that compiler is working with v1.71 and failing with v1.69 when using some boost::asio sockets class.
The other restriction is to use c++17 or e... |
pre-1.70.0 Asio doesn't support executors in IO objects yet:
Changelog
Added custom I/O executor support to I/O objects.
All I/O objects now have an additional Executor template parameter. This template parameter defaults to the asio::executor type
(the polymorphic executor wrapper) but can be used to specify a
user... |
73,528,203 | 73,528,487 | Why is template template function overload chosen over the one with the concept? | The following code fails in static_assert:
#include <iostream>
#include <concepts>
#include <vector>
template <typename T>
concept container_type = requires(T& t) {
typename T::value_type;
typename T::reference;
typename T::iterator;
{ t.begin() } -> std::same_as<typename T::iterator>;
{ t.end() } ... | Constraints are considered for the purpose of choosing between two viable overloads only if there is no other tie breaker between the overloads, considered as unconstrained. In particular that means that if one is more specialized by the old partial ordering rules for function templates, ignoring constraints, then that... |
73,529,175 | 73,531,438 | When is the vtable created/populated? | I had a hard time figuring out why my code didn't work. I tracked the problem down to the vtable generation/population.
Here is a simplified version of my code:
#include <iostream>
#include <functional>
#include <thread>
using namespace std;
typedef std::function<void (void)> MyCallback;
MyCallback clb = NULL;
void... | Data races aside, when a derived class object is constructed in C++, it starts as a Base object then transitions to a Child object. (If you have more than one level of inheritance, the object transitions more than once)
If you call a virtual function from the base class constructor, you will see that the base class imp... |
73,530,170 | 73,530,249 | How to determine if C/C++ function or macro parameter is a constant string? | I want to define a macro or function with one input parameter x, is there a way to detect if the input parameter is a constant string or a variable? For example SOME_MACRO(x):
#define SOME_MACRO(x) \
// if x is a constant string \
printf("x is a constant string"); \
// else \
printf("x is a variable");
... | Are you asking for a macro because you don't know any C++ feature that can do it and are searching for a solution outside of C++? In that case, you can do it in C++:
#include <iostream>
void foo(const std::string& s){
std::cout << "is constant\n";
}
void foo(std::string& s){
std::cout << "is not constant\n";
}... |
73,530,307 | 73,531,372 | Return underlying value of boost::variant with boost::apply_visitor | Is it possible to code the write the boost:static_visitor so that it could return the underlying value of a boost::variant in a type-safe way?
My current efforts to do that look as follows.
using EventData = boost::variant<boost::blank, int, std::string, boost::system::error_code>;
struct EventDataVisitor : public boo... | You can't. If that were possible you wouldn't need variant.
Another way of putting it: you can but it requires you to return (another) variant, e.g.:
struct EventDataVisitor : public boost::static_visitor<boost::variant<boost::blank, int, SstErrors, boost::system::error_code> >
{
int operator()(int number) const { re... |
73,530,520 | 73,530,999 | cin is being ignored when another cin was previously used | Have 2 functions - fill() and Sum(). When Sum() is called after fill(), I get (!cin).
I found that when I replace while (cin>>u){} with cin>>u, there is no problem, but I need to multiply the input.
void fill (vector <int>& x){
int u;
while (cin>>u){
x.push_back(u);
}
#include <stdexcept>
#incl... | When this loop finishes
while (cin>>u){
x.push_back(u);
}
it is because cin>>u has returned false. When this happens (however it happens, unfortunately you didn't say) cin will be in an error state and no further input will happen until you clear that error state. This explains what you have observed. Additiona... |
73,530,688 | 73,531,874 | Can I set a solution-wide macro from VS a project property sheet? | Short Version:
I need to find a way allow a new VS solution to "override" a build macro used by existing C++ projects, but only for that solution, without affecting the value of that macro in older solutions with those projects. I can change the existing projects however I need. I can write any new projects (for the... | While property sheets macros are not conditional, property sheets themselves could be included conditionally. So you can create a solution-level property sheet with custom output directory and then modify all your projects to include this property sheet if it exists:
<ImportGroup Label="PropertySheets">
<Import
... |
73,531,901 | 73,532,503 | Running a c++ executable using qt5 | I have created a Qt5 application with Visual Studio (2019). When I compile and launch the application, everything goes well but if I try to launch it by hand, in other words by double clicking on the .exe file and not by clicking on 'Local Windows Debugger', I get errors like:
error
For the translation: "Unable to exec... | There are two possible solutions:
First solution
Use windeployqt to copy all the required dlls. But I don't like this solution.
Second solution
Use Cmake correctly to link the dlls you can do that by adding these lines to your CMakeLists.txt file:
find_package(Qt5 COMPONENTS Widgets REQUIRED) # Add all used qt packages... |
73,532,077 | 73,532,488 | Compilation error C++ undefined reference | I'm a beginner and I'm currently feeling pretty lost about a compilation error that I'm getting since yesterday, so I was hoping someone could help me. I'm writing the following program:
#include <iostream>
#include <algorithm>
void heapify(int);
void print(int);
const int MAX = 10;
int main () {
int arr[MAX] = {... | Look at the two declaration of heapify.
The one before main:
void heapify(int);
The one after main (which is also a definition):
void heapify(int arr[]) { ...
It might not be totally obvious, but these two declarations declare two different functions, both named heapify but with different parameter types. One accepts... |
73,532,273 | 73,532,568 | %X format specifier prints value only up to 4 bytes? | Hex value of 6378624653 is : 0x17C32168D
But this code prints : 0x7C32168D
#include<iostream>
int main()
{
int x = 6378624653;
printf("0x%x", x);
}
can anyone explain why this happens ? and what should I do to get the right output?
| The obtained result means that an object of the type int can not store such a big value as 6378624653.
Try the following test program.
#include <iostream>
#include <limits>
int main()
{
std::cout << std::numeric_limits<int>::max() << '\n';
std::cout << 6378624653 << '\n';
std::cout << std::numeric_limits<... |
73,532,410 | 73,604,257 | Slicing Eigen tensor: Error accessing matrices from tensors | I am new to tensor in Eigen and just trying to run simple examples here. This is the code I have it's to access the first matrix in a tensor. Let's say I have a tensor with size ((nz+1),ny,nx), where each matrix in this tensor should have the shape or size of (nz+1)-by-ny. The thing is I can only extract a matrix that ... | I was able to fix:
std::array<long,3> offset = {0,0,0}; //Starting point
std::array<long,3> extent = {(nz+1),nx,1}; //Finish point:(row,column,matrix)
std::array<long,2> shape = {(nz+1),(nx)};
std::cout << epsilon.slice(offset, extent).reshape(shape) << std::endl;
|
73,533,021 | 73,533,123 | C++ function doesn't return anything more than 15 characters | I have a C++ function that is supposed to repeat a string a certain amount of times. What I've seen is that when the resulting string is more than 15 characters long, the function does not return anything, but it works as expected when the string is less than 16 characters long.
Here is the function:
const char* repeat... | You are invoking UB (Undefined Behavior) by returning a pointer into a string (repeat) that is locally declared and therefore de-allocated when your function returns. I'd suggest that you have your function actually return the string object itself instead of const char*.
|
73,533,363 | 73,533,395 | How to list all registry keys and their subkeys names using Win API (C++)? | I'm aware of the functions like RegOpenKey, RegGetValue and etc. But I can't figure out how to get all keys and their subkeys names. How can I do such thing?
| You are looking for RegEnumKeyEx and to get the values, RegEnumValue.
|
73,533,372 | 73,533,391 | Visual Studio 2019 appears to ignore its language level setting for C++ | I have a C++ project in Visual Studio 2019. Preferences are set to support C++14 (at least that is my understanding).Here's my preference panel:But here's a pic of some of my source with the cursor hovering over the word "__cplusplus":
And yes, I have tried adding the "L" so that my compiler directive refers to "201400... | You need to enable /Zc:__cplusplus.
|
73,533,422 | 73,533,737 | How to define namespace name same as return type of function in that namespace? | I have something like this in my header:
namespace Utils
{
namespace Klass
{
Klass fromObject(Object object)
{
if (something) {
return a;
} else if (something2) {
Klass b = Klass::initialise();
return b;
// ...
... | for return class Klass();
you can simply write
return {};
as long as Klass doesn't overload for initializer_list (or the semantic doesn't change)
or you can (fully) qualify the name
return ::whatever::ns::Klass();
generally, you can introduce alias for internal use
namespace Utils
{
namespace Klass
{
... |
73,533,521 | 73,533,695 | Partially specialized member function on template classes | I have some template classes and I need to implement a specialized member function for the main class. For example, if we have a template class Parent and other two template classes Boy and Girl. I want to implement a member function with specialization for Boy and for Girl. The member function for Girl has one more ar... | If you wanted to fully specialize the function then you could explicitly instantiate the function to create a specialization, but that won't work in this case since you can't partially specialize function templates.
In this case, your best bet is probably to pull the non-specialized functionality out into a base class.... |
73,533,797 | 73,533,855 | cppcheck: one definition rule is violated when overriding | In the following code (which is a minimal example based on a much more complex code), a base class defines a struct local to the class. A derived class overrides this definition, but uses also the definition in the base class.
#include <iostream>
struct base {
struct update;
void apply(int& x);
};
struct base::u... | It is also a false positive. There is nothing wrong with declaring a nested class of the same name in the derived class. The two nested classes will be separate entities and each can have one definition per one-definition-rule.
|
73,533,925 | 73,534,401 | CMake link libraries no header found | Here is my directory tree
I implemented accident component which have to be a standalone library. Here is CMakeLists.txt for it
set (ACCIDENT accident)
file (GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
file (GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.hpp")
add_library (${ACCIDENT} STATIC $... | As we figured out in the comment section, the test executable was forgotten to be linked to the relevant static library.
|
73,534,181 | 73,534,555 | Fast floating point model broken on next-generation intel compiler | Description
I'm trying to switch over from using the classic intel compiler from the Intel OneAPI toolkit to the next-generation DPC/C++ compiler, but the default behaviour for handling floating point operations appears broken or different, in that comparison with infinity always evaluates to false in fast floating poi... | If you add -fp-speculation=safe to -fp-model=fast, you will still get the warning that you shouldn't use -fp-model=fast if you want to check for infinity, but the condition will evaluate correctly: godbolt.
In the Intel Porting Guide for ICC Users to DPCPP or ICX it is stated that:
FP Strictness: Nothing stricter than... |
73,534,332 | 73,535,204 | How do I set the parameter of a parents class's constructor in a child class? | In calling Parent's constructor from Child's constructor, how do I first instantiate a AnotherClass instance based on myString below, then pass in that AnotherClass instance to Parent's constructor? If that's not possible, what is a common pattern to achieve this in C++ ?
class Parent {
public Parent(AnotherClass my... | Easy solution: just do nothing. Compiler does it for you (as written in comments), as long as it's not an explicit ctor for AnotherClass:
class Child : public Parent
{
public Child(std::string myString)
: Parent(myString) {}
};
You can even consider simply using the ctor of Parent (by simply writing using Parent::... |
73,534,414 | 73,560,452 | How to read the headers of a .txt files and put them as headers of a QTableView | I have a small problem trying to propoerly parse a .txt files and show its content on a QTableView. Specifically how to extract the headers of the file and show them into a QTableView.
The .txt file is composed of a first row which carries the headers, and all the other rows, which are data.
I can successfully upload t... | Assuming you have your data in cvs file with ; separator instead of .txt The code will be like this:
namespace constants
{
const QStringList HEADERS = {
"tax_id", "Org_name", "GeneID", "CurrentID", "Status",
"Symbol", "Aliases", "description", "other_designations",
"map_location", "chromosome", "genomic_nuc... |
73,534,531 | 73,574,829 | How can I synchronize a child kernel inside a parent kernel safely without affecting the performance? | I have a parent kernel than calls a child kernel as shown below. How can I make sure that the child kernel completed all its threads' calculations before continuing in the parent's calculations?
I know that I can't use cudaDeviceSynchronize(); inside parent kernel as it may result in problems. What can I do?
__device__... | According to Robert Crovella's comment, it seems the best solution now is to refactor the code to avoid any unpredictable results like this:
__global__ void child(double* A, double* B)
{
int r, c;
r = blockIdx.x * blockDim.x + threadIdx.x;
c = blockIdx.y * blockDim.y + threadIdx.y;
B[7 * r + c] += A[c];... |
73,535,031 | 73,536,251 | ctor is ambiguous between single and multiple std::initializer_list ctors on clang and gcc but not msvc | I have a nested initializer_list ctor for creating 2D matrixes. Works great. But then I decided to add a simplified row vector matrix (n rows, 1 col) using a single initializer list. This is so I could create a row matrix like this: Matrix2D<int> x{1,2,3} instead of having to do this: Matrix2D<int> x{{1},{2},{3}}. Of c... |
However, compiles w/o error Why are gcc and clang deductions
ambiguous?
Ambiguous arises here because {} or {1} can also initialize a single int.
Is there a workaround?
Template your specialized constructor such that {} is never deduced to initializer_list which still works for {1,2,3}.
#ifdef INCLUDE_EXTRA_CTOR
... |
73,535,050 | 73,535,348 | Streaming into `char` array with `ostream` - how to get characters written count? | This answer shows how to write to an array with stringstream, but can we obtain the total number of characters written? Surely the stringstream has some information to know where to put the next character, but I don't know how to access it.
The OP of the linked question even asks this in a comment but I wanted a separa... | The std::ostrstream class itself is deprecated.
Use std::ostringstream instead, which has a tellp() method.
#include <sstream>
int main()
{
char buf[1024];
std::ostringstream stream;
stream.rdbuf()->pubsetbuf(buf, sizeof(buf));
auto start = stream.tellp();
stream << "Hello " << "World " << std::e... |
73,535,669 | 73,836,978 | C++ Preprocessor Stringize - Different between GCC and MSVC | With the following example, the output is different between MSVC and GCC. Can someone please point me in the right direction to understand why?
#define TO_STRING(...) #__VA_ARGS__
#define QUOTE(...) TO_STRING(__VA_ARGS__)
#define KEY1 "Key1"
#define KEY2 "Key2"
#define KEY3 "Key3"
#define LEN1 32
#define LEN2 32
co... | According to C/C++: How should preprocessor directive work on macros argument list? , you can't put preprocessor directives (like #if) inside macro argument lists. The behavior of your code is undefined.
I think I would do:
#ifdef TEST
#define IF_TEST(...) __VA_ARGS__
#else
#define IF_TEST(...)
#endif
QUOTE(
....
IF... |
73,535,914 | 73,535,974 | Doesn't let me input new data via cin.get after the first one | I tried to make a code that takes the first two letters in three separate arrays, and concatenate them. For example, I put Dog, Cat, Rabbit, and it must show "DoCaRa". I tried to use cin.get but it only reads the first one, then it doesn´t let me enter new arrays. Here's the code:
#include <iostream>
#include <string.h... | cin.get (or1, 3); reads at most 2 chars until line end but leaves other characters and end-of-line character in the stream, so cin.get (or1, 3); reads do, cin.get (or2, 3); reads g until line end, cin.get (or3, 3); meets line end and will not give new inputs. Use the entire buffers for reading and cin.get() to consume ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.