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)
#endif
extern "C" PAMAIN_API double add(double x, double y);
My xll works fine when it doesn't call the new 'add' function. I then try writing the line of code
double z = add(1, 2);
anywhere within my xll project. The whole solution builds and links. But now when I import the generated xll into excel, I get error message The file format and extension of xll.xll don't match
What can the problem possibly be?
Thank you
|
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){return foo*x;};
}
Basically, I want to bind some values into the function (kind of like currying), and then call it later.
I want to use it through something like
functionMaker{2}(10)
But it errors me.
I verified that
functionMaker(2)(10)
works
And I explored what happens if I stored the function and then called it.
auto fct = functionMaker{2};
std::cout << fct(10) << std::endl;
fails, but
auto fct = functionMaker(2);
std::cout << fct(10) << std::endl;
works.
So it seems like braces just don't work here. What's going on? To reiterate, I would like to call it with something like functionMaker{2}(10). This way it's a bit easier for me to read which part is the construction and which part is the calling. What am I missing here?
|
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); }
std::function<int(int)> f;
};
It's a bit more clumsy, but you only need to write it once; you can even generalize it to be like, make_functionMaker(f, ...).
Note that you can save std::function's overhead by simply implementing the function in operator().
|
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 my CMake code in a way that I have to include my headers like this: #include<mylib/file.h>.
How can I do so?
Here is an example of my current setup:
CMakeLists.txt
|
|- mylib
| |- CMakeLists.txt
| |- include
| |- header1.h
| |- header2.h
|
|- test
|- CMakeLists.txt
|- mylib
|- header1_test.cpp
|- header2_test.cpp
Where the three CMakeLists.txt are:
# main CMakeLists.txt
# ... requirements, etc. ...
# ... fetch and include GoogleTest ...
add_subdirectory(mylib)
add_subdirectory(test)
# mylib/CMakeLists.txt
add_library(mylib INTERFACE)
target_include_directories(mylib INTERFACE include/)
# test/CMakeLists.txt
# link directories
link_directories(../mylib)
# test executable
add_executable(header1_test mylib/header1_test.cpp)
add_executable(header2_test mylib/header2_test.cpp)
# link libraries
target_link_libraries(header1_test PRIVATE mylib PRIVATE gtest_main)
target_link_libraries(header2_test PRIVATE mylib PRIVATE gtest_main)
# discover tests
gtest_discover_tests(header1_test)
gtest_discover_tests(header2_test)
|
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 library that is not part of your CMake project and in a different location that your linker doesn't search by default. Here, you create your lib mylib via add_library and everything is under the same CMake project (you have a root CMakeLists that adds 2 subdirectories).
Also, you don't need to duplicate the keyword PRIVATE:
target_link_libraries(header2_test PRIVATE mylib gtest_main)
|
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: warning: use emplace_back instead of push_back [modernize-use-emplace]
a.push_back(make_pair(1, 2)); //caught
^~~~~~~~~~~~~~~~~~~ ~
emplace_back
clang-tidy --version
LLVM (http://llvm.org/):
LLVM version 14.0.6
Optimized build.
Default target: x86_64-pc-linux-gnu
Host CPU: skylake
clang-tidy wiki
|
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 UseEmplaceCheck.cpp is:
auto CallPushBack = cxxMemberCallExpr(
hasDeclaration(functionDecl(hasName("push_back"))),
on(hasType(cxxRecordDecl(hasAnyName(SmallVector<StringRef, 5>(
ContainersWithPushBack.begin(), ContainersWithPushBack.end()))))));
Using the example from the question, the following simplified matcher (which can be passed to clang-query) will report the non-nested case, as expected:
cxxMemberCallExpr(
hasDeclaration(functionDecl(hasName("push_back"))),
on(hasType(cxxRecordDecl(hasName("std::vector"))))
)
Reports:
vector<pair<int, int>> a;
a.push_back(make_pair(1, 2)); //caught
However, to get it to match the nested case (when compiling with GCC-9.3.0 headers), it must be changed to:
cxxMemberCallExpr(
hasDeclaration(functionDecl(hasName("push_back"))),
on(hasType(namedDecl(hasName("::__gnu_cxx::__alloc_traits<std::allocator<std::vector<std::pair<int, int>>>, std::vector<std::pair<int, int>>>::value_type"))))
)
Reports:
vector<vector<pair<int, int>>> b(1);
b[0].push_back(make_pair(1, 2)); //not caught
That is, the type is no longer a cxxRecordDecl, and its name is a long template-id. That template-id is derived from the code used to declare std::vector::reference in the headers. It should be semantically equivalent to std::pair<int, int>, but that equivalence is evidently obscured from clang-tidy here.
|
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(int, bbb) \
template <class T> class A
{
public:
A(){ std::cout << "Hello From A\n";}
};
class B
{
public:
B() {std::cout << "Hello From B\n";}
};
int main()
{
#define X(a,b) \
if (0 == strlen(#a)) { \
printf("%s is empty\n", #b); \
B b; \
} else { \
printf("%s is NOT empty\n", #b); \
A<a> b; \
}
FOO
#undef X
return 0;
}
|
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. Here's a modified piece of code where the type AHelper serves to output something of the proper type.
/* By default, use A. */
template <typename... Args> struct AHelper {
using result = A<Args...>;
};
/* But not if there are no arguments. */
template <> struct AHelper<> {
using result = B;
};
int main() {
#define X(a,b) \
AHelper<a>::result b;
FOO
#undef X
}
(Initially, I thought this would be as easy as using if constexpr rather than if, but in a non-template context the compiler is supposed to evaluate both the if and else branch and the same compiler error results.)
|
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 orientation of the camera but the parts that I'm having issues with is changing the pitch, yaw, roll and finding out how to get the new up, right and direction vectors needed for the glm::lookAt function to create a view matrix.
So far this is my code with the functions I need help with marked:
#include "camera.hpp"
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/quaternion.hpp>
Camera::Camera(glm::vec3 position, glm::quat orientation, float zNear, float zFar)
{
this->position = position;
this->orientation = orientation;
right = glm::vec3( 1, 0, 0);
up = glm::vec3( 0, 1, 0);
direction = glm::vec3( 0, 0, -1);
this->zNear = zNear;
this->zFar = zFar;
updateViewMatrix();
}
Camera::Camera(glm::vec3 position, glm::vec3 orientation, float zNear, float zFar)
{
this->position = position;
this->orientation = glm::quat(glm::vec3(glm::radians(orientation.x), glm::radians(orientation.y), glm::radians(orientation.z)));
right = glm::vec3( 1, 0, 0);
up = glm::vec3( 0, 1, 0);
direction = glm::vec3( 0, 0, -1);
this->zNear = zNear;
this->zFar = zFar;
updateViewMatrix();
}
void Camera::setPosition(glm::vec3 position)
{
this->position = position;
}
void Camera::setOrientation(glm::quat orientation)
{
this->orientation = orientation;
}
void Camera::setOrientation(glm::vec3 orientation)
{
glm::quat orientationQuat = glm::quat(orientation);
this->orientation = orientationQuat;
}
void Camera::setPitch(float amount)
{
// NEED HELP
updateViewMatrix();
}
void Camera::setYaw(float amount)
{
// NEED HELP
updateViewMatrix();
}
void Camera::setRoll(float amount)
{
// NEED HELP
updateViewMatrix();
}
void Camera::setZNear(float zNear)
{
this->zNear = zNear;
updateProjectionMatrix();
}
void Camera::setZFar(float zFar)
{
this->zFar = zFar;
updateProjectionMatrix();
}
void Camera::move(glm::vec3 movement)
{
position += right * movement.x + up * movement.y + direction * movement.z;
updateViewMatrix();
}
void Camera::moveAxis(glm::vec3 translation)
{
position += translation;
updateViewMatrix();
}
void Camera::rotate(glm::quat rotation)
{
// NEED HELP
}
void Camera::rotate(glm::vec3 rotation)
{
glm::quat rotationQuat = glm::quat(rotation);
// NEED HELP
}
void Camera::pitch(float amount)
{
// NEED HELP
updateViewMatrix();
}
void Camera::yaw(float amount)
{
// NEED HELP
updateViewMatrix();
}
void Camera::roll(float amount)
{
// NEED HELP
updateViewMatrix();
}
// Excluded a few get___() functions here
glm::mat4 Camera::getViewMatrix() const
{
return viewMatrix;
}
glm::mat4 Camera::getProjectionMatrix() const
{
return projectionMatrix;
}
glm::mat4 Camera::getViewProjectionMatrix() const
{
return viewProjectionMatrix;
}
void Camera::updateViewMatrix()
{
viewMatrix = glm::lookAt(position, position + direction, up/*glm::cross(right, direction)*/);
viewProjectionMatrix = projectionMatrix * viewMatrix;
}
These are the relevant variables I create in my header file:
glm::vec3 position;
glm::quat orientation;
glm::vec3 direction; // Camera Direction / Camera View Facing
glm::vec3 right;
glm::vec3 up;
|
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(orientation * glm::vec3(0, 1, 0));
direction = glm::normalize(orientation * glm::vec3(0, 0, -1));
|
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 = 0
----> 3 array[index]
IndexError: list index out of range
But a code like this in C++ only gives us a generic address boundary error in both GCC and Clang compiler:
#include <vector>
int main(int argc, const char **argv) {
std::vector<int> array{};
int index = 0;
int value = array[index];
return 0;
}
Is there a way to have better runtime errors with more detail in C++??
|
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 or do anything else. This is a very important difference from Python that must be understood. In C++ if you violate language rules or preconditions of library functions there is no guarantee that the compiler or the program will tell you about it. It will just not behave as expected in many cases.
To figure out where such an error comes from you usually run your program under a debugger which will tell you the line that e.g. a segmentation fault (if one happened) occurred and allows you to step through the code.
You can guarantee that indexing a std::vector out-of-bounds will generate an error message by using its .at member function instead of indexing with brackets. If the index is then out-of-bounds an exception will be thrown which you can catch or let propagate out of main to terminate the program with some error message. However, the exception doesn't typically carry information about the point at which it was thrown. Again you'll need to run under a debugger to get that information.
Depending on your compiler and platform, if you keep using [], you may also be able to compile your program with a sanitizer enabled which will print a diagnostic including source lines when such an out-of-bounds access occurs. For example GCC and Clang have the address sanitizer which can be enabled with -fsanitize=address at compile-time. The option -g should be added as well to generate debug symbols that will be used in the sanitizer output to reference the source locations.
|
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 sure if this is happening because of some weird case where it is trying to push back something I didn't intend even though I double-checked it by putting outputs to see where it was happening.
==== Function ====
ifstream dataEve;
dataEve.open(fileName, std::ifstream::in);
std::vector<std::vector<string>> dataStore;
//string dataStore[10][10]; ***works if you replace the vector above***
string currentLine;
string currentObject;
int x = 0;
int y = 0;
while (!dataEve.eof()) {
getline(dataEve, currentLine, '\n');
stringstream ss(currentLine);
string currentLine;
while (std::getline(ss, currentObject, ',')) {
dataStore[x][y].push_back(currentObject);
//dataStore[x][y] = currentObject; ***works fine if you use this too***
std::cout << currentObject << "\t";
y++;
}
x++;
std::cout << "\n";
}
std::cout << "\n\n";
dataEve.close();
==== fileName.csv ====
Organism,Genetic Code
Felis catus,ACTG
Canis lupis,ATCG
|
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 x and y variables, but I left them in anyway.
Two errors in your code, firstly dataStore[x][y] doesn't exist as the vector has zero size, so that would be a run time error.
Secondly dataStore[x][y] is a string, so if you push_back on a string the compiler expects you to give a char. That's the reason for the compiler error.
|
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 event and BitBlt() "solves" the problem.
The issue happens randomly and only to some windows. Can someone explain what's happening and how to properly fix this?
Here's a minimal reproduceable example:
VOID CALLBACK WinEventProcCallback(HWINEVENTHOOK hWinEventHook, DWORD dwEvent, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
if (dwEvent == EVENT_SYSTEM_FOREGROUND && hwnd)
{
// Sleep(20); // This "solves" the issue
HDC dcScreen = GetDC(hwnd);
HDC dcTarget = CreateCompatibleDC(dcScreen);
HBITMAP bmpTarget = CreateCompatibleBitmap(dcScreen, 100, 100);
HGDIOBJ oldBmp = SelectObject(dcTarget, bmpTarget);
BitBlt(dcTarget, 0, 0, 100, 100, dcScreen, 100, 100, SRCCOPY | CAPTUREBLT);
SelectObject(dcTarget, oldBmp);
DeleteDC(dcTarget);
ReleaseDC(hwnd, dcScreen);
}
}
int main()
{
SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL, WinEventProcCallback, 0, 0, WINEVENT_OUTOFCONTEXT);
MSG msg;
while (GetMessageA(&msg, NULL, 0, 0)) {}
return 0;
}
|
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 returns a long double again.
Another function lround can only return long and works on a smaller range of values.
So given a long double, how to do I round it to the nearest integer of type, unsigned long long?
Thanks.
Related Question
Cast from unsigned long long to double and vice versa changes the value
|
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 integral type, you'll get the exact same value back as long as the integer is not larger than the representable limit.
For double precision numbers, as explained in this answer, that's 2^53, which is big enough for all 32 bit integers. We can apply the same general formula for for quad precision numbers, and get 2^113, which is big enough for all 64 bit integers.
So, if long double on your implementation is a quad precision number, and unsigned long long is a 64 bit integer, then you can safely do the roundtrip:
unsigned long long i = /* a very big value */;
long double d = i; // safe because it's a widening conversion
assert(static_cast<unsigned long long>(d) == i); // should pass
Now, if you don't have an integer in that long double, then of course there'll be some loss, because that fraction will have to be cut. If you round the number first, you'll end up with an integer, and that is representable, so no loss (assuming it's not bigger than 2^113), but of course you'll still end up with a different number than the one you started with before the rounding.
long double d = /* a very big value */;
unsigned long long i = static_cast<unsigned long long>(std::roundl(d));
Or you can avoid the cast altogether by using std::llroundl:
long double d = /* a very big value */;
unsigned long long i = std::llroundl(d);
Although you'll need to be careful about negative numbers (but that's easy to check beforehand).
All of this assumes that your long double is never bigger than 2^64, but if it were, then you wouldn't be able to fit it into the unsigned long long anyway.
|
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 bad then..." << std::endl;
} else {
std::cout << "What do you mean by that?" << std::endl;
}
return 0;
}
If I don't write the commented return 0 line and input yes, the output is Let's rock and roll! followed by What do you mean by that?. It should only output Let's rock and roll!.
But I don't need to put return 0 in the if (question=="no"){...} block. If I input no, the output is just Too bad then....
Why do I need the return 0 in the first case, but not the second?
|
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 better by surrounding if/else statements/blocks with newlines and adding some whitespace around operators.
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;
}
These are two different conditionals. The first one being triggered does not stop the second if/else from being evaluated. In fact, if question equals "yes" then it cannot equal "no" so the else clause in the second if/else must be executed.
By including return 0; in the first conditional block, the function exits immediately, thus skipping everything after it. The second if/else is not evaluated and "What do you mean by that?" is never printed.
You likely wanted this to be a single if/else. Now only one of these blocks will be executed. Because an else is included as a catch-all in the event none of the previous conditions were met, it is guaranteed one branch will be executed.
if (question == "yes") {
std::cout << "Lets rock and roll!" << std::endl;
}
else if (question == "no") {
std::cout << "Too bad then..." << std::endl;
}
else {
std::cout << "What do you mean by that?" << std::endl;
}
|
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 {
// Only compare up to the size of the prefix
auto result = l.compare(0, r.of.length(), r.of);
return result < 0;
}
bool operator()(prefix l, std::string_view r) const {
auto result = r.compare(0, l.of.length(), l.of);
return result > 0;
}
};
(Full example usage)
So prefix_comparator::prefix{ "XYZ" } compares equivalent to any string starting with "XYZ" with this comparator. Would it be UB to use this in a std::set?
It does not form equivalence classes with things of type prefix_comparator::prefix, since prefix objects cannot be compared with each other and stuff like equiv("XYZABC", prefix{ "XYZ" }) && equiv(prefix{ "XYZ" }, "XYZabc") but not equiv("XYZABC", "XYZabc"). But the set doesn't store prefix objects, so I don't know if this applies.
It seems to work fine in practice (with libstdc++ std::set): count() returns the correct value greater than 1, equal_range can return an iterator range larger than one element, etc. I'm unsure if find is usable since it only returns an iterator to a single element (possibly it only returns an arbitrary element?)
|
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 restrictions on methods and what the arguments are. Here is the common set used:
(7.20) kl is a value such that a is partitioned ([alg.sorting]) with respect to c(x, kl), with x the key value of e and e in a;
(7.21) ku is a value such that a is partitioned with respect to !c(ku, x), with x the key value of e and e in a;
(7.22) ke is a value such that a is partitioned with respect to c(x, ke) and !c(ke, x), with c(x, ke) implying !c(ke, x) and with x the key value of e and e in a;
(7.23) kx is a value such that
(7.23.1) a is partitioned with respect to c(x, kx) and !c(kx, x), with c(x, kx) implying !c(kx, x) and with x the key value of e and e in a, and
(7.23.2) kx is not convertible to either iterator or const_iterator; and [...]
these are used in concert with a_tran, which is the shortcut the standard uses for "an associative container when Compare has is_transparent", to describe the requirements of most (all?) of the extra methods you get when you have is_transparent turned on.
So under this, the important part is that your non-key elements actually used actually partition your container with the actual keys stored in the container:
a_tran.erase(kx)
122 # Result: size_type
123 # Effects: Erases all elements in the container with key r such that !c(r, kx) && !c(kx, r) is true.
what this means is you have to check each and every methods requiements for what it expects. Count, for example:
a_tran.count(ke)
150 # Result: size_type
151 # Returns: The number of elements with key r such that !c(r, ke) && !c(ke, r).
152 # Complexity: log(a_tran.size())+a_tran.count(ke)
So here the argument must be ke, so the specific value passed in has to be a "nice" partition of the current contents of the associative container.
|
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&&) [with _T1 = unsigned int; _T2 = std::unique_ptr<Panel>&; typename std::__strip_reference_wrapper<typename std::decay<_Tp2>::type>::__type = std::unique_ptr<Panel>; typename std::decay<_Tp2>::type = std::decay<std::unique_ptr<Panel>&>::type; typename std::__strip_reference_wrapper<typename std::decay<_Tp>::type>::__type = unsigned int; typename std::decay<_Tp>::type = unsigned int]((* &((Screen*)this)->Screen::panels.std::vector<std::unique_ptr<Panel> >::emplace_back<>()))’ from ‘pair<[...],std::unique_ptr<Panel>>’ to ‘pair<[...],std::unique_ptr<Panel>&>’
67 | return std::make_pair<PanelID, Panel_Ptr&>(
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
| |
| pair<[...],std::unique_ptr<Panel>>
68 | std::move(panelID), panels.emplace_back());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Screen
{
private:
using PanelID = uint32_t;
using Panel_Ptr = std::unique_ptr<Panel>;
std::vector<Panel_Ptr> panels {};
public:
std::pair<PanelID, Panel_Ptr&> foo()
{
PanelID panelID {static_cast<PanelID>(panels.size())};
return std::make_pair<PanelID, Panel_Ptr&>(
std::move(panelID), panels.emplace_back());
}
};
|
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<X> for some type X, in which case the deduced type is X&.
https://en.cppreference.com/w/cpp/utility/pair/make_pair
Remove your explicit instantiation of the type parameters of std::make_pair() and wrap the emplace_back() call with std::ref:
return std::make_pair(
std::move(panelID),
std::ref(panels.emplace_back())
);
Alternatively, you can explicitly make the std::pair:
return std::pair<PanelID, Panel_Ptr&>(
std::move(panelID),
panels.emplace_back()
);
Finally, to note on your code, you are calling std::move() on your PanelID type even though it is just an integer. std::move() is useless in that scenario, so removing it entirely would make your code clearer.
Though, putting the generation of panelID on a separate statement is still necessary due to the unspecified order of evaluation of arguments passed to functions. Good awareness of this fact.
|
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 == array[i][j][k])
result++;
}
}
}
return result;
}
int main()
{
int b;
const int a = 3;
int nums[a][a][a] = { rand() % 10 };
int array = sizeof(nums);
cout << "===================================================================================" << endl;
cout << "==========================DISPLAYING 3X3X3 ARRAY ELEMENTS==========================" << endl;
for (int i = 0; i < a; ++i) {
for (int j = 0; j < a; ++j) {
for (int k = 0; k < a; ++k) {
cout << setw(10) << "[ array[" << i << "][" << j << "][" << k << "] = " << nums[i][j][k] << " ]" << " ";
}
cout << endl;
}
}
cout << endl;
cout << endl;
cout << endl;
cout << "Please enter a target value : ";
cin >> b;
cout << "The number of occurrences of " << b << " : " << count_occurrences(nums, a, b) << " times";
return 0;
}
|
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] = {
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10,
rand() % 10, rand() % 10, rand() % 10
};
A cleaner, more programmatic way would be like this:
int nums[a][a][a];
for(int i = 0; i < a; i++){
for(int j = 0; j < a; j++){
for(int k = 0; k < a; k++){
nums[i][j][k] = rand()%10;
}
}
}
|
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 newer jobs failing -- and so I've started looking into dockerizing these builds to try to guarantee better reliability and stability.
However, I'm having some difficulty understanding what a proper and idiomatic approach is to producing build images like this without causing a large amount of duplication caused by layers.
For example, let's say I want to build using the following toolset:
gcc 4.8, 4.9, 5.1, ... (various versions)
cmake (latest)
ninja-build
I could write something like:
# syntax=docker/dockerfile:1.3-labs
# Parameterizing here possible, but would cause bloat from duplicated
# layers defined after this
FROM gcc:4.8
ENV DEBIAN_FRONTEND noninteractive
# Set the work directory
WORKDIR /home/dev
COPY . /home/dev/
# Install tools (cmake, ninja, etc)
# this will cause bloat if the FROM layer changes
RUN <<EOF
apt update
apt install -y cmake ninja-build
rm -rf /var/lib/apt/lists/*
EOF
# Default command is to use CMak
CMD ["cmake"]
However, the installation of tools like ninja-build and cmake occur after the base image, which changes per compiler version. Since these layers are built off of a different parent layer, this would (as far as I'm aware) result in layer duplication for each different compiler version that is used.
One alternative to avoid this duplication could hypothetically be using a smaller base image like alpine with separate installations of the compiler instead. The tools could be installed first so the layers remain shared, and only the compiler changes as the last layer -- however this presents its own difficulties, since it's often the case that certain compiler versions may require custom steps, such as installing certain keyrings.
What is the idiomatic way of accomplishing this? Would this typically be done through multiple docker files, or a single docker file with parameters? Any examples would be greatly appreciated.
|
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 you could spin up multiple instances the same time.
ARG COMPILER=gcc:4.8
FROM ${COMPILER}
ENV DEBIAN_FRONTEND noninteractive
# Install tools (cmake, ninja, etc)
# this will cause bloat if the FROM layer changes
RUN <<EOF
apt update
apt install -y cmake ninja-build
rm -rf /var/lib/apt/lists/*
EOF
# Set the work directory
VOLUME /src
WORKDIR /src
CMD ["cmake"]
Build it
Here you have few options. You could either prepare a volume with the sources or use bind mounts together with docker exec like this:
#bash style
for compiler in gcc:4.9 gcc:4.8 gcc:5.1
do
docker build -t mytag-${compiler} --build-arg COMPILER=${compiler} .
# place to clean the target folder
docker run -v $(pwd)/src:/src mytag-${compiler}
done
And because the source is not part of the docker image you don't have bloat. You can also have two mounts, one for a readonly source tree and one for the output files.
Note: If you remove the CMake command you could also spin up the docker containers in parallel and use docker exec to start the build. The downside of this is that you have to take care of out of source builds to avoid clashes on the output folder.
|
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 capture a functor allocated by new.
However, I found that after I passed the function created by foo into evaluate the address of the functor changed and the program did some crazy things.
Example
Here's a simplified reproducible example,
#include <iostream>
#include <functional>
using namespace std;
double evaluate(const function<double (const double &)> foo) {
double result = 0.0;
for (double i=0; i<1; ++i) {
result += foo(i);
}
return result;
}
struct Bar {
double a;
explicit Bar(const double &a): a(a) {}
double operator()(const double &b) const {
return b * a;
}
};
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);
};
return result;
}
int main() {
auto f = foo(1);
auto v = f(2);
cout << "value of f(2): " << v << endl;
v = evaluate(f);
cout << "evaluate(f): " << v << endl;
return 0;
}
A possible output of the above code could be
address of bar: 0x7ff7b787c870
value of f(2): 4.3834e-314
address of bar: 0x7ff7b787c840
evaluate(f): 0
Questions
Can anyone
explain why the address of the functor changed;
provide other better ways of doing this? (assume I cannot directly pass the functor to the evaluate function)
|
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);
};
return result;
}
And you want to access it in other places assuming it exists. You should have already noticed a problem in your code from this result:
value of f(2): 4.3834e-314
Because it should be 2. If you write code as follows:
function<double(const double &)> foo(const double &a) {
function<double (const double &)> result = [bar = new Bar(a)](const double &b) {
cout << "address of bar: " << bar << endl;
return (*bar)(b);
};
return result;
}
It will work as you expect. Just remember to use std::unique_ptr rather than raw pointer here. This code, as it is right now, has a memory leak as a result of forgetting to release memory.
|
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;
vObj.push_back(temNum);
cout << "\n\n Cycle\n\n";
cout << "Temp Num: " << temNum << "\n\nN: " << nCopy << endl;
}
return 0;
}
For example, I input 0.59392 but eventually when the code reaches the bottom, where it should be going
5939.2 and then go to
59392 and stop but for some reason
it keeps going.
|
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 the best one , but it works for this case :
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
std::vector<int> vObj;
double n = 0.59392;
double nCopy = n;
int temNum = 0;;
while (fmod(nCopy, 1) != 0) {
temNum = (nCopy * 10); cout << endl << nCopy << endl;
nCopy *= 10;
vObj.push_back(temNum);
cout << "\n\n Cycle\n\n";
cout << "Temp Num: " << temNum << "\n\nN: " << nCopy << endl;
}
return 0;
}
so the explanation is as follow , the double data types gives higher precision than float , that's why I used double instead of float , but it will lack accuracy when the number becomes big .
second of : you have to how is float or double is represented , as the value 0.59392 is actually stored in the memory as value 0.593900024890899658203125 when using float according to IEEE 754 standard , so there are other types of decimals to solve this problem where the difference between them is as follow
Decimal representation gives lower accuracy but higher range with big numbers and high accuracy when talking about small numbers, most 2 used standards are binary integer decimal (BID) and densely packed decimal (DPD)
float and doubles gives higher accuracy than Decimal when talking about big numbers but lower range ,they follow IEEE 754 standard
Fixed-Point types have the lowest range but they are the most accurate one and they are the fastest ones
but unfortunately , C++ only supports float and double types of numbers , but I believe there is external libraries out there to define a decimal data type.
|
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 winner with a function that uses 8 if statements to check for win conditions (3 horizontals, 3 verticals, or 2 diagonals).
int winCheck()
{
int winner = 0;
// check horizontal 1
if ((board[0][0] == board[0][1] == board[0][2]) && (board[0][2] > 0))
{
winner = board[0][0];
}
// check horizontal 2
...
return winner;
}
Any ideas? I think the logic is fine but my syntax is off.
|
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 necessarily work because it'll be reset during the call.
int drawSierpinskiTriangle(GWindow& window, GPoint one, GPoint two, GPoint three, int order) {
if (order == 0) fillBlackTriangle(window, one, two, three); // order 0 triangle
// one is left point, two is right point, three is top point
else {
int count = 0;
GPoint bottom = { (one.x + two.x)/ 2, (one.y + two.y)/ 2 }; // bottom side of triangle
GPoint right = { (two.x + three.x)/ 2, (two.y + three.y)/ 2 }; // right side of triangle
GPoint left = { (one.x + three.x)/ 2, (one.y + three.y)/ 2 }; // left side of triangle
drawSierpinskiTriangle(window, one, left, bottom, order - 1);
drawSierpinskiTriangle(window, two, right, bottom, order - 1);
drawSierpinskiTriangle(window, three, left, right, order - 1);
count++;
return count;
}
return 0;
}
|
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(window, one, left, bottom, order - 1);
count += drawSierpinskiTriangle(window, two, right, bottom, order - 1);
count += drawSierpinskiTriangle(window, three, left, right, order - 1);
In addition you should return 1 when the recursion reaches the end (otherwise you will only accumulate zeroes):
if (order == 0)
{
fillBlackTriangle(window, one, two, three); // order 0 triangle
return 1;
}
|
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 coredumpctl gdb.
My question is: can I do similar on Cloud Run? Can I collect coredump files and get them from somewhere like Cloud Storage?
|
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 that feature. Cloud Run does not provide access to the host platform.
Note: Cloud Run runs containers via Knative.
|
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 = y.load(std::memory_order_relaxed); // A
x.store(r1, std::memory_order_relaxed); // B
// Thread 2:
r2 = x.load(std::memory_order_relaxed); // C
y.store(42, std::memory_order_relaxed); // D
is allowed to produce r1 == r2 == 42 because, although A is sequenced-before B within thread 1 and C is sequenced before D within thread 2, nothing prevents D from appearing before A in the modification order of y, and B from appearing before C in the modification order of x. The side-effect of D on y could be visible to the load A in thread 1 while the side effect of B on x could be visible to the load C in thread 2. In particular, this may occur if D is completed before C in thread 2, either due to compiler reordering or at runtime.
My question is: C is sequenced-before D in thread2 thus C is also happens-before D, right?
Does the reordering of operation D and C contradict with what says in the book, that relaxed operations can be reordered but must obey happens-before relationships? In what conditions can relaxed operations be reordered?
|
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 program will actually do (its observable behavior). And that is ultimately dictated by what values are returned by your loads. The happens-before relation provides such information in three ways:
the coherence rules explained on the page you link (write-write, read-write and so on),
in telling you whether or not you have a data race
via the "visible side effect" rule. (cppreference misstates that rule: it phrases it in terms of modification order, but it is meant to apply to non-atomic variables which in C++20 do not have a modification order.)
All of those rules are ultimately based on knowing whether or not you have a happens-before relationship between two reads or writes of the same variable.
So since C and D are accesses to different variables, the only reason that we would care whether one happens before the other is if we can use that fact as part of a longer chain of reasoning, to eventually deduce a happens-before (or a "does not happen before") between two accesses to the same variable. In the program at hand, we have no way to do that. The statement that C happens before D is true but completely useless, and so it does not in any way restrict the compiler / machine from reordering how C and D are actually executed or made visible.
In understanding relations such as happens before, dependency-ordered before, etc, it is best to be guided by the actual formal definitions, and not by your intuition about what their names seem to imply. The names are just names.
|
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) {
...
} else if (m_type == 1) {
...
}
}
};
Example 2 (const char* equals const char*)
struct some_struct {
const char* m_type;
...
inline constexpr
void somefunc() {
if (strcmp(m_type, "some_str_1")) {
...
} else if (strcmp(m_type, "some_str_2")) {
...
}
}
};
Edit:
As @RichardCritten pointed out, strcmp is not a constexpr function. Though in my actual code I have a custom strcmp function that is a constexpr function.
|
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, optimizer might optimize and return a result computed at compilation, constexpr might be a hint for compiler in that regards).
|
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 using fluxbox; so apparently that can show utf8 titles).
I tried to set the same title in my own application, but the result looks quite different:
. The one on top is chromium, the one below that is my own application.
Also xprop shows a difference:
WM_NAME(UTF8_STRING) = "Apple (Россия) – Официальный сайт - Chromium"
_NET_WM_NAME(UTF8_STRING) = "Apple (Россия) – Официальный сайт - Chromium"
whereas my application gives:
_NET_WM_NAME(UTF8_STRING) = 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20, 0x28, 0xd0, 0xa0, 0xd0, 0xbe, 0xd1, 0x81, 0xd1, 0x81, 0xd0, 0xb8, 0xd1, 0x8f, 0x29, 0x20, 0xe2, 0x80, 0x93, 0x20, 0xd0, 0x9e, 0xd1, 0x84, 0xd0, 0xb8, 0xd1, 0x86, 0xd0, 0xb8, 0xd0, 0xb0, 0xd0, 0xbb, 0xd1, 0x8c, 0xd0, 0xbd, 0xd1, 0x8b, 0xd0, 0xb9, 0x20, 0xd1, 0x81, 0xd0, 0xb0, 0xd0, 0xb9, 0xd1, 0x82, 0x20, 0x2d, 0x20, 0x43, 0x68, 0x72, 0x6f, 0x6d, 0x69, 0x75, 0x6d
WM_NAME(UTF8_STRING) = "Apple (\320\240\320\276\321\201\321\201\320\270\321\217) \342\200\223 \320\236\321\204\320\270\321\206\320\270\320\260\320\273\321\214\320\275\321\213\320\271 \321\201\320\260\320\271\321\202 - Chromium"
Thus, despite that xprop says that the type is 'UTF8_STRING' in both cases, in my case it isn't displaying the values as utf8 strings.
The (C++20) code that I used looks as follows:
xcb_connection_t* m_connection = ...;
xcb_window_t handle = ...;
xcb_atom_t m_utf8_string_atom;
xcb_atom_t m_net_wm_name_atom;
...
xcb_intern_atom_cookie_t utf8_string_cookie = xcb_intern_atom(m_connection, 0, 12, "UTF8_STRING");
xcb_intern_atom_reply_t* utf8_string_reply = xcb_intern_atom_reply(m_connection, utf8_string_cookie, 0);
m_utf8_string_atom = utf8_string_reply->atom;
free(utf8_string_reply);
xcb_intern_atom_cookie_t net_wm_name_cookie = xcb_intern_atom(m_connection, 0, 12, "_NET_WM_NAME");
xcb_intern_atom_reply_t* net_wm_name_reply = xcb_intern_atom_reply(m_connection, net_wm_name_cookie, 0);
m_net_wm_name_atom = net_wm_name_reply->atom;
free(net_wm_name_reply);
...
xcb_void_cookie_t ret = xcb_create_window(m_connection, XCB_COPY_FROM_PARENT, handle,
parent_handle ? parent_handle : m_screen->root, x, y, width, height,
border_width, _class, m_screen->root_visual, value_mask, value_list.data());
std::u8string t = u8"Apple (Россия) – Официальный сайт - Chromium";
// Set window name.
xcb_change_property(m_connection, XCB_PROP_MODE_REPLACE, handle,
XCB_ATOM_WM_NAME, m_utf8_string_atom, 8,
t.size(), t.data());
xcb_change_property(m_connection, XCB_PROP_MODE_REPLACE, handle,
m_net_wm_name_atom, m_utf8_string_atom, 8,
t.size(), t.data());
...
// Display window.
xcb_map_window(m_connection, handle);
xcb_flush(m_connection);
What am I doing wrong?
|
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...
It works now!
|
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;
cout << *a << endl;
}
};
int main() {
thread th1(thread_obj(), 1);
thread th2(thread_obj(), 1);
thread th3(thread_obj(), 1);
thread th4(thread_obj(), 1);
// Wait for thread t1 to finish
th1.join();
// Wait for thread t2 to finish
th2.join();
// Wait for thread t3 to finish
th3.join();
while (true) {
// th4 is still running
/* whether the memory allocated for (int* a = new int;) is freed automatically when thread 1, 2, 3 joins main thread
Does this cause memory leak or I must delete them manually?*/
}
th4.join();
return 0;
}
Memory allocated for new int in th1, th2, th3, th4.
After joining (th1, th2, th3) in main thread, are they deallocated automatically and free to use for th4?
Thanks in advance.
|
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 to live and will never be destroyed by the program.
|
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.cpp
#include "Player.hpp"
#include "string.h"
#include <iostream>
void Player::initPlayer()
{
const char* playerTexturePath = "/Users/don/Desktop/sfmlgames/game1/img/MCmid.png";
if(!mPlayerTexture.loadFromFile(playerTexturePath))
{
std::cout << "mPlayerTexturePath not found!!" << std::endl;
}
mPlayerSprite.setTexture(mPlayerTexture);
mPlayerSprite.setPosition(100.f, 100.f);
mPlayerSprite.setScale(1.f, 1.f);
}
void Player::draw_player(sf::RenderWindow &win)
{
win.draw(mPlayerSprite);
}
Game.cpp
#include "Game.hpp"
#include <iostream>
Player player1;
//Constructor: Create a window and Player
Game::Game() : mWindow(sf::VideoMode(640, 480), "Game")
{
//Frame rate 60
mWindow.setFramerateLimit(60);
player1.initPlayer();
}
//Game loop
void Game::Run()
{
while(mWindow.isOpen())
{
render();
events();
update();
}
}
void Game::events()
{
sf::Event event;
while (mWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
mWindow.close();
}
}
}
void Game::update()
{
}
void Game::render()
{
mWindow.clear(sf::Color::Red);
player1.draw_player(mWindow);
mWindow.display();
}
main.cpp
#include "Game.hpp"
int main()
{
Game game;
game.Run();
}
I don't think I will need to give code to hpp files.
|
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 <iostream>
#include <vector>
using namespace std;
// recursive function to include/excluded every element in the sum.
long long solve(int N,int sum, int* coins, long long mysum, vector<vector<long long >> &my, long long j){
if (mysum == sum){
return 1;
}if (mysum>sum){
return 0;
}
if (my[mysum][j]!=-1){
return my[mysum][j];
}
long long ways = 0;
while (j<N){
ways+= solve (N,sum,coins,mysum+coins[j],my, j);
j++;
}
//Line in question
return my[mysum][j] = ways;
}
int main() {
// code here.
int N=3;
int coins[] = {1,2,3};
int sum =4;
int check = INT_MIN;
vector<vector<long long int>> my(sum+1,vector<long long int>(N+1,-1));
cout<< solve (N,sum,coins,0,my,0)<< " ";
// traversing to check if the memoizing vector stored the return values
for (int x=0; x<sum+1; x++){
for (int y=0; y<N; y++){
if (my[x][y]!=-1){
check = 0;
}
}
}
cout<< check;
return 0;
}
output: 4 -2147483648
|
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
+-- File2.cpp
+-- File2.h
+-- TestMainProject(dir)
+-- TestFile1.cpp
+-- TestFile2.cpp
+-- Subdirectory(dir)
+-- TestFile1.cpp
+-- TestFile2.cpp
For the MainProject I'd like to include all files from the MainProject folder with filters following the folder structure.
For the TestMainProject I'd like to include all files from the MainProject folder with filters following the folder structure but also put all these files under the MainProject filter. Same for the TestMainProject directory: put all files under the TestMainProject filter and follow the folder structure.
I want to achieve this:
So I wrote this code:
cmake_minimum_required(VERSION 3.10)
project("CMake Subdirectories Filters Example")
set(main_project_name "MainProject")
set(main_project_path "${PROJECT_SOURCE_DIR}/${main_project_name}")
file(GLOB_RECURSE main_project_files "${main_project_path}/*.h" "${main_project_path}/*.cpp")
add_executable(${main_project_name} ${main_project_files})
source_group(TREE "${main_project_path}/" FILES ${main_project_files})
function(group_source_files_into_filter_with_folder_structure files_list project_path filter_to_put_into)
foreach(file_path IN LISTS files_list)
get_filename_component(file_directory_path "${file_path}" DIRECTORY)
string(REPLACE ${project_path} ${filter_to_put_into} file_path_msvc_relative "${file_directory_path}")
string(REPLACE "/" "\\" source_path_msvc "${file_path_msvc_relative}")
source_group("${source_path_msvc}" FILES "${file_path}")
endforeach()
endfunction()
set(test_main_project_name "TestMainProject")
set(test_main_project_path "${PROJECT_SOURCE_DIR}/${test_main_project_name}")
file(GLOB_RECURSE test_main_project_files "${test_main_project_path}/*.h" "${test_main_project_path}/*.cpp")
add_executable(${test_main_project_name} ${main_project_files} ${test_main_project_files})
group_source_files_into_filter_with_folder_structure("${main_project_files}" "${main_project_path}" "${main_project_name}")
group_source_files_into_filter_with_folder_structure("${test_main_project_files}" "${test_main_project_path}" "${test_main_project_name}")
It almost does the job:
It does create filters as I want it to for the TestMainProject: it creates the additional TestMainProject filter for the TestMainProject folder and additional MainProject filter for the MainProject folder.
The problem is that it also creates additional MainProject filter for the MainProject folder in the MainProject folder:
And here's what I'd like to achieve:
See how there is no MainProject filter in the MainProject project.
Is there a way to do what I would like to do? Feels like I hit a limit of CMake and there's no way because, apparently, source_group is global and it creates the group for the files for all projects.
|
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_project_name}")
file(GLOB_RECURSE main_project_files "${main_project_path}/*.h" "${main_project_path}/*.cpp")
add_subdirectory(MainProject)
add_subdirectory(TestMainProject)
CMakeLists.txt in the MainProject folder:
add_executable(${main_project_name} ${main_project_files})
source_group(TREE "${main_project_path}/" FILES ${main_project_files})
CMakeLists.txt in the TestMainProject folder:
cmake_minimum_required(VERSION 3.10)
set(test_main_project_name "TestMainProject")
set(test_main_project_path "${PROJECT_SOURCE_DIR}/${test_main_project_name}")
file(GLOB_RECURSE test_main_project_files "${test_main_project_path}/*.h" "${test_main_project_path}/*.cpp")
add_executable(${test_main_project_name} ${main_project_files} ${test_main_project_files})
source_group(TREE "${main_project_path}/" PREFIX "${main_project_name}" FILES ${main_project_files})
source_group(TREE "${test_main_project_path}/" PREFIX "${test_main_project_name}" FILES ${test_main_project_files})
Now it generates the correct filters, just as I wanted:
|
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 being implemented as p->~T() because T may be substituted with a scalar type.
However, the following code compiles:
template <typename T>
void destroy_at(T* p)
{
p->~T();
}
int main()
{
int i = 0;
destroy_at(&i);
}
I don't know why.
What's the point of disallowing such use?
|
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-destructor calls are necessary at all is generic code like this.
If you knew exactly what the type that p points to is while writing the code and you knew it to be non-class, then there wouldn't be any point in writing a pseudo-destructor call. Such a call could practically always be removed without affecting the program (assuming it didn't have undefined behavior to begin with).
The only place where it could affect behavior of the program that I can think of is when testing whether an expression is a constant expression (since C++20). The pseudo-destructor call ends the lifetime of the object and therefore could disqualify an expression that would otherwise be a constant expression from being one.
|
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 whole string will be copied. In this program below s2 string is not displayed, Why?
#include<iostream>
#include<cstring>
using namespace std;
class String // user defined string type
{
protected:
enum { SZ = 80 }; // size of all String objects
char str[SZ]; // holds a C-string
public:
String() // no-argument constructor
{ str[0] = '\0'; }
String( char s[] ) // 1-argument constructor
{ strcpy( str, s); } // converts C-string to String
void display() const // display the String
{ cout << str ; }
operator char*() // conversion operator
{ return str; } // converts String to C-string
};
class Pstring : public String // class Pstring ( derived publically from String class)
{
public:
Pstring() : String() // no-argument constructor
{ }
Pstring( char s[] ); // 1-argument constructor declared
};
Pstring::Pstring( char s[] ) // 1-argument constructor
{
if( strlen(s) > SZ-1 )
{
for( int i = 0; i < SZ-1; i++)
str[i] = s[i];
str[SZ-1] = '\0';
}
else
String(s);
}
int main()
{
Pstring s1, s2;
s1 = "My name is Lakhan and your name is Ram Kumar. My age is 35 and your age is 40
then how I am your uncle"
" You are a damn duff who can't understand this small thing that whether a thing is
right or wrong";
s2 = "My name is lakhan and your is what??";
cout << "\ns1 = "; s1.display();
cout << "\ns2 = "; s2.display(); // Here is the problem( it is not displayed)
cout << endl;
return 0;
}
|
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_opencv PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java4.so) ,it will compile successfully.
my cmakelist :
cmake_minimum_required(VERSION 3.10.2)
project(OPENcv_app)
include_directories(../include)
# opencv
set(OpenCV_STATIC ON)
set(OpenCV_DIR c:/tools/OpenCV-android-sdk/sdk/native/jni)
find_package(OpenCV REQUIRED)
add_library( # Sets the name of the library.
native_opencv SHARED
lib_opencv SHARED IMPORTED
# Provides a relative path to your source file(s).
../ios/Classes/ArucoDetector/ArucoDetector.cpp
../ios/Classes/native_opencv.cpp
)
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java4.so)
target_include_directories(
native_opencv PRIVATE
../ios/Classes/ArucoDetector
)
find_library(log-lib log)
target_link_libraries( # Specifies the target library.
native_opencv
${OpenCV_LIBS}
lib_opencv
${log-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/ArucoDetector/ArucoDetector.cpp
../ios/Classes/native_opencv.cpp
)
# create imported library lib_opencv
add_library(lib_opencv SHARED IMPORTED)
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libopencv_java4.so)
|
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)
{
volkInitialize();
WindowProps props = {};
props.Height = 600;
props.Width = 800;
props.Title = "Engine";
currentWindow = EngWindow::Create(props);
//Create all physical, logical, instance for vulkan
Prepare();
VolkDeviceTable test;
volkLoadDeviceTable(&test, m_LogicalDevice->GetVkDevice());
VmaAllocatorCreateInfo allocatorCreateInfo = {};
allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2;
allocatorCreateInfo.physicalDevice = m_PhysicalDevice->GetVkPhysicalDevice();
allocatorCreateInfo.device = m_LogicalDevice->GetVkDevice();
allocatorCreateInfo.instance = m_Instance->GetRawVkInstance();
allocatorCreateInfo.pVulkanFunctions = reinterpret_cast<const VmaVulkanFunctions*> (&test);
VmaAllocator allocator;
vmaCreateAllocator(&allocatorCreateInfo, &allocator);
BuildRenderPipelines(t_Conf, t_reg);
}
void VulkApp::Prepare()
{
m_Instance = std::make_unique<VulkInst>();
volkLoadInstance(m_Instance->GetRawVkInstance());
currentWindow->CreateSurface(m_Instance->GetRawVkInstance(), &m_Surface);
m_PhysicalDevice = std::make_unique<PhysicalDevice>(*m_Instance);
m_LogicalDevice = std::make_unique<LogicalDevice>(*m_Instance, *m_PhysicalDevice, m_Surface);
volkLoadDevice(m_LogicalDevice->GetVkDevice());
m_SwapChain = std::make_unique<SwapChain>(ChooseSwapExtent(), *m_LogicalDevice, *m_PhysicalDevice, m_Surface);
GraphicsHelpers::CreateCommandPool(m_CommandPool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); //TODO: added Transient bit
CreateFrameSyncResources();
/*
Create Camera
*/
BuildSwapChainResources();
}
I don't have any error when i build, but when i execute, the VmaCreateAllocator return an error:
Exception raised at 0x00007FFAB0CD836B (VkLayer_khronos_validation.dll) in My_Game.exe : 0xC0000005 : access violation reading location 0x0000000000000120.
Not very useful, but it stops on the line 14082 of the file vk_mem_alloc.h:
(*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps);
The program check all the vulkan validation function so my vulkan function table must be good. But still the allocation fail.
I'm sorry i don't put a 'minimal' code, but with vulkan, even the minimum is really long. So, as a first test, maybe some of you have an insight of the error?
|
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:
VmaVulkanFunctions vma_vulkan_func{};
vma_vulkan_func.vkAllocateMemory = vkAllocateMemory;
vma_vulkan_func.vkBindBufferMemory = vkBindBufferMemory;
vma_vulkan_func.vkBindImageMemory = vkBindImageMemory;
vma_vulkan_func.vkCreateBuffer = vkCreateBuffer;
vma_vulkan_func.vkCreateImage = vkCreateImage;
vma_vulkan_func.vkDestroyBuffer = vkDestroyBuffer;
vma_vulkan_func.vkDestroyImage = vkDestroyImage;
vma_vulkan_func.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges;
vma_vulkan_func.vkFreeMemory = vkFreeMemory;
vma_vulkan_func.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements;
vma_vulkan_func.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements;
vma_vulkan_func.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties;
vma_vulkan_func.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties;
vma_vulkan_func.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges;
vma_vulkan_func.vkMapMemory = vkMapMemory;
vma_vulkan_func.vkUnmapMemory = vkUnmapMemory;
vma_vulkan_func.vkCmdCopyBuffer = vkCmdCopyBuffer;
And then pass those to the create info:
VmaAllocatorCreateInfo allocator_info{};
...
allocator_info.pVulkanFunctions = &vma_vulkan_func;
|
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...>, std::tuple<T2...>>
{
std::tuple<T1...> t1;
std::tuple<T2...> t2;
Foo(const std::tuple<T1...>& x, const std::tuple<T2...>& y) : t1(x), t2(y)
{
}
};
}
t.cpp
#include "t.h"
int main()
{
using namespace example;
using T1 = std::tuple<int>;
example::Foo f(T1{}, T1{});
return 0;
}
When I try to compile the code above, the compiler gives me the following error:
error: no viable constructor or deduction guide for deduction of template arguments of 'Foo'
example::Foo f(T1{}, T1{});
After playing around a bit, I found out I can make the code work by adding a user defined deduction guide as follows
t.h (works)
namespace example
{
template<typename ... T>
struct Foo;
template<typename ... T1, typename ... T2>
struct Foo<std::tuple<T1...>, std::tuple<T2...>>
{
std::tuple<T1...> t1;
std::tuple<T2...> t2;
Foo(const std::tuple<T1...>& x, const std::tuple<T2...>& y) : t1(x), t2(y)
{
}
};
// After adding this deduction guide, things work
template<typename T1, typename T2>
Foo(const T1& t1, const T2& out) -> Foo<T1, T2>;
}
The Question
My question is twofold. First, why does the compiler need a deduction guide in this case in the first place, and second, how does it work? I'm still learning the newer language features of C++ 20/23 and I'm using clang++ compiler.
Thanks for reading!
|
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 to figure out what the template arguments are. These arguments are applied to the template, which is when specialization happens.
|
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], [over.match.copy], [over.match.conv]); the
program is ill-formed if the corresponding non-reference
copy-initialization would be ill-formed. The result of the call to the
conversion function, as described for the non-reference
copy-initialization, is then used to direct-initialize the reference.
For this direct-initialization, user-defined conversions are not considered.
How, during direct initialization of a reference, user-defined conversions are not considered?
If possible, support the answer with an example in which this rule is applied.
|
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 trying to initialize) would be bound to that reference. Simple, right? There is no question of how such binding is to occur. The reference simply becomes an alias for that temporary object and we are done.
When CWG1604 was resolved just prior to the publication of C++14, the wording was changed so that, instead of this paragraph requiring the copy-initialization of a temporary of type "cv1 T1", we instead do the following:
Determine the user-defined conversion function f that would be used for a hypothetical copy-initialization of a cv1 T1 object from the initializer expression;
Call the function f on the initializer expression. Denote the result of this by x;
Finally, direct-initialize our reference (call it r) from r.
Because x might not be of type cv1 T1, a second run through the reference initialization algorithm is required in order to determine how to direct-initialize r from x. The old wording didn't require a second run. The drafters may have been concerned that there would be an edge case where the new wording would require consideration of user-defined conversions in the second run. But I think we can prove that there are no such cases.
We can consider all possible ways in which the copy-initialization of a hypothetical cv1 T1 object could be done by consulting [dcl.init.general]/17, which governs copy-initializations:
p17.6.1 would not be applicable because if T1 and T2 are identical, then we would not be coming from [dcl.init.ref]/5.4.1 in the first place.
p17.6.2 would not be applicable because if T1 is a base class of T2, then we would not be coming from [dcl.init.ref]/5.4.1 in the first place.
If p17.6.3 applies, then f might be selected from the converting constructors of T2 (see [over.match.copy]/1.1). In this case the second run will be trivial: r is bound directly to x.
If p17.6.3 applies and a conversion function of T2 (possibly inherited) is selected then, as specified by [over.match.copy]/1.2, f must return a type cv3 T3 such that T3 is derived from T1. This implies that T1 is reference-related to T3, and on the second run, due to T1 being reference-related to T3, we never reach any of the clauses telling us to consider user-defined conversions. So even without the bolded sentence, user-defined conversions would be irrelevant.
Otherwise, p17.6.4 applies; T1 is a non-class type, and f is a conversion function of T2 (possibly inherited). As specified in [over.match.conv]/1.1, f must yield a type (i.e., x must be of a type) that is convertible to T1 by a standard conversion sequence. A standard conversion sequence can never convert a class type to a non-class type, so in this case x is of a non-class type. Since T1 is of non-class type and x is also of non-class type, during the second run, user-defined conversions will be irrelevant even without the bolded sentence.
The remaining cases in p17.6 deal with cases where T1 and T2 are both of non-class type, so we would not reach them if we are coming from [dcl.init.ref]/5.4.1.
Note that all references above are to the C++20 standard.
I suspect that the resolution to this issue might have been drafted in a hurry since it was not fixed until after the committee draft had been sent out and it appears that the Canadian NB asked the committee to fix it. The drafters might have decided to just insert the clause about not using user-defined conversions rather than doing an in-depth study to determine whether it is needed. In addition, it seems "cleaner" to avoid even conceptual recursion (i.e. instead of re-running the reference initialization algorithm with different inputs on which the logic of the algorithm guarantees that a further recursive call won't occur, we run a more limited algorithm).
|
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 is expected without any preconditions.
Tested on Windows 11 with a simple Win32 program, generated by Visual Studio. Just added to the message loop "case WM_POWERBROADCAST:", which sets some static variable. After waking up from sleep, the variable is untouched.
You can verify with Spy++: there are only multiple WM_DEVICECHANGE messages, plus 0x02C8 and 0x02C9 messages, and repainting messages.
The workaround is to constantly poll the system with, for example, GetTickCount64(), and detect periods of inaction. Of course, better to avoid polling.
If you know something about it, please let me know what I am missing!
|
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 operator << matches these operands.
Array.cpp(16,15) operand types are std::ostream << Pokemon
I then tried to overload the << operator as I've seen other people ask on here, but I'm not getting the output I want. When I compile the program as-is, nothing prints.
Can someone explain what I can do to get the desired output?
Cyndaquill is a fire type at level 5
Also, can someone explain, or point me in the direction of someone who can explain, operator overloading in an easy non-verbose way? A lot of what I've seen on StackOverflow has been overly verbose and confusing. Maybe it's because I'm new to C++, but still.
Array.cpp
#include <iostream>
#include "Array_Header.hpp"
int main() {
Pokemon pokeDex[15];
Pokemon Cyndaquill = Pokemon("Cyndaquill", 5, "Fire");
Pokemon Totodile = Pokemon("Totodile", 5, "Water");
Pokemon Chikorita = Pokemon("Chikorita", 5, "Grass");
pokeDex[0] = Cyndaquill;
pokeDex[1] = Totodile;
pokeDex[2] = Chikorita;
std::cout << pokeDex[0];
std::cout << pokeDex[1];
std::cout << pokeDex[2];
std::cout << pokeDex[3];
}
Array_Header.hpp
#include <string>
class Pokemon {
public:
//variable declarations
std::string name;
int level;
std::string type;
//Constructor for the DVD class
Pokemon(std::string name, int level, std::string type);
Pokemon() = default;
//toString function declaration
std::string toString();
friend std::ostream& operator<<(std::ostream& os, const Pokemon& obj)
{
return os;
};
};
Array_Header.cpp
#include "Array_Header.hpp"
//Constructor Definition
Pokemon::Pokemon(std::string name, int level, std::string type){
this->type = type;
this->level = level;
this->name = name;
};
//toString function definition
std::string Pokemon::toString(){
return this->name + " is a " + this->type + " type at level " + std::to_string(level) + "\n";
};
|
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();
return os;
};
|
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. For the following snippet:
#include <concepts>
#include <utility>
template <typename PolicyType, typename T, typename... Ts>
concept concept_policy = requires(Ts&&... args)
{
{ PolicyType::template Create<T>(args...) } -> std::same_as<T*>;
};
struct basic_policy
{
template <typename T, typename... Ts>
static T* Create(Ts&&... args)
{
return new T { std::forward<Ts>(args)... };
}
};
struct type_a
{
int m_val;
};
template <concept_policy<int> TPolicy = basic_policy>
static void DoSomething()
{
//works on msvc, msvc needs the "template" for no args, but not with?
{
type_a* type1 = TPolicy::Create<type_a>(5); //why is this fine without template?
type_a* type2 = TPolicy::template Create<type_a>(); //why does this require template if the above doesn't?
}
// //clang requires both to have "template"
// {
// type_a* type1 = TPolicy::template Create<type_a>(5);
// type_a* type2 = TPolicy::template Create<type_a>();
// }
}
int main()
{
DoSomething();
{
//both versions compile fine without "template"
basic_policy policy;
type_a* type1 = basic_policy::Create<type_a>(5);
type_a* type2 = basic_policy::Create<type_a>();
}
return 0;
}
Why do msvc and clang produce different outputs here? Msvc is fine having the "template" omitted for the call with arguments, but not without
Using a similar policy design, is there any way around prefixing the Create with "template"? Ideally I'd like to be able to call TPolicy::Create<type>(...);
|
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, not the beginning of a template argument list. If you mean < as a template argument list, then you must prefix m with the keyword template.
This behaviour is specified in [temp.names]/3. A < that doesn't satisfy any of the conditions listed must be interpreted to mean the less-than operator; the compiler cannot use contextual information to determine that it means the beginning of a template argument list.
As for why MSVC sometimes fails to diagnose the violation, I am not sure.
There is no way to make TPolicy::Create<type>(...); just work without the template keyword. If you really hate writing template, you have to restructure your code so that Create is a non-member, sort of like std::get in the standard library (which would have to be invoked in the form .template get<i>() if it were a class member and the object expression were of dependent type). I guess in this case, Create could be a class template that takes the policy class as one of its template arguments, and the type you want to create as another. I have been told that people often do make their templates into non-members for this exact reason (to avoid having to write template). I think that's a big mistake. It's better to write template than to choose a less natural design.
|
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. I know that everything works the way it's supposed to on its own - the member function returns the expected values when I use it on normal objects, and the other function returns the objects that it's supposed to - but for some reason I don't seem to get anything at all when I use them this way:
functionReturningMyObject(parameters).memberFunction(other parameters);
Is there no way to get a method to act directly on an object that is the output of another function in this way? Or does my problem lie elsewhere?
EDIT: here is my attempt at a "minimal reproducible example," as requested:
Main.cpp
#include <iostream>
#include <string>
#include "mre.hpp"
//Here are some objects
Class first (1, 'A');
Class second (1, 'B');
Class third (2, 'A');
Class fourth (2, 'D');
//Here is the function returning objects in the class
Class FindMatchingObject(int matchNumber, char matchLetter) {
if ((first.getNumber()==matchNumber)&&(first.getLetter()==matchLetter)) {
return first;
}
else if ((second.getNumber()==matchNumber)&&(second.getLetter()==matchLetter)) {
return second;
}
else if ((third.getNumber()==matchNumber)&&(third.getLetter()==matchLetter)) {
return third;
}
else if ((fourth.getNumber()==matchNumber)&&(fourth.getLetter()==matchLetter)) {
return fourth;
}
}
int main() {
//User puts in a string consisting of: first, the old number-letter pair to identify the object they'd like to change, then second, the new number-letter pair that they'd like to change it to. In this case, I put in '1B8H' to pick 'second' and change its values to 8 and H.
std::string userInput;
std::cin >> userInput;
int oldUserNumber = userInput[0] - 48;
char oldUserLetter = userInput[1];
int newUserNumber = userInput[2] - 48;
char newUserLetter = userInput[3];
//Here we see that, indeed, 'second' is being identified by the function.
std::cout << FindMatchingObject(oldUserNumber, oldUserLetter).getNumber() << FindMatchingObject(oldUserNumber, oldUserLetter).getLetter() << "\n";
// Here we see that, indeed, the change() method can take an object and set new values for it.
third.change(7, 'G');
std::cout << third.getNumber() << third.getLetter() << "\n";
// But here, after trying to use change() on 'second' directly through the FindMatchingObject() function, the values of the object remain unchanged afterwards.
FindMatchingObject(oldUserNumber, oldUserLetter).change(newUserNumber, newUserLetter);
std::cout << second.getNumber() << second.getLetter() << "\n";
}
mre.hpp
#include <iostream>
#include <string>
class Class {
char letter;
int number;
public:
Class(int number0, char letter0);
void change(int newNumber, char newLetter);
int getNumber();
char getLetter();
};
mre.cpp
#include <iostream>
#include <string>
#include "mre.hpp"
Class::Class(int number0, char letter0) {
number=number0;
letter=letter0;
}
void Class::change(int newNumber, char newLetter) {
number=newNumber;
letter=newLetter;
}
int Class::getNumber() {
return number;
}
char Class::getLetter() {
return letter;
}
Also, I know it's kind of gross having all of that stuff above the main() function, but for some reason I got compiling errors until I put them there.
|
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 reference or pointer instead.
However, do note that your function has undefined behavior if no matching object is found, as no return gets executed in that case. Your compiler should be warning you about that. You would need to either return a default object, or throw an exception, or return nullptr if you change the function to return a Class* pointer.
|
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){}
// Member function
void display()
{
cout<<"This function is inside class foo"<<endl;
}
};
// Non-member function
void display()
{
cout<<"Non-member function called."<<endl;
}
int main()
{
foo obj;
obj.display();
display(); // Why does this not call the class member function,
// even though it is public ?
return 0;
}
Kinda new with the language.
|
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. For instance, obj.num is an invalid access of the field num of the object obj in your example.
However, since your question is "can the member functions be ONLY accessed by the objects of same class", to that I answer, "not necessarily".
For example, any class inherits from the class (like the class "foo" in your example) can access public/protected member functions as well. So if we do
class bar : foo {};
bar child_obj;
Then you could access the display() function by child_obj.display();
The other part of question consists in "why does the "display()" not call the member function rather it calls the non member function".
To this, it is because the calling of non-member function "display()" resolves the scope to be the global scope, rather than the scope of the member-function. Whereas, obj.display() resolves the scope to be the public member functions of the class foo.
|
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;
int height;
};
// CONSTRUCTOR
AVLTree(){
Node::parent = NULL; // Access struct attributes here
}
|
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, if your AVLTree template has a member
Node n;
then the AVLTree constructor can set this member:
n.parent=nullptr;
However, that's not even the best way to do this. You will discover that the best way to avoid bugs in C++ code is to make it logically impossible for them to happen. Right now it is possible to forget to initialize Node's members, and cause bugs because of that.
So, to fix that, have Node itself provide default values for its members, with its own constructor.
But it's not even necessary to do that, with modern C++, just define the default values for the attributes, or class members:
struct Node
{
Node *parent=nullptr;
Node *right=nullptr;
Node *left=nullptr;
int height=0;
};
Node n;
Now, nothing needs to be done in AVLTree's constructor, and you automatically avoid all bugs due to uninitialized class members.
|
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("5555555555");
Something like this:
int x = num_convert("55");
long y = num_convert("5555555555");
Is there any standard functionality for what I am trying to do?
|
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 function to deduce the returned type with the unused parameter:
#include <string>
template<typename T>
T num_convert(const char* s, const T&) {
return static_cast<T>(std::stoll(s));
}
int main() {
int x = num_convert("55", x);
long y = num_convert("5555555555", y);
}
|
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 ...Args>
std::array<T, N> create_array(Args&&... args)
{
return { T(args...), T(args...), .... };
}
For example, this is necessary when T has members that are (smart) pointers and you want these pointers to reference unique objects.
|
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<decltype(gen(std::size_t{}))>, N>
{
return { {(gen(I))...} };
}(std::make_integer_sequence<std::size_t, N>{});
}
https://godbolt.org/z/5qGbYWjEh
|
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 what does the latter mean? I have never seen such C++ syntax before. Could anyony explain it? Thanks in advance.
|
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 valid for the primary template.
Basically it replaces the definition of the template for the specific specialization determined by the template-id.
__nv_tex_rmnf_ret<char> is now a class containing a typedef for type, but all other specializations __nv_tex_rmnf_ret<T> where T is not char are completely empty classes.
|
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);
return wintitle;
}
LPCTSTR wintitle;
wintitle = WinGetTitle(hWnd);
|
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 call. That's either a pointer into a buffer with static storage duration, or a heap allocation. Neither is particularly useful (the former needs to be fixed size, and the latter puts the burden of releasing the memory on the caller, which usually doesn't know how to).
It is far more practical to return an object that manages its memory automatically. Using a std::wstring is the canonical solution. You can instantiate an object, fill it with contents, and then return it to the caller:
std::wstring WinGetTitle(HWND hWnd)
{
std::wstring wintitle;
auto const len = ::GetWindowTextLengthW(hWnd);
if (len > 0) {
wintitle.resize(static_cast<size_t>(len));
GetWindowTextW(hWnd, wintitle.data(), len + 1);
}
return wintitle;
}
If you need to get an LPCWSTR pointer to pass it into other API calls, you can use std::wstring's c_str() member.
This requires C++17 to return a pointer to non-const from data(). Also note that I omitted using generic-text mappings. Those aren't useful, unless you're targeting Win9x (which has been out of support for a while now).
|
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()
{
while(!x.load(std::memory_order_seq_cst)); // 3
if(y.load(std::memory_order_seq_cst)) // 4
++z;
}
void read_y_then_x()
{
while(!y.load(std::memory_order_seq_cst)); // 5
if(x.load(std::memory_order_seq_cst)) // 6
++z;
}
int main() {
x=false;
y=false;
z=0;
std::thread a(write_x);
std::thread b(write_y);
std::thread c(read_x_then_y);
std::thread d(read_y_then_x);
a.join();
b.join();
c.join();
d.join();
assert(z.load()!=0);
}
In the book C++ Concurrency in Action, the author gives this example when talking about suquential consistency, and says assert can never fire, because
either [1] or [2] must happen first...and if one thread sees x==true
and then subsequently sees y==false, this implies that the store to
x occurs before the store to y in this total order.
I understant there is a global total order with all sequentially consistent atomic operations, and if one thread sees x == true, that means operation 1 synchronozies with operation 3, and also happens before 3, but my question is if that thread subsequently sees y == false, why it implies 1 happens before 2? is it possible that operation 2 happens before 1 but operation 4 doesn't see that value change?
|
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 the total order of sequentially-consistent operations.
Suppose we write X < Y to mean that operation X occurs before operation Y in that total order. You consider the case 2 < 1. In order for 4 to observe the value before the store we also need 4 < 2. There is also a condition that 3 observes the stored value, otherwise 4 is never reached, so also 1 < 3. Lastly we have that 3 is sequenced-before 4 and the total order must be consistent with that, so also 3 < 4.
All in all:
2 < 1
4 < 2
1 < 3
3 < 4
If you now try to create a total order of 1, 2, 3, 4 satisfying these conditions, you will see that it can't work. For a proof see that 2 < 1 and 1 < 3 imply 2 < 3, which together with 3 < 4 implies 2 < 4. That contradicts 4 < 2.
There is no total order satisfying the conditions and therefore this is not a possible outcome. 4 must be seeing the value after the store which is in fact what the chain I used above deduced as 4 < 2. (If you check carefully replacing the condition 4 < 2 with 2 < 4 in the above does not yield any other contradictions and so you can also find a total order actually satisfying them all.)
|
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
return fn(std::get<I>(tup));
}
template<size_t index, typename Func, typename... Args>
auto transform(std::tuple<Args...> tup, Func fn) {
return [&]<std::size_t... I>(std::index_sequence<I...>) {
return std::tuple{transform_helper<index, I>(tup, fn)... };
}(std::index_sequence_for<Args...>{});
}
Demo
|
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... Args>
class Callback
{
public:
Func dFunc;
etl::delegate<void(Func v, int& ret )> dLambda;
vl::Func<void(Func func, int& ret)> dLambda1;
Callback(Func func, Args&...args) :
dFunc(func),
dLambda([&args...](Func v, int& ret) { ret = v(args...); }),
dLambda1([&args...](Func v, int& ret) { ret = v(args...); })
{}
void run(int& ret)
{
dLambda(dFunc, ret );
//auto test = dLambda;
//CHECK_EQUAL(true, is_stateless<decltype(test)>::value);
}
void run1(int & ret)
{
dLambda1(dFunc, ret);
//auto test1 = dLambda1;
//CHECK_EQUAL(true, is_stateless<decltype(test1)>::value);
}
};
I tested them both for is_stateless stateless test , both said they are not! (??)
Furthermore the test itself 'fixed' a non working replacement (??)
I would like to know what is added to the ones that do support [&] ? What should I look for?
|
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 linked documentation seems to imply, it is always undefined behavior to pass the constructor of etl::delegate a lambda expression directly as argument, no matter whether it is stateless or not. Because etl::delegate stores a pointer to the passed object, when operator() is called it will try to call a non-static member function on an out-of-lifetime object.
The undefined behavior is just less likely to cause unintended behavior of the compiled program if the lambda is stateless and so the compiled member function called on the invalid pointer doesn't actually have to access/dereference the pointer.
You must store the lambda somewhere outside the etl::delegate.
I am not sure why the author didn't add a lambda-to-function-pointer conversion for non-capturing lambdas and/or disallowed rvalue arguments to the constructor. The way it is written now it is extremely easy to misuse.
vl::Func seems to implement a pattern similar to std::function and does own the passed callable. That also means it uses new to store the callable in dynamic memory, but no matching delete as far as I can tell.
Therefore it is not a static-allocation replacement. It does use dynamic allocation.
(Sorry for my previous assertion that it is leaking the object. I completely misread the code. I don't see any defect in the implementation anymore as far as the superficial look I had at the code.)
It is not possible to implement what std::function does in generality without dynamic allocation. A static allocation replacement for std::function which also owns the callable must have some parameter limiting the maximum size of a callable object it can store or something similar because the callable would need to be embedded directly into the storage of the std::function-replacement object.
From the examples above you can see that problem. Both of them don't have such a parameter. So one of the replacements isn't owning and the other isn't statically allocating, they can't be doing both.
To test whether the lambda is stateless you need to apply is_stateless to the type of the lambda expression, e.g.
auto lambda = [&args...](Func v, int& ret) { ret = v(args...); };
CHECK_EQUAL(true, is_stateless<decltype(lambda)>::value);
You are applying is_stateless to a type that is not a lambda at all.
|
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 properly but I want to see here what the problem is so I can hopefully learn from it and void making the same problem in future
void merge(int arr[], int l, int mid, int r)
{
int n1= mid-l+1;
int n2= r-mid;
int array1[n1];
int array2[n2];
for(int i=0; i<n1; i++)
{
array1[i]=arr[l+i];
}
for(int i=0; i<n2; i++)
{
array2[i]=arr[mid+1+i];
}
int i=0; int j=0; int k=l;
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[j];
j++,k++;
}
}
}
void mergeSort(int arr[], int l, int r)
{
if (l<r)
{
int mid= (l+r)/2;
mergeSort(arr, l, mid);
mergeSort(arr, mid+1, r);
merge(arr, l, mid, r);
}
}
int main()
{
int arr[]={5,4,3,2,1};
mergeSort(arr, 0, 4);
for(int i=0; i<5; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
|
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[j];
j++,k++;
}
}
should be written as three separate loops like this
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[j];
j++,k++;
}
It helps to understand the merge sort algorithm itself. Only then can you write the code for it. Copying without understanding what you are copying doesn't teach you much.
Try executing the algorithm using pen and paper to get a better understanding of it.
I haven't tested the rest of your code there may still be bugs in it.
|
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 project name
project(msv-auth VERSION 0.1)
# add the executable
add_executable(app "${CMAKE_CURRENT_SOURCE_DIR}/src/app.cpp")
# app name
get_target_property(Z_APP_NAME app NAME)
# specify compiler
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# specify C++ compiler flags
set(CMAKE_CXX_FLAGS -pthread)
if(CMAKE_BUILD_TYPE MATCHES Debug)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -Wall)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -o\"${CMAKE_CURRENT_SOURCE_DIR}/target/debug/${Z_APP_NAME}\")
else()
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -O3)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -o\"${CMAKE_CURRENT_SOURCE_DIR}/target/release/${Z_APP_NAME}\")
endif()
#includes
target_include_directories(app INTERFACE "/usr/local/include/oatpp-1.3/oatpp")
#libs
target_link_directories(app INTERFACE "/usr/local/oatpp-1.3.0")
target_link_libraries(app oatpp)
But I can't seem able to fix that error even after I tried multiple times. OK, I though, let's simplify things a bit, and make a completely new CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
# set the project name
project(msv-auth VERSION 0.1)
# add the executable
add_executable(app "${CMAKE_CURRENT_SOURCE_DIR}/src/app.cpp")
# specify compiler
set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
# specify C++ compiler flags
set(CMAKE_CXX_FLAGS -pthread)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -Wall)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -o\"${CMAKE_CURRENT_SOURCE_DIR}/target/debug/app\")
#includes
target_include_directories(app INTERFACE "/usr/local/include/oatpp-1.3/oatpp")
#libs
target_link_directories(app INTERFACE "/usr/local/oatpp-1.3.0")
target_link_libraries(app oatpp)
(There is only 23 lines of code in the 2nd CMakeLists.txt file)
However, running cmake .., it produced this error:
CMake Error at CMakeLists.txt:34:
Parse error. Expected "(", got newline with text "
".
-- Configuring incomplete, errors occurred!
Exactly the same error on the same exact line number! Like, how can there be an error on line 34 if there's only 23 lines on the file?!
Even creating a new folder, renaming every file, or even running a completely different CMakeLists.txt on a completely different folder for a completely different project, produced the same exact error message. Even rebooting the computer did not fix it at all. I've even tried uninstall and installing CMake again, still the same issue.
Anyone ever stumped on this kind of error? How did you fix it?
|
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, that for some reason it was stuck on broken CMakeLists.txt from another test project that I did before and somehow did not look at the CMakeLists.txt of my current directory? Or is it some FreeBSD bug? I don't know TBH.
Edit: for context on why my CMake was 3.23: this is the latest version on PKG for FreeBSD. I wasn't thinking of compiling CMake from source yet.
|
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 "Access Violation" exception.
Here is a part my code:
HRESULT hres;
IWbemClassObject* pclsObj = NULL;
ULONG uReturn = 0;
IEnumWbemClassObject* pEnumerator = NULL;
// pSvc is a IWbemServices object.
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Win32_Processor"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
while (pEnumerator)
{
hres = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if (0 == uReturn)
{
break;
}
VARIANT vtProp;
VariantInit(&vtProp);
///////////////////////////////////
// Accessing properties
// hr = pclsObj->Get(SysAllocString(L"NumberOfCores"), 0, &vtProp, 0, 0);
hr = pclsObj->Get(SysAllocString(L"Name"), 0, &vtProp, 0, 0);
if(FAILED(hr))
{
cout<< "failed"; // it doesn't fail with either property.
return 0;
}
wcout << " Name : " << vtProp.bstrVal << endl; <-this line throws the exception.
///////////////////////////////////
VariantClear(&vtProp);
pclsObj->Release();
}
I read somewhere that you get this error when the (bstrVal) field is either empty or null, but when I checked it was neither.
Any help is much appreciated.
|
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 linked list is 2->2->3.
I tried making a program that removes duplicate elements from a linked list and count the number of occurrence of the duplicate element
output for my program is
Your linked list is 1 2 1 2 1 3 1
Enter a number: 1
Number of occurance is: 4
After deleting repeated elements:
Your linked list is 2 2 1 3 1
I am going to add third case to remove element from the end soon but I need help in this function . Here I am only able to remove one '1' why is this happening please help
struct Node* ptr2= head;
struct Node* ptr3= head->next;
while(ptr3!=NULL)
{
if(ptr3->data==x)
{
ptr2->next=ptr3->next;
}
ptr2=ptr2->next;
ptr3=ptr3->next;
}
cout<<"Number of occurance is: "<<count<<endl;
return head;
whole program is :-
#include<iostream>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
void traversal(struct Node* head)
{
cout<<"Your linked list is ";
struct Node* ptr = head;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->next;
}
}
struct Node* deleterepeated(struct Node* head, int x)
{
int s=0;//number of elements in linked list
struct Node* p = head;
while(p!=NULL)
{
p=p->next;
s++;
}
struct Node* ptr = head;
int count=0;
while(ptr!=NULL)
{
if(ptr->data == x)
{
if(count==0)
{
head=ptr->next;
}
count++;
}
ptr=ptr->next;
}
struct Node* ptr2= head;
struct Node* ptr3= head->next;
while(ptr3!=NULL)
{
if(ptr3->data==x)
{
ptr2->next=ptr3->next;
}
ptr2=ptr2->next;
ptr3=ptr3->next;
}
cout<<"Number of occurance is: "<<count<<endl;
return head;
}
int main()
{
struct Node* head;
struct Node* val1;
struct Node* val2;
struct Node* val3;
struct Node* val4;
struct Node* val5;
struct Node* val6;
head= (struct Node*)malloc(sizeof(struct Node));
val1= (struct Node*)malloc(sizeof(struct Node));
val2= (struct Node*)malloc(sizeof(struct Node));
val3= (struct Node*)malloc(sizeof(struct Node));
val4= (struct Node*)malloc(sizeof(struct Node));
val5= (struct Node*)malloc(sizeof(struct Node));
val6= (struct Node*)malloc(sizeof(struct Node));
head->data=1;
val1->data=2;
val2->data=1;
val3->data=2;
val4->data=1;
val5->data=3;
val6->data=1;
head->next=val1;
val1->next=val2;
val2->next=val3;
val3->next=val4;
val4->next=val5;
val5->next=val6;
val6->next=NULL;
traversal(head);
cout<<endl;
cout<<"Enter a number: ";
int x;
cin>>x;
head=deleterepeated(head,x);
cout<<"After deleting repeated elements: "<<endl;
traversal(head);
return 0;
}
|
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 edit it out here in the new version , this is only the deleterepeated function
struct Node* deleterepeated(struct Node* head, int x)
{
int count = 0;
struct Node* ptr2 = head;
struct Node* ptr3 = ptr2->next;
struct Node* temp;
while (ptr3 != NULL)
{
if (head && head->data == x) // here is the part of deleting the head if it matches
{
temp = head;
head = head->next;
free(temp);
ptr2 = head;
ptr3 = head->next;
}
else if (ptr3 && ptr3->data == x)
{
temp = ptr3;
ptr2->next = ptr3->next;
free(temp); // you have to free memory to avoid memory leak
ptr3 = ptr2->next;
count++;
}
else
{
ptr2 = ptr2->next;
ptr3 = ptr3->next;
}
}
cout << "Number of occurance is: " << count << endl;
return head;
}
picture of the results:
|
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...>>>)
friend auto tag_invoke(tag_t<connect>, This&& that, Receiver&& r)
noexcept(std::is_nothrow_constructible_v<std::tuple<Values...>, member_t<This, std::tuple<Values...>>>)
-> operation<Receiver, Values...> {
return {static_cast<This&&>(that).values_, static_cast<Receiver&&>(r)};
}
from libunifex
|
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
#define template(...) \
template <__VA_ARGS__ UNIFEX_TEMPLATE_SFINAE_AUX_ \
/**/
#endif
which is used to simplify template definitions with the suffix UNIFEX_PP_EXPAND.
|
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 end user.
How would I be able to make it so the user can type 5'9 with the apostrophe, and still have the code understand it and use it?
Essentially what I would need it to understand is that the 5 represents 12*5 (12 inches in a foot) + the 9.
Thank you in advance!
|
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 feet and inches
...
}
else
{
// some kind of error handling
...
}
|
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 of int and struct Example but the compiler says none of the overloads match..?
|
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/container/unordered_map/insert
|
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 save it in a third location.
here is the program and its source code if it helps :
http://modderbase.com/showthread.php?tid=17
it's for renaming uasset files
btw i tried rewriting the whole thing in c# but i don't understand c++ so yeeeeeeah.
also if you anyone know how to write the core part of the program in c# i would appreciate it.
sorry about my English. it's my second language
|
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 process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "UassetRenamer.exe" + " fisrtFilePath " + "SecondFilePath";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
|
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 project usually compiles without error but when adding this small part at the beginning
#include "ggponet.h"
int main()
{
GGPOSession ggpo;
GGPOErrorCode result;
GGPOSessionCallbacks cb;
I get the following error:
error C2079: 'ggpo' uses undefined struct 'GGPOSession'
GGPOSession is the only element causing a problem.
I have tried everything I could find to try to link the .lib properly but nothing seems to work.
I have also linked SFML without problem so I don't understand why this doesn't work.
Looking at the "Build order" output, it seems the compiler doesn't even try to link to find the implementation of the GGPOSession struct which can be found in the lib.
Thanks for reading, any help is welcome!
|
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
if (mp[i].second > 2) {
cout << "WRONG";
x = false;
break;
}
}
how can I do this?
|
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, performing an insertion if such key does not already exist.
(emphasis mine)
Method 1
Since you don't want to use auto, you can explicitly write the type std::pair<int, int> in the range-based for loop as shown below:
//---------vvvvvvvvvvvvvvvvvvvvvvvv--------------------->not using auto here as you want
for (const std::pair<const int, int> &pair_elem: mp) {
cout << pair_elem.second << " " << endl;
if (pair_elem.second > 2) {
cout << "WRONG";
//other code here
}
}
Method 2
Note that you can also use std::find_if instead of a for loop as shown below:
auto iter = std::find_if(mp.begin(), mp.end(), [](const std::pair<int,int>& elem)
{ return elem.second > 2;});
if (iter != mp.end())
std::cout << "Greater found ";
else
{
std::cout<<"Greater not found"<<std::endl;
}
Demo
|
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, then I am trying to read from the file dataset a single row into the memory, but I always get an error:
#001: ../../../src/H5Dio.c line 487 in H5D__read(): src and dest dataspaces have different number of elements selected
Here is my code:
H5File fp(... , H5F_ACC_RDONLY);
DataSet dset = fp.openDataSet("/dataset");
DataSpace dspace = dset.getSpace();
hsize_t rank;
hsize_t dims[2];
rank = dspace.getSimpleExtentDims(dims, NULL);
cout<<"Datasize: " << dims[0] << endl;
// Define the memory dataspace
hsize_t dimsm[1];
dimsm[0] = dims[1];
DataSpace memspace (1, dimsm);
// create a vector the same size as the dataset
vector<vector<float>> data;
data.resize(dims[0]);
for (hsize_t i = 0; i < dims[0]; i++) {
data[i].resize(dims[1]);
}
//cout<<"Vectsize: "<< data.size() <<endl;
// Initialize hyperslabs
hsize_t dataCount[1] = {0,};
hsize_t dataOffset[1] = {0,};
hsize_t memCount[1] = {0,};
hsize_t memOffset[1] = {0,};
for (hsize_t i = 0; i < dims[0]; i++) {
dataOffset[0] = i;
dataCount[0] = dims[1];
memOffset[0] = 0;
memCount[0] = dims[1];
dspace.selectHyperslab(H5S_SELECT_SET, dataCount, dataOffset);
memspace.selectHyperslab(H5S_SELECT_SET, memCount, memOffset);
dset.read(data[i].data(), PredType::IEEE_F32LE, memspace, dspace);
printf("OK %d\n", (int)i);
}
|
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 hsize_t memOffset[1] = {0};
memspace.selectHyperslab(H5S_SELECT_SET, memCount, memOffset);
for (hsize_t i = 0; i < dims[0]; i++) {
dataOffset[0] = i;
dspace.selectHyperslab(H5S_SELECT_SET, dataCount, dataOffset);
dset.read(data[i].data(), PredType::NATIVE_FLOAT, memspace, dspace);
}
Some parts are const and don't need to be changed. I'm not even sure you need to select a hyperslab on the memory dataspace.
Also, I've changed the output datatype to the native float. You should read in the format of the platform, even if you define datasets as IEEE_F32LE for consistency. HDF5 will handle the conversion.
|
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 class in it:
for(??? c:myVector){
c* tmp = new c();
Edit: I just realized, I would have to store the different object-pointers somewhere to access them later, so even then would have to write every single one manually. That might be the reason, why its not possible to archive. I'm still curious if there is a way, so if you know one, enlighten me please.
|
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<class1>(); },
[]()->pbase { return std::make_unique<class2>(); },
[]()->pbase { return std::make_unique<class3>(); } };
Note that the array stores functions (function objects in this case) not types orr classes or anything of the sort. Classes are not objects and cannot be stored.
Note also that all functions return pointers (smart pointers in this case) to a common base class of your objects. You work with the objects via ther virtual functions defined in the base class and overridden in the derived classes.
pbase pb = objectCreation[1]();
pb->doMyStuff(); // virtual func defined in Base
This is one of the ways we deal with the "I don't know the exact type of this thing but I need to work with it anyway" problem. Inheritance, virtual functions, pointers or references. Those are the three pillars of the object-oriented way. There are other ways but I recommend getting up to speed with this one first.
For additional reading, do a web search for "creational design patterns". You should get some links that mention "factories". That's the good stuff.
|
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 read from stdin in my program, but I never get the text.
My stdinlistener is:
void stdin_listener()
{
std::string line;
do {
std::cin >> line;
std::cout << "received: " << line;
} while (!line.empty());
}
when I run ls -l on the process no I get
lrwx------. 1 64 Aug 28 17:49 /proc/PROCNO/fd/0 -> /dev/pts/2
|
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 -> /dev/pts/0
lrwx------. 1 mrsam mrsam 64 Aug 28 18:01 /proc/5777/fd/1 -> /dev/pts/0
lrwx------. 1 mrsam mrsam 64 Aug 28 18:01 /proc/5777/fd/2 -> /dev/pts/0
They are three different file descriptors, but all three of them are read/write, and they are all connected to the same underlying device. They can be read/written interchangeably, although traditionally only 0 is read from, and 1 and 2 are written to, but it doesn't matter. But the process can read and write from any of the three file descriptors. Reading from any of these file descriptors reads from the terminal. Writing to them will write to the terminal.
I would like to read from stdin in my program, but I never get the text.
Because reading/writing to the file descriptors reads or writes from the terminal. The End.
If you want to run a process that reads and writes to its standard input and output, and have both the input and the output redirected to your program you will have to create and set up your own terminal device, then launch the program with that terminal device opened as its program standard input and output. See the pty manual page for more information.
|
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"
cout << examplevector[0] << endl; // prints "one". I was expecting "eight".
}
Is there a way to alter the values within examplevector via examplemap["vector1"]?
|
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<string>> examplemap {{"vector1", examplevector}};
This effectively makes a copy of the examplevector and stores it in the map. Changes to the object in the map have no effect on the original examplevector. Similarly:
string abra="cadabra";
std::vector<std::string> examplevector{"hocuspocus", abra};
// ...
examplevector[1]="abracadabra";
This modifies the object in the vector. abra is still cadabra.
It's possible to store a map or a container of pointers, or perhaps std::reference_wrappers. Then, modify the pointed-to object, or wrapped reference, will modify the underlying object. But that introduces its own kind of complexity, in terms of managing the lifetime of all objects, correctly.
|
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 avoids unnecessary data copying, like this.
defs::string string = "hello"_constexpr_str;
Of course, my string class also supports building from const char_T*
Now here's the problem!
I want to use the constexpr method automatically when my string class is constructed with compile-time constants like string("hell word!") rather than ugly but strong string("hell word!"_constexpr_str)
In other words, I want string("hell word!") to automatically become string("hell word!"_constexpr_str) in compile-time to calculate the information about the constant string and put it in constant state storage, so that all my string class has to do is hold a pointer to constexpr_str_t
//Draft Code
#if defined(__cpp_if_consteval)
#define if_in_consteval if consteval
#else
#define if_in_consteval if constexpr(0)
#endif
constexpr string_t(const constexpr_str_t&str)noexcept;//save a pointer to constexpr_str_t
string_t(const char_T* str)noexcept{
if_in_consteval{
constexpr constexpr_str_t constexpr_str(str);
construct[this](constexpr_str);
}
else{
construct[this](string_view_t(str));
}
}
What do I do to achieve this?
|
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) string literal as argument with overloads taking either constexpr_str_t or const char*. You basically want the const char* overload to only be chosen when the argument is not a constant expression. Otherwise the constexpr_str_t overload should be chosen and constructed at compile-time (i.e. via consteval) so that the extra information can be attached at compile-time.
This cannot work however, because it is impossible to overload on consteval. Whether or not a consteval function is called depends only on the type of the argument. It is not possible to distinguish between constant expression arguments and non-constant expression arguments.
Trying to determine whether a function argument is a constant expression inside a function is also impossible. Functions are compiled individually. They are not compiled twice depending on whether or not the argument is a constant expression.
The only thing possible is to change behavior based on whether the whole expression that the function call is used in is a context requiring a constant expression. That is what if consteval is for. But if you are making a decision based on such a scenario, you don't need
constexpr constexpr_str_t constexpr_str(str);
You can simply do the calculation for the additional properties of the string there as if at runtime and mark the function constexpr. If used in a context requiring a constant expression it will be evaluated at compile-time.
If you want to enforce this even if the call doesn't happen in a context requiring a constant expression, then it is impossible.
You can however write a macro which tests whether an expression is a constant expression and then conditionally calls either a consteval function or a non-consteval function. It is just impossible through a function call.
|
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-gcc -Wall -g2 -gstabs -O0 -fpack-struct -fshort-enums -ffunction-
sections -fdata-sections -std=gnu99 -funsigned-char -funsigned-bitfields
-mmcu=atmega32 -DF_CPU=1000000UL -MMD -MP -MF"DIO.d" -MT"DIO.o" -c -o
"DIO.o" "../DIO.c"
Finished building: ../DIO.c
Building file: ../main.c
Invoking: AVR Compiler
avr-gcc -Wall -g2 -gstabs -O0 -fpack-struct -fshort-enums -ffunction-
sections -fdata-sections -std=gnu99 -funsigned-char -funsigned-bitfields
-mmcu=atmega32 -DF_CPU=1000000UL -MMD -MP -MF"main.d" -MT"main.o" -c -o
"main.o" "../main.c"
Finished building: ../main.c
Building target: Project00 (Dio_Driver).elf
Invoking: AVR C Linker
avr-gcc -Wl,-Map,Project00 (Dio_Driver).map -mmcu=atmega32 -o "Project00
(Dio_Driver).elf" ./DIO.o ./main.o
/usr/bin/sh: -c: line 1: syntax error near unexpected token `(D'
/usr/bin/sh: -c: line 1: `avr-gcc -Wl,-Map,Project00 (Dio_Driver).map -
mmcu=atmega32 -o "Project00 (Dio_Driver).elf" ./DIO.o ./main.o '
make: *** [Project00 (Dio_Driver).elf] Error 258
"make all" terminated with exit code 2. Build might be incomplete.
04:43:38 Build Failed. 1 errors, 0 warnings. (took 592ms)
|
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
│ └── opencv2
│ ├── ...
│ ├── core
│ ├── core.hpp
│ ├── ...
│ └── ...
├── lib
│ ├── cmake
│ │ └── opencv4
│ │ ├── OpenCVConfig.cmake
│ │ └── ...
│ ├── ...
│ ├── libopencv_core.so -> libopencv_core.so.4.2
│ ├── libopencv_core.so.4.2 -> libopencv_core.so.4.2.0
│ ├── libopencv_core.so.4.2.0
│ ├── ...
│ ├── ...
│ ├── opencv4
│ │ └── 3rdparty
│ │ ├── ...
│ │ └── ...
│ ├── python2.7
│ │ └── dist-packages
│ │ └── cv2
│ └── python3.6
│ └── dist-packages
│ └── cv2
└── share
├── licenses
│ └── opencv4
│ ├── ...
│ └── ...
└── opencv4
├── ...
│ └── ...
├── ...
└── ...
I had a similar issue for PCL (Point Cloud Library) in the past and my answer/solution fixed that. So, I tried something similar:
In settings.json, I put:
"C_Cpp.default.includePath": [
"/usr/local/<blah_blah>/include/opencv4/opencv2/**",
"/usr/local/<blah_blah>/include/opencv4/opencv2/core",
"/usr/local/<blah_blah>/include/opencv4/opencv2/core/*",
"/usr/local/<blah_blah>/include/opencv4/opencv2/core/**"
],
and in the c_cpp_properties.json file, I put:
"includePath": [
"${workspaceFolder}/**",
"${default}"
],
However, doing this is not fixing the issue. C++ IntelliSense/autocomplete still does not work for OpenCV C++. So, how to fix this issue?
Sample Code:
Note1:
In cmake, /usr/local/<blah_blah>/include/opencv4 is used under include_directories.
Compilation and execution work fine.
Note2: the following questions/issues are different from mine:
VSCode autocomplete not working for OpenCV installed from source -- for OpenCV Python, not C++
cv2 (opencv-python) intellisense not working -- for OpenCV Python, not C++
|
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",
.
.
],
However, in my code, the headers were included like:
#include <opencv2/core.hpp>
If the opencv2 folder needs to be included in the #include directive, the includePaths should look like this:
"C_Cpp.default.includePath": [
"/usr/local/<blah_blah>/include/opencv4",
.
.
],
So, the following includePaths configuration fixed the issue with IntelliSense/autocompletion for OpenCV:
"C_Cpp.default.includePath": [
"/usr/local/<blah_blah>/include/opencv4",
"/usr/local/<blah_blah>/include/opencv4/**",
],
For a detailed explanation, take a look into the issue (Issue 9900) I created on vscode-cpptools GitHub page, particularly this thread/reply.
Special thanks to vscode-cpptools and vscode-cmake-tools team!
|
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 MyLogger
..
// avoid conflict..
#undef error
#undef trace
#define error(_MESSAGE_, ...) _write(LOG_LEVEL_ERROR, (const char*)__FILE__, (int)__LINE__, (const char*)_MESSAGE_, ##__VA_ARGS__)
#define info(_MESSAGE_, ...) _write(LOG_LEVEL_INFO, (const char*)__FILE__, (int)__LINE__, (const char*)_MESSAGE_, ##__VA_ARGS__)
#define trace(_MESSAGE_, ...) _write(LOG_LEVEL_TRACE, (const char*)__FILE__, (int)__LINE__, (const char*)_MESSAGE_, ##__VA_ARGS__)
..
// main.cpp
using namespace MyLogger;
// using like this
logger.error("- log error");
logger.info("- log info %s", "test 1");
..
In fact, it seems to work well.
However, the problem occurred while using openv.
error and trace seem to conflicted with error and trace in opencv.
error: expected primary-expression before ‘int’
[build] CV_EXPORTS CV_NORETURN void error(int _code, const String& _err, const char* _func, const char* _file, int _line);
So I'm thinking about other methods using inline functions, not macros.
// global.h
..
//void _write(int _level, const char* _file, int _line, const char* _fmt, ...);
static inline void error(/* Is it possible to toss __LINE__ or __FILE__ ? */);
static inline void info(/* .. */);
static inline void trace(/* .. */);
..
// main.cpp
logger::error("- log error");
logger::info("%d %c %f, 1, 'A', '0.1');
Can I know the line or file of the location where the log was output through a method other than a macro?
|
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 subunits. So the line number and the file names will always be same that of those functions where it resides.
Refer: Inline functions vs Preprocessor macros
C++20
As suggested in this useful comment, you may also consider using std::source_location which allows you to avoid the macro trickery via the help of standard library & language features.
|
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 now, but I don't understand why because it seems that myPosition would end up pointing to nothing long before StartWorker completed.
Assuming this isn't safe, is there any solution other than just passing around everything by value or ensuring it's all on the heap?
|
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_;
}
return it->second;
}
private:
std::map<std::string, std::vector<int>> field2values_;
std::vector<int> default_ints_;
};
Context ctx;
std::vector<int> ctx_field2values(const std::string& field) {
return ctx.field2values(field);
}
class Checker {
public:
explicit Checker():
user_field_values_(ctx_field2values),
user_field_values_nc_(ctx_field2values)
{}
void print(){
const auto& values = user_field_values_("age");
std::cout << "size=" << values.size() << std::endl; // unexpected: 18446744073709535740
const auto& values_nc = user_field_values_nc_("age");
std::cout << "size=" << values_nc.size() << std::endl; // expected: 3
}
private:
const std::function<const std::vector<int>&(const std::string&)> user_field_values_;
const std::function<std::vector<int>(const std::string&)> user_field_values_nc_;
};
int main() {
Checker checker;
checker.print();
}
As we all know, const reference to temporary variable will extend the its lifetime. But in the code above, it does not work for user_field_values_ while it works for user_field_values_nc_. I guess this is because the type of user_field_values_ does not match its initialization, namely ctx_field2values. But why is there such a difference? Can anyone explain in principle why this rule (const reference to temporary variable) does not take effect?
Thanks in advance.
|
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. ([class.temporary]/(6.11))
The function call operator of user_field_values_ behaves just like the invoke_f above. It invokes ctx_field2values (which returns a vector<int>), and returns the result as a const vector<int>& -- a dangling reference.
In C++23, std::function will be able to recognize this pattern (by means of std::reference_converts_from_temporary) and reject it. But it requires compiler support, which AFAIK does not exist yet.
|
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.c:183:17: error: implicitly declaring library function 'abs' with type 'int (int)' [-Werror,-Wimplicit-function-declaration]
exact_y = abs(exact_y);
src/bid64_pow.c:183:17: note: include the header <stdlib.h> or explicitly provide a declaration for 'abs'
1 error generated.
but which are easily fixed by adding the suggested #include <stdlib.h> to the offending files (in this case, src/bid64_pow.c).
After fixing the above, I get the following errors,
float128/dpml_exception.c:186:13: error: implicit declaration of function 'raise' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
DPML_SIGNAL(p);
^
float128/dpml_exception.c:135:28: note: expanded from macro 'DPML_SIGNAL'
# define DPML_SIGNAL(p) raise(SIGFPE)
^
1 error generated.
which I'm unable to fix.
Since the library claims to support Mac OSX, I'm a bit surprised that it wouldn't install right off the bat even on my intel laptop without having to edit the source code. Perhaps then I'm missing something else. In any case, please help!
|
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 )
{
case SIGFPE:
printf( "mysig SIGFPE\n");
break;
default:
printf( "mysig other signal\n");
}
return;
}
int main()
{
#define p SIGFPE
signal( p, mysig);
DPML_SIGNAL(p);
return 0;
}
/*
$ gcc raise.c -Wall -o ./a.out
$ ./a.out
mysig SIGFPE
OR
C:> gcc.exe raise.c -Wall -o .\a.out
C:> .\a.out
mysig SIGFPE
C:> ldd.exe a.out
ntdll.dll => /cygdrive/c/Windows/SYSTEM32/ntdll.dll
KERNEL32.DLL => /cygdrive/c/Windows/System32/KERNEL32.DLL
KERNELBASE.dll => /cygdrive/c/Windows/System32/KERNELBASE.dll
cygwin1.dll => /usr/bin/cygwin1.dll
*/
If you need further comments(from others), provide more information.
Example:
Including related header file.
provide type of variable you are using (p)
compilation option you are using to include dependent libraries(static/dynamic)
provide 32/64 bit compilation information and related compiler(C/C++, if C++ provide -std=c++... version)
Try writing sample program for compilation(for you to follow privacy policy of your IT) whether/not to share your code outside. :)
Provide related compilation error/output if any?
|
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: " << value << std::endl;
}
};
int main()
{
std::vector<BaseParameter> paramsVector;
paramsVector.push_back(MyParam(1));
paramsVector.push_back(MyParam(2));
paramsVector.push_back(MyParam(3));
paramsVector.push_back(MyParam(4));
for (BaseParameter& p : paramsVector)
{
p.print();
}
}
The code above is a basic representation of a more complex code I have in a project.
However, this distills the problem to the basic form.
Why do I get the "cannot instantiate abstract class" error?
How to over come this issue so I can use a base class and many different parameter classes and iterate and print all according to the interface?
|
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.push_back(std::make_unique<MyParam>(2));
paramsVector.push_back(std::make_unique<MyParam>(3));
paramsVector.push_back(std::make_unique<MyParam>(4));
for (const auto& p : paramsVector)
{
p->print();
}
}
In addition, don't forget you need a virtual destructor for base class if you are using polymorphism:
virtual ~BaseParameter() = default;
|
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 here?
|
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(&model);
}
I'd imagine that the compiler has all the information required to eliminate the else clause in the bla() function. The only code path that calls the function comes from main, and it takes in const model_t, so it should be able to figure out that that code path is not being used. However:
With GCC 12.2 we see that the second part is linked in.
If I inline the function this goes away though:
What am I missing here? And is there some way I can make the compiler do some smarter work? This happens in both C and C++ with -O3 and -Os.
|
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 discarded:
[See online]
Additionally, you use static or inline keywords to achieve something similar.
|
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 fix it like this, specifying the type info:
int i = 1;
f<int>(&i, NULL);
Ok, it gets compiled.
But isn't it that, c++ compiler could do type deduction for us : so that we can call template functions without specifying all the type information?
Seems NULL/nullptr here is an unusual case for template.
My question: is there a way to go without f<int> in each place, just f, when there's NULL/nullptr?
Thanks.
|
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 use std::type_identity to establish a non-deduced context:
#include <type_traits>
template<typename T>
void f(const T* t1, const std::type_identity_t<T>* t2) {}
int main() {
const int* x;
f(x,nullptr); // calls f<int>
}
The second parameter will then not be used to deduce T. Whether this is really what you want depends on details of f. Before C++20, the trait is rather simple to write yourself (see possible implementation).
|
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 messages using a QoS of 0.
However, when publishing with a QoS of 1 or 2, I get a runtime error:
MQTT error [-9]: Invalid QoS value
When I try publishing with a QoS less than 0 or greater than 2, I get this instead:
MQTT error [-9]: Bad QoS
I have compiled the same code in the RPi itself and the code runs without any issues.
I'm not completely sure what is happening, but I tried checking why I'm getting the same reason code but different error messages. It appears that the Bad QoS message is written in mqtt/message.h, which can be found in the C++ library, while the Invalid QoS Value can be found in MQTTAsync.c, from the C library.
|
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 line, targetting the link libraries in a more 'specific' way:
target_link_libraries(myproject PahoMqttCpp::paho-mqttpp3 eclipse-paho-mqtt-c::paho-mqtt3as)
I'm actually unsure which one fixed my issues, I'm currently not willing to re-build the toolchain for the armv8 march just to check if the march parameter fixed it, since it takes a little under 30mins.
|
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 earlier, so sadly c++20 fancy features are not allowed here.
Here is a minimal (really minimal) functional example, just to show the problem. Do not expect this sample code doing anything, not even trying to connect.
Godbolt link: https://godbolt.org/z/fj4E8qhxT
#include <map>
#include <boost/asio.hpp>
namespace tcpsocket
{
using boost::asio::ip::tcp;
class client
{
public:
client(boost::asio::executor executor) : socket(executor) {}
private:
tcp::socket socket;
};
}//namespace tcpsocket
int main()
{
boost::asio::io_context ioc;
std::map<int, tcpsocket::client> clients;
//This is working with boost v1.71 but failing with boost v1.69
auto id{125};
auto[it, ok] = clients.emplace(id, ioc.get_executor());
if (ok)
auto& client = it->second;
}
Is it using a boost::asio::io_context& (watch the reference &) a very naive solution solution to solve this problem? I mean, was there any hidden problem with that in a single threaded application?
Well, there is at least one problem, the change from get_io_context() to get_executor() between versions.
Any help with this?
|
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-defined executor type.
I/O objects' constructors and functions that previously took an asio::io_context& now accept either an Executor or a reference to a
concrete ExecutionContext (such as asio::io_context or
asio::thread_pool).
I'd go with the old interface:
Live On Compiler Explorer
#include <map>
#include <boost/asio/version.hpp>
#include <boost/asio.hpp>
#include <iostream>
namespace tcpsocket
{
using boost::asio::ip::tcp;
using boost::asio::io_context;
class client
{
public:
client(io_context& ctx) : socket(ctx) {}
private:
tcp::socket socket;
};
}//namespace tcpsocket
int main()
{
std::cout << BOOST_ASIO_VERSION << " " << BOOST_VERSION << "\n";
boost::asio::io_context ioc;
std::map<int, tcpsocket::client> clients;
//This is working with boost v1.71 but failing with boost v1.69
auto id{125};
auto[it, ok] = clients.emplace(id, ioc);
if (ok)
auto& client = it->second;
}
Prints either
101202 106900
or
101401 107100
|
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() } -> std::same_as<typename T::iterator>;
};
// overload (0), fallback case
template <typename T>
constexpr int foo(const T& o) {
return 0;
}
// overload (1), using the concept
constexpr int foo(const container_type auto& o) {
return 1;
}
// overload (2), using template template parametar
template <typename T, template <typename ...> typename C >
constexpr int foo(const C<T>& o) {
return 2;
}
int main()
{
std::vector<int> a {1,3,3,44,55,5,66,76};
static_assert(foo(a) == 1);
return 0;
}
Compiler used is GCC on https://coliru.stacked-crooked.com, command line is g++ -std=c++20 -O2 -Wall -pedantic -pthread.
I would expect that the overload (1) should be used as the best match, but overload (2) is used instead.
Is this standard conformant behavior?
|
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 will be chosen and constraints are not relevant.
Basically the constraints only matter when comparing function templates that are, except for the constraints, exactly equivalent in terms of their function parameters.
Leaving out the constraint (which is satisfied with the foo(a) call in main) your first overload looks like
constexpr int foo(const auto& o) {
return 1;
}
Now if you compare this to the second overload I think it should be clear that by the usual partial ordering rules for function templates this is less specialized than the second overload. As a consequence the second overload is chosen.
Even if you recast the conditions under which the second overload is valid into a concept Overload2Concept and then use
constexpr int foo(const Overload2Concept auto& o) {
return 2;
}
instead, it won't work, because the constraints of the two overloads are not subsets of one another. You can have a container_type per your definition which is not a specialization of a template and you can have a specialization of a template template <typename ...> class C; which is not a container_type.
So in that case neither would be more specialized than the other, neither by old partial ordering rules nor by new constraint ordering rules, and consequently overload resolution would be ambiguous.
Having concepts/constraints integrated into overload resolution in this way guarantees that adding additional overloads with constraints to pre-C++20 code won't cause any break in the way overloads were chosen beforehand. Were constraints allowed to overrule the old partial ordering in the way you seem to expect, then it would be dangerous to modify any pre-C++20 overload set of functions with constraints.
The following overload would be preferred over overload (2) because it is more specialized per constraints and the unconstrained equivalents identical:
template <typename T, template <typename ...> typename C >
requires container_type<C<T>>
constexpr int foo(const C<T>& o) {
return 1;
}
|
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 callCallbackFromThread(void){
while(clb == NULL);
clb();
}
int someLongTask(void){
volatile unsigned int i = 0;
cout << "Start someLongTask" << endl;
while(i < 100000000)
i++;
cout << "End someLongTask" << endl;
return i;
}
class Base{
public:
Base(){
clb = std::bind(&Base::_methodToCall, this);
cout << "Base-Constructor" << endl;
}
protected:
virtual void methodToCall(void){
cout << "Base methodToCall got called!" << endl;
};
private:
void _methodToCall(void){
methodToCall();
}
};
class Child: public Base{
public:
Child()
: dummy(someLongTask()){
cout << "Child Constructor" << endl;
}
protected:
void methodToCall(void){
cout << "Child methodToCall got called!" << endl;
}
private:
int dummy;
};
int main()
{
thread t(callCallbackFromThread);
Child child;
t.join();
clb();
return 0;
}
When I run this, I sometimes get the result:
Base-Constructor
Start someLongTask
Child methodToCall got called!
End someLongTask
Child Constructor
Child methodToCall got called!
And sometimes this:
Base-ConstructorBase methodToCall got called!
Start someLongTask
End someLongTask
Child Constructor
Child methodToCall got called!
Can someone explain to me why the base-method is called in one case and the child-method in the other?
It surely has something to do with the exact time the thread will be executed. To me, it seems, that the vtable isn't set up properly when the thread calls the callback, but I don't understand why.
|
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 implementation is called, because the object is still a base class object.
The behaviour you are seeing is exactly what you would expect if you called _methodToCall(); inside the base class constructor. In your code, the call happens on another thread while the base class constructor is still running, which comes with a zillion risks, but the thread is actually irrelevant - you could simply write _methodToCall(); or clb(); inside the base class constructor and observe similar behaviour.
|
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");
SOME_MACRO("This is a constant string"); // it detects x is a constant string
int x = 2;
std::string y = std::to_string(x);
SOME_MACRO(y) // it detects y is not a constant string
|
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";
}
int main() {
std::string x = "asdasd";
foo(x);
foo("asdasdasd");
}
Are you asking for a macro for a different reason? Then the answer is the same ;). Don't use a macro.
If you want to detect string literals, thats not possible, as you cannot distinguish them from arrays of const char. Though you can add an overload that matches string literals and arrays of const char:
template <size_t N>
void foo(const char(&s)[N]) {
std::cout << "array of const char\n";
}
Live Demo
|
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 boost::static_visitor<>
{
int operator()(int number) const { return number; }
SstErrors operator()(SstErrors err) const { return err; }
boost::blank operator()(boost::blank) const { return boost::blank{}; }
decltype(auto) operator()(const boost::system::error_code& ec) const { return ec; }
};
Next, I want to use the EventData variant as follows:
EventData data {"Hello world!"};
// ... Some code here ...
// Retrieve data of specific type later.
// Should safely return the underlying value of a type it was initialized with.
std::string& eventDataString = boost::apply_visitor(EventDataVisitor{}, data)
If this is not possible, what is another safe way to retrieve the current value of the EventData? (With or better without enabling RTTI).
|
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 { return number; }
SstErrors operator()(SstErrors err) const { return err; }
boost::blank operator()(boost::blank) const { return boost::blank{}; }
decltype(auto) operator()(const boost::system::error_code& ec) const { return ec; }
};
The usual approach is to pass a callback that is invoked with the active element type. This is exactly what the visitor interface is, but sometimes it might make sense to have a more specific interface.
If this is not possible, what is another safe way to retrieve the current value of the EventData? (With or better without enabling RTTI).
EventData data {"Hello world!"};
std::string& eventDataString = boost::get<std::string>(data);
That's safe. If there's more between the assignment and use, you might use the pointer versions of get<>:
if (auto* p = boost::get<std::string>(&data)) {
// contains a valid std::string
std::string& eventDataString = *p;
}
|
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>
#include <iostream>
#include <vector>
int Sum (std::vector<int>& x){
std::cout << "Enter number: ";
int number;
std::cin >> number; //THIS LINE
if (!std::cin){
throw std::runtime_error (" "); // semicolon was missing before edit
}
if(number >= 0 && number < x.size()){
//doing smthg
}
return 0; // was missing before edit.
}
|
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. Additionally you might need to clear any pending input, but can't say for certain until I understand precisely what input you are giving to your program
Suggest you change the above code to this
while (cin>>u){
x.push_back(u);
}
cin.clear(); // clear error state
cin.ignore(999, '\n'); // clear pending input
|
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 new solution) if necessary. But I need to use one common set of project files to achieve this. Is this possible
Long version:
My old solution of 15 C++ projects directs output to a common folder via one common VS property sheet that they all use. The sheet builds an output path that's a subfolder of the solution using the (SolutionDir), $(Configuration) and $(PlatformToolset) macros
Every C++ project includes this property sheet and is careful not override the "Output Directory" setting. So all the binaries go to a subfolder of the solution like this
\x64\Release\v143
Now I have a larger, .NET 6 solution that includes those 15 projects and others. The solution will have its own output directory and I want all output to go there (i.e. no file-copying build steps). The output path doesn't use the toolset (e.g. "v143") but rather the standard .NET subfolder, like "net6.0-windows". So the new solution's output subfolder will be
\x64\Release\net6.0-windows"
I want to find a way to make all those C++ projects send their output to this new subfolder when they are built as part of this new solution. But my restrictions are:
I need the old solution (of just the 15 projects) to still work and send its output where it used to.
I need to use the same set of .VCXPROJ files between the two solutions (I cannot maintain two sets of 15 project files)
I cannot rely on forcing the developer to define some environment variable before opening the solution.
I can make whatever edits I need to the old projects. But when building with the old solution, the output folder must be the same.
This would be really easy if VS property sheets macros could be "conditional" and would then be the same for all projects in the solution (like $(SolutionDir)). That is, if I could make my property sheet only define that macro (or some other) if it was not already defined. But I don't see a way to do that
Is what I want possible? If so, how?
|
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
Project="$(SolutionDir)outputdir.props"
Condition="exists('$(SolutionDir)outputdir.props')"
Label="Outputdir override" />
</ImportGroup>
|
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 execute the code, because QtWidgetsd.dll is
not found. Reinstalling the program may fix this problem.
problem". I get 3 messages each time with QtWidgetsd.dll, QtCored.dll, QtGuid.dll that are missing.
So I copied the .dll from Qt/5.15.2/msvc2019_64/bin But another error appears:
error2
I have been searching for a long time, reinstalling visual studio, changing the qt5 configuration in VS but nothing changes.
Thanks in advance for any help you can provide
|
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
target_link_libraries(CMAKE_PROJECT_NAME PUBLIC Qt5::Widgets) # Add all used libraries.
|
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] = {2, 3, 4, 1, 12, 34, 11, 9, 22, 5};
print(arr[MAX]);
heapify(arr[MAX]);
print(arr[MAX]);
return 0;
}
void heapify(int arr[]) {
int i = 0;
int l = 2 * i;
int r = 2 * i + 1;
for (i = 0; i < ::MAX; i++) {
if (l <= i/2 && arr[l] > arr[i/2]) {
std::swap(arr[l], arr[i/2]);
}
if (r <= i/2 && arr[r] > arr[i/2]) {
std::swap(arr[r], arr[i/2]);
}
}
}
void print(int arr[]) {
for (int i = 0; i < ::MAX; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
I'm then compiling it using the g++ -c main.cpp and g++ -o main main.cpp commands but I get the following compilation errors:
main.o:main.cpp:(.text+0x66): undefined reference to 'print(int)'
main.o:main.cpp:(.text+0x72): undefined reference to 'heapify(int)'
main.o:main.cpp:(.text+0x7e): undefined reference to 'print(int)'
collect2.exe: error: ld returned 1 exit status
I've looked up the type of error and I get that whenever I am getting a compilation error like undefined reference to main c++ or undefined reference to a c++ function then I have to add definition of that function inside my file. I'm probably in the wrong but it seems to me that I have defined my functions correctly, though the program won't be executed successfully. I've consulted similar questions on StackOverflow about this error and, as far as I've seen, most of them have as a cause a missing .cpp file but I'm just compiling the main.cpp file so I don't really know what to do.
By any chance, can anyone point out what am I getting wrong?
|
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 an int and another accepts an int * (cleverly disguised as int [] -- in case of function parameters (but not elsewhere!) these two things are the same). Both can happily coexist in a single program. This is called "overloading". It is a powerful tool, but you don't need it here. You need one function named heapify, not two.
The compiler complains about the first function, heapify(int), which is never defined.
So fix the first declaration to have the same parameter types as the other one:
void heapify(int []);
The same goes for print.
Now if you try to compile your program, you will get compilation
errors. That's because the calls to heapify and print are wrong.
When you declare an array, you put the size in the square brackets:
int arr[MAX];
When you use and array, you don't put the size in the square brackets. To refer to a single element, you put its index in a square brackets:
int first = arr[0]; // for example.
To refer to the whole array, you don't use square brackets at all:
heapify(arr);
If you write arr[MAX], the following happens.
The compiler treats MAX as just another index, no different from 0 or 1 or l/2 or anything else.
It generates code to access the element with the index MAX, which does not exist. Valid indices are 0 to MAX-1. Accessing arr[MAX] is undefined behaviour. At run time the program would have crashed or produced unexpected results (or sometimes, by pure chance, expected results -- but only when you are looking at it, not when your professor is looking). So it's pretty bad. However...
The type of arr[anything] is int, regardless of whether it exists or not. When you write heapify(arr[MAX]), the compiler generates a call to heapify(int). But this function was never defined. You defined heapify(int[]) which is a totally different function. And of course at the linking stage heapify(int) is not found.
Fix the calls to heapify and print and the program should compile. (I have not tested it so I don't know if it works).
|
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<unsigned int>::max() << '\n';
}
and see what the maximum value that can be stored in an object of the type int. In most cases using different compilers you will get the following output
2147483647
6378624653
4294967295
That is even objects of the type unsigned int can not store such value as 6378624653.
You should declare the variable x as having the type unsigned long long int.
Here is a demonstration program.
#include <cstdio>
int main()
{
unsigned long long int x = 6378624653;
printf( "%#llx\n", x );
}
The program output is
0x17c32168d
|
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 returns size ny-by-nz.
The code:
static const int nx = 10;
static const int ny = 10;
static const int nz = 10;
Eigen::Tensor<double, 3> epsilon((nz+1),ny,nx);
epsilon.setZero();
//slicing test: access first matrix in tensor
std::array<long,3> offset = {0,0,0}; //Starting point
std::array<long,3> extent = {1,ny,nx}; //Finish point
std::array<long,2> shape2 = {(ny),(nx)};
std::cout << epsilon.slice(offset, extent).reshape(shape2) << std::endl;
The answer is a matrix with a 10-by-10 size. How can I change this to extract slice and reshape it into a 11x10 matrix instead (11 rows and 10 columns). I tried changing last line to std::array<long,2> shape2 = {(nz+1),(nx)}; but this returns the error:
Eigen::TensorEvaluator<const Eigen::TensorReshapingOp<NewDimensions, XprType>, Device>::TensorEvaluator(const XprType&, const Device&) [with NewDimensions = const std::array<long int, 2>; ArgType = Eigen::TensorSlicingOp<const std::array<long int, 3>, const std::array<long int, 3>, Eigen::Tensor<double, 3> >; Device = Eigen::DefaultDevice; Eigen::TensorEvaluator<const Eigen::TensorReshapingOp<NewDimensions, XprType>, Device>::XprType = Eigen::TensorReshapingOp<const std::array<long int, 2>, Eigen::TensorSlicingOp<const std::array<long int, 3>, const std::array<long int, 3>, Eigen::Tensor<double, 3> > >]: Assertion `internal::array_prod(m_impl.dimensions()) == internal::array_prod(op.dimensions())' failed.
Aborted
How can I change the number of rows in this matrix? Thanks
|
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(const char* str, int n) {
std::string repeat;
std::string s=std::string(str);
for (int i = 0; i < n; i++) {
repeat += s;
}
printf(repeat.c_str()); // this is for testing
printf("\n");
return repeat.c_str(); // It returns the same thing it prints
}
When using gdb, the output of the function is like this: (I added comments)
(gdb) print repeat("-",10)
---------- // prints 10 dashes
$1 = 0x7fffffffd9e0 "----------" // returns 10 dashes
(gdb) print repeat("-",15)
--------------- // prints 15 dashes
$2 = 0x7fffffffd9e0 '-' <repeats 15 times> // returns 15 dashes
(gdb) print repeat("-",16)
---------------- // prints 16 dashes
$3 = 0x5555555712c0 "" // returns nothing
(gdb) print repeat("-=",8)
-=-=-=-=-=-=-=-= // prints 8 "-="s
$4 = 0x5555555712c0 "" // returns nothing
(gdb)
I have no idea what this is about.
PS: this is my first SO post so I'm not used to doing this.
Update
My understanding of C strings was wrong, I still don't fully understand them so I will stick to std::string. Returning const char* was the wrong thing because it returns a pointer to something only to be used once. This is my new code:
std::string repeat(std::string str, int n) {
std::string repeat;
for (int i = 0; i < n; i++) {
repeat += str;
}
return repeat;
}
Thanks for the help!
|
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 "201400L" but that didn't make any difference. How can I get VS to compile C++14?
|
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;
// ...
} else {
return Klass();
{
}
Klass fromString() { ... }
Klass fromInt() { ... }
// ...
}
}
I want to be able to call this like this:
Klass k1 = Utils::Klass::fromObject(obj);
Klass k2 = Utils::Klass::fromString(str);
Problem I have, when I write it this way, is that I get error "Must use 'class' tag to refer to type 'Klass' in this scope".
Error is fixed when I add the keyword class:
namespace Klass
{
class Klass fromObject(Object object)
{
...
} else if (something2) {
class Klass b = Klass::initialise();
return b;
...
But I don't know how to fix this in the else of this function. I cannot write return class Klass();.
Is it even possible to do something like this in C++? What I am trying to do is to group my utility functions according to a type they return.
|
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
{
using the_Klass = ::Klass;
the_Klass fromObject(Object object)
{
return the_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 argument.
Boy and Girl are template class themselves also, so how do I define TT in this code?
template< typename TT >
class Child
{
TT age;
};
template< typename TT >
class Boy< TT > : public Child< TT >
{ ... };
class Girl< TT > : public Child< TT >
{ ... };
template<typename T>
class Parent {
private:
std::vector< T > children;
//public:
// void ProcessChild() {
// }
};
template<> void Parent < Boy< TT > >::ProcessChild( TT age ) { // ??
// implementation for boys
}
template<> void Parent< Girl< TT > >::ProcessChild( TT age, std::string name ) { // ??
// implementation for girls
}
In this context, T would be a Boy or a Girl and TT would be int or double.
I want two member function specializations for ProcessChild, one for Boy and one for Girl. I can't seem to find the proper syntax for my code, also I can't find any other example where inner class is also a template class. Other examples are specializations of primitive types such as int or double.
I am also trying something like this:
template<>
template< class U >
class Parent < Girl< U > >
{
public:
template< class TT >
void ProcessChild( TT age, std::string name )
{
//...
}
};
All the code shown here is not compiling. This is one of the errors I am getting: error: invalid use of incomplete type 'class Parent<Girl<U> >
Extra: my question is an extension from this previous post. I modified the example quite a bit though.
|
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. Then you can partially specialize Parent<Boy<TT>> and Parent<Girl<TT>> and have them both derive from the base class:
template <typename T>
class ParentBase {
protected:
std::vector<T> children;
};
template <typename T>
class Parent;
template <typename TT>
class Parent<Boy<TT>> : ParentBase<Boy<TT>> {
public:
void processChild(TT age) {
// ...
}
};
template <typename TT>
class Parent<Girl<TT>> : ParentBase<Girl<TT>> {
public:
void processChild(TT age, std::string name) {
// ...
}
};
Demo
|
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::update {
void operator()(int& x)
{
++x;
}
};
void base::apply(int& x) { update{}(x); }
struct deriv : public base {
struct update;
void apply(int& x, int& y);
};
struct deriv::update {
void operator()(int& x, int& y)
{
typename base::update{}.operator()(x);
++y;
}
};
void deriv::apply(int& x, int& y) { update{}(x, y); }
int main()
{
base b;
int x = 1;
b.apply(x);
std::cout << x << std::endl;
int y = 2;
deriv d;
d.apply(x, y);
std::cout << x << ' ' << y << std::endl;
return 0;
}
Compiling with gcc and -Wall -Wextra does not issue any warning.
The output of the code is as expected
2
3 3
However, when analyzing the code with cppcheck, with --enable=all, I get the following:
Checking test.cpp ...
test.cpp:25:24: style: Parameter 'x' can be declared with const [constParameter]
void operator()(int& x, int& y)
^
test.cpp:9:1: error: The one definition rule is violated, different classes/structs have the same name 'update' [ctuOneDefinitionRuleViolation]
struct base::update {
^
test.cpp:24:1: note: The one definition rule is violated, different classes/structs have the same name 'update'
struct deriv::update {
^
test.cpp:9:1: note: The one definition rule is violated, different classes/structs have the same name 'update'
struct base::update {
The first reported error (Parameter 'x' can be declared with const) seems clearly a false positive, as clearly I need non-const reference to be able to modify it, and in fact the code obviously does not compile with a const int&.
But what about the second error on ODR violation? Is this a correct diagnose, and if so why cannot I override the definition of update?
|
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 ${HEADER_FILES} ${SOURCE_FILES})
target_include_directories (${ACCIDENT} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
add_subdirectory (test)
and that works fine. Now I am trying to use that library in note part which should be linked with accident. Especially the accident.hpp file should be visible in my IDE without doing things like this
#include "../../accident/include/accident.hpp"
and the code from accident.cpp should also be accessible. My attempts was similar to this one
set (MUSIC_NOTE music_note)
file (GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp")
file (GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.hpp")
add_library (${MUSIC_NOTE} STATIC ${HEADER_FILES} ${SOURCE_FILES})
target_include_directories (${MUSIC_NOTE}
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include"
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/../accident/include"
)
target_link_libraries (${MUSIC_NOTE} accident)
add_subdirectory (test)
unfortunately, it does not work - accident.hpp header is not found. Do you know where I am doing a mistake?
EDIT
In response to @Martin's question, here is my top level CMakeLists.txt
cmake_minimum_required (VERSION 3.5)
set (CMAKE_BUILD_TYPE Debug)
set (PROJECT_NAME scales)
project (${PROJECT_NAME} LANGUAGES CXX)
set (CMAKE_CXX_STANDARD 17)
set (CMAKE_CXX_STANDARD_REQUIRED ON)
set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set (CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set (CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set (CMAKE_MODULE_PATH "${CMAKE_BINARY_DIR}" "${CMAKE_MODULE_PATH}")
set (CMAKE_PREFIX_PATH "${CMAKE_BINARY_DIR}" "${CMAKE_PREFIX_PATH}")
add_subdirectory (src)
add_subdirectory (external)
option (BUILD_TESTS "Build tests" ON)
enable_testing ()
if (BUILD_TESTS)
add_subdirectory (test)
endif ()
# Add google test
include (FetchContent)
FetchContent_Declare (
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.12.1
)
The note directory is in src, and src includes CMakeLists.txt with only one line
add_subdirectory (note)
In this note directory we have the stuff I pasted above Top level CMakeLists.txt in note directory contains
add_subdirectory (accident)
add_subdirectory (note)
EDIT 2
Problem resolved - see Ave Milia comment below. Thanks!
|
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 point modes. The above is both a compiler warning and the behaviour I now experience with ICX, but not a behaviour experienced with the classic compiler (for the same minimal set of compiler flags used).
Minimally reproducible example
#include <iostream>
#include <cmath>
int main()
{
double a = 1.0/0.0;
if (std::isinf(a))
std::cout << "is infinite";
else
std::cout << "is not infinite;";
}
Compiler Flags:
-O3 -Wall -fp-model=fast
ICC 2021.5.0 Output:
is infinite
(also tested on several older versions)
ICX 2022.0.0 Output:
is not infinite
(also tested on 2022.0.1)
Live demo on compiler-explorer:
https://godbolt.org/z/vzeYj1Wa3
By default -fp-model=fast is enabled on both compilers. If I manually specify -fp-model=precise I can recover the behaviour but not the performance.
Does anyone know of a potential solution to both maintain the previous behaviour & performance of the fast floating point model using the next-gen compiler?
|
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 the default is supported. There is no support for -fp-model strict, -fp-speculation=safe, #pragma fenv_access, etc. Implementing support for these is a work-in-progress in the open source community.
Even though it works for the current version of the tested compiler (icx 2022.0.0), there is a discrepancy: either the documentation is outdated (more probable), or this feature is working by accident (less probable).
|
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 myClass){
//....
}
}
class Child : public Parent{
public Child (std::string myString) : Parent (// get a AnotherClass instance by passing in myString and use that instance as input to Parent constructor) {}
}
class AnotherClass{
public AnotherClass(std::string myString){
///
}
}
|
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::Parent), albeit that changes the interface.
If you'd like to be verbose, you might say (again, as in the comments):
class Child : public Parent
{
public Child(std::string myString)
: Parent(AnotherClass(myString)) {}
};
These are for simple cases. However, sometimes you need to solve a more complicated issue before calling Parent's ctor: e.g., you'd like to reuse AnotherClass or do some calculation/verification on it. This is why I wrote the answer: in the generic case, you might need to do some arbitrary complex calculation. You might still do that, with the help of lambdas (or static member functions, or even free functions):
class Child : public Parent
{
public Child(std::string myString)
: Parent([&](){
// here you can write any code
// it'll run _before_ Parent's ctor
AnotherClass ac(myString);
// do any calculation on ac, store it, etc.
return ac;
}()) {}
};
Also, suggest using std::move when you pass the argument (unless, of course, when you need it in another place in the ctor as well).
|
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 the .txt file on a QTableView but for some reasons, the whole file appears under one gigantic column instead of properly parsing all the different headers and put them on the QTableView.
Below the example .txt file I am uploading on the QTableView - specifically the headers:
tax_id Org_name GeneID CurrentID Status Symbol Aliases description other_designations map_location chromosome genomic_nucleotide_accession.version start_position_on_the_genomic_accession end_position_on_the_genomic_accession orientation exon_count OMIM
Below the rows of some exmaple data:
1041930 Methanocella conradii HZ254 11971032 0 live mRNA MTC_RS04550, Mtc_0908 coenzyme-B sulfoethylthiotransferase subunit alpha coenzyme-B sulfoethylthiotransferase subunit alpha NC_017034.1 886220 887887 plus 0
79929 Methanothermobacter marburgensis str. Marburg 9705221 0 live mRNA MTBMA_RS07375, MTBMA_c15120 coenzyme-B sulfoethylthiotransferase subunit alpha coenzyme-B sulfoethylthiotransferase subunit alpha NC_014408.1 1393293 1394954 minus 0
523846 Methanothermus fervidus DSM 2088 9962464 0 live mRNA MFER_RS03735, Mfer_0734 coenzyme-B sulfoethylthiotransferase subunit alpha coenzyme-B sulfoethylthiotransferase subunit alpha NC_014658.1 713917 715581 plus 0
EDIT
Below the Excel file of the same .txt I posted for clarity in the visualization.
this is the expected output on the QTableView after parsing the .txt file and its headers
This is the wrong output that is currently happening which puts everything under a gigantic column.
Currenlty this upload the .txt file into the QTableView.
However it is not divided per header, but it is just a gigantic column and I don't know why despite I split the strings:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
model = new QStandardItemModel(this);
ui->tableView->setModel(model);
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
setWindowTitle("Viewer Example");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_loadTXTBtn_clicked()
{
auto filename = QFileDialog::getOpenFileName(this, "Open", QDir::rootPath(), "txt file (*.txt)");
if(filename.isEmpty()) {
return;
}
QFile file(filename);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QTextStream xin(&file);
int ix = 0;
while (!xin.atEnd()) {
model->setRowCount(ix);
auto line = xin.readLine();
auto values = line.split(" ");
const int colCount = values.size();
model->setColumnCount(colCount);
for(int jx = 0; jx < colCount; ++jx) {
setValueAt(ix, jx, values.at(jx));
}
++ix;
ui->pathLineEdit->setText(filename);
}
file.close();
}
void MainWindow::setValueAt(int ix, int jx, const QString &value)
{
if (!model->item(ix, jx)) {
model->setItem(ix, jx, new QStandardItem(value));
} else {
model->item(ix, jx)->setText(value);
}
}
In doing research on how to solve the problem I found this post useful and also this one. In particular the last post was very useful for understanding how to parse through the headers but I still was not able to properly understand how to extract those and show them into a QTableView.
Please any pointers on how to solve would be great!
|
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_nucleotide_accession.version",
"start_position_on_the_genomic_accession", "end_position_on_the_genomic_accession",
"orientation", "exon_count", "OMIM"};
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
model = new QStandardItemModel(this);
ui->tableView->setModel(model);
model->setHorizontalHeaderLabels(constants::HEADERS);
model->setColumnCount(constants::HEADERS.length());
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::ResizeToContents);
setWindowTitle("Viewer Example");
OpenFile();
}
void MainWindow::OpenFile()
{
auto filename = QFileDialog::getOpenFileName(this, "Open", QDir::rootPath(), "txt file (*.csv)");
if(filename.isEmpty()) {
return;
}
QFile file(filename);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QTextStream xin(&file);
int row = 0;
while (!xin.atEnd()) {
auto line = xin.readLine();
auto values = line.split(";");
const int colCount = model->columnCount();
for(int col = 0; col < colCount; ++col)
{
setValueAt(row, col, values.at(col));
}
row++;
ui->pathLineEdit->setText(filename);
}
file.close();
}
void MainWindow::setValueAt(int ix, int jx, const QString &value)
{
if (!model->item(ix, jx)) {
model->setItem(ix, jx, new QStandardItem(value));
} else {
model->item(ix, jx)->setText(value);
}
}
Your data.csv example file will be like this:
1041930;Methanocella conradii HZ254;11971032;0;live;mRNA;MTC_RS04550, Mtc_0908;coenzyme-B sulfoethylthiotransferase subunit alpha;coenzyme-B sulfoethylthiotransferase subunit alpha;;;NC_017034.1;886220;887887;plus;0;;
79929;Methanothermobacter marburgensis str. Marburg;9705221;0;live;mRNA;MTBMA_RS07375, MTBMA_c15120;coenzyme-B sulfoethylthiotransferase subunit alpha;coenzyme-B sulfoethylthiotransferase subunit alpha;;;NC_014408.1;1393293;1394954;minus;0;;
I don't think there is a clean way to achieve what you want with the way your txt file is formatted.
|
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__ void child(double* A, double* B, int p)
{
int r;
r = blockIdx.x * blockDim.x + threadIdx.x;
B[p + r] += A[r];
}
__global__ void parent(double* A, double* B, double* C)
{
int i, r;
r = blockIdx.x * blockDim.x + threadIdx.x;
child<<<1, 5>>>(A, B, 7 * r);
for (i = 0; i < 5; i++)
C[r] += B[r * 7 + i];
}
int main()
{
parent<<<1, 2>>>(A, B, C);
}
|
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];
}
__global__ void parent(double* A, double* B, double* C)
{
int i, r;
r = blockIdx.x * blockDim.x + threadIdx.x;
for (i = 0; i < 5; i++)
C[r] += B[r * 7 + i];
}
int main()
{
dim3 Grid(1, 1);
dim3 Block(2, 5);
child<<<Grid, Block>>>(A, B);
cudaDeviceSynchronize();
parent<<<1, 2>>>(A, B, 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 course this required a separate ctor.
Everything worked including in constexpr with MSVC. But when checked using gcc and clang I'm getting ambiguous ctors. Seems pretty clear to me when the lists are nested and MSVC operates exactly as expected.
Here's the code:
// Comment out next line for only nested initializer_list ctor
#define INCLUDE_EXTRA_CTOR
#include <memory>
#include <numeric>
#include <initializer_list>
#include <exception>
#include <stdexcept>
#include <concepts>
using std::size_t;
template <typename T>
class Matrix2D {
T* const pv; // pointer to matrix contents
public:
const size_t cols;
const size_t rows;
// default ctor;
Matrix2D() noexcept : pv(nullptr), cols(0), rows(0) {}
// 2D List initialized ctor
Matrix2D(std::initializer_list<std::initializer_list<T>> list) :
pv((list.begin())->size() != 0 ? new T[list.size() * (list.begin())->size()] : nullptr),
cols(pv != nullptr ? (list.begin())->size() : 0),
rows(pv != nullptr ? list.size() : 0)
{
if (pv == nullptr)
return;
for (size_t row = 0; row < list.size(); row++)
{
if (cols != (list.begin() + row)->size())
throw std::runtime_error("number of columns in each row must be the same");
for (size_t col = 0; col < cols; col++)
pv[cols * row + col] = *((list.begin() + row)->begin() + col);
}
}
#ifdef INCLUDE_EXTRA_CTOR
// Row initialized ctor, rows=n, cols=1;
Matrix2D(std::initializer_list<T> list) :
pv(list.size() != 0 ? new T[list.size()] : nullptr),
cols(pv != nullptr ? 1 : 0),
rows(pv != nullptr ? list.size() : 0)
{
if (pv == nullptr)
return;
for (size_t row = 0; row < rows; row++)
{
pv[row] = *(list.begin() + row);
}
}
#endif
// dtor
~Matrix2D() { delete[] pv; }
};
int main()
{
// Tests of various possible null declarations
Matrix2D<int> x1{ }; // default
Matrix2D<int> x2{ {} }; // E0309, nested init list with 1 row, 0 cols, forced to 0 rows, 0 cols
Matrix2D<int> x3{ {},{} }; // E0309, nested init list with 2 rows, 0 cols, forced to 0 rows, 0 cols
// typical declaration
Matrix2D<int> x4{ {1,2},{3,4},{5,6} }; // nested init list with 3 rows, 2 cols
// standard row vector declaration
Matrix2D<int> x5{ {1},{2},{3} }; // E0309, init list with 3 rows, 1 col
#ifdef INCLUDE_EXTRA_CTOR
// row vector declaration
Matrix2D<int> x6{ 1,2,3 }; // init list with 3 rows, 1 col
#endif
}
E0309 is the MSVC intellisense ambiguous ctor error. However, compiles w/o error
Why are gcc and clang deductions ambiguous? Is there a workaround?
Compiler Explorer
|
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
// Row initialized ctor, rows=n, cols=1;
template<class U>
Matrix2D(std::initializer_list<U> list) :
pv(list.size() != 0 ? new T[list.size()] : nullptr),
cols(pv != nullptr ? 1 : 0),
rows(pv != nullptr ? list.size() : 0)
{
fmt::print("1: {}\n", list);
if (pv == nullptr)
return;
for (size_t row = 0; row < rows; row++)
{
pv[row] = *(list.begin() + row);
}
}
#endif
If you want Matrix2D<double> d1{ 1,2,4. } to work, then you can use type_identity_t to establish non-deduced contexts in template argument deduction:
// Row initialized ctor, rows=n, cols=1;
template<class U = T>
Matrix2D(std::initializer_list<std::type_identity_t<U>> list) :
pv(list.size() != 0 ? new T[list.size()] : nullptr),
cols(pv != nullptr ? 1 : 0),
rows(pv != nullptr ? list.size() : 0)
{
Demo
|
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 separate question to be sure.
I know ostrstream has a pcount method, unfortunately, it is deprecated.
|
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::endl;
auto written = stream.tellp() - start;
//...
}
|
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
const char * cNVKeysMetaData = QUOTE(
{
"Area1":[
{
"key":KEY1,
"maxLength":LEN1,
"type":"s",
"default":"Hello"
},
#if defined(TEST)
{
"key":KEY2,
"maxLength":LEN2,
"type":"s",
"default":"invalid"
},
#endif
{
"key":KEY3,
"maxLength":64,
"type":"s",
"default":"invalid"
}
]
}
);
#include <iostream>
int main()
{
std::cout << cNVKeysMetaData << std::endl;
return 0;
}
GCC Output:
{ "Area1":[ { "key":"Key1", "maxLength":32, "type":"s", "default":"Hello" }, { "key":"Key3", "maxLength":64, "type":"s", "default":"invalid" } ] }
MSVC Output:
{ "Area1":[ { "key":"Key1", "maxLength":32, "type":"s", "default":"Hello" }, #if defined(TEST) { "key":"Key2", "maxLength":32, "type":"s", "default":"invalid" }, #endif { "key":"Key3", "maxLength":64, "type":"s", "default":"invalid" } ] }
Note that MSVC does replace the macros KEY1 etc, but does not strip out the #if. GCC does strip out the #if.
|
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_TEST(
{
"key":KEY2,
"maxLength":LEN2,
"type":"s",
"default":"invalid"
},
)
...
)
|
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>
using namespace std;
int main()
{
char or1[99],or2[99],or3[99];
cout << "Enter array: ";
cin.get (or1, 3);
cout << "Enter array: ";
cin.get (or2, 3);
cout << "Enter array: ";
cin.get (or3, 3);
cout << "\n--" << or1 << or2 << or3 << "--\n";
}
Output:
Enter array: dog
Enter array: Enter array:
--dog--
|
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 end-of-line character.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char or1[99],or2[99],or3[99];
cout << "Enter array: ";
cin.get (or1, 99); cin.get(); or1[2] = 0;
cout << "Enter array: ";
cin.get (or2, 99); cin.get(); or2[2] = 0;
cout << "Enter array: ";
cin.get (or3, 99); cin.get(); or3[2] = 0;
cout << "\n--" << or1 << or2 << or3 << "--\n";
}
// Output:
// --DoCaRa--
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.