question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
70,918,614 | 70,918,933 | Sorting a ring buffer class objects | I am trying to make a sorting function for a ring buffer class object, but it gives me the below error and I couldn't remove it:
template placeholder type 'ring' must be followed by a simple declarator-id
argument list for class template "ring" is missing
'arr' was not declared in this scope
(arr) was declared in the parameter of the function but yet it does not recognize it
hopefully someone can explain what is wrong with the sorting function, here is below my code:
#include<iostream>
#include<initializer_list>
template<typename T>
void swap(T& x, T& y) {
T temp;
temp = x;
x = y;
y = temp;
}
template<typename T>
class ring {
public:
class iterator;
public:
ring(std::initializer_list<T>elements) {
sze = elements.size();
value = new T[sze];
for (auto& i : elements) {
add(i);
}
}
T& get(int x) { return value[x]; }
std::size_t size() { return sze; }
void add(T v) {
value[index++] = v;
if (index == sze)
index = 0;
}
iterator begin() { return iterator(0, *this); }
iterator end() { return iterator(sze, *this); }
friend void BubbleSort(ring& arr, std::size_t n);
~ring() { delete[] value; }
private:
int index = 0;
std::size_t sze;
T* value;
};
template<typename T>
class ring<T>::iterator {
public:
iterator(int x, ring& y) :index(x), obj(y) {}
iterator& operator++() { index++; return *this; }
iterator& operator++(int x) { index++; return *this; }
bool operator!=(const iterator& other) { return index != other.index; }
T& operator*() { return obj.get(index); }
private:
int index;
ring& obj;
};
template<typename T>
void BubbleSort(ring& arr, std::size_t n) { // here is the function of the sorting.
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr.value[j] > arr.value[j + 1]) {
swap(arr.value[j], arr.value[j + 1]);
}
}
}
}
| Your friendly compiler showed you already the problem and in which line it happened.
And it gave you 3 error messages telling you exactly what the problem is.
See my compiler output
Your class ring needs a template parameter. So same as in line 49 of the picture.
The below will compile.
#include<iostream>
#include<initializer_list>
template<typename T>
void swap(T& x, T& y) {
T temp;
temp = x;
x = y;
y = temp;
}
template<typename T>
class ring {
public:
class iterator;
public:
ring(std::initializer_list<T>elements) {
sze = elements.size();
value = new T[sze];
for (auto& i : elements) {
add(i);
}
}
T& get(int x) { return value[x]; }
std::size_t size() { return sze; }
void add(T v) {
value[index++] = v;
if (index == sze)
index = 0;
}
iterator begin() { return iterator(0, *this); }
iterator end() { return iterator(sze, *this); }
friend void BubbleSort(ring& arr, std::size_t n);
~ring() { delete[] value; }
private:
int index = 0;
std::size_t sze;
T* value;
};
template<typename T>
class ring<T>::iterator {
public:
iterator(int x, ring& y) :index(x), obj(y) {}
iterator& operator++() { index++; return *this; }
iterator& operator++(int x) { index++; return *this; }
bool operator!=(const iterator& other) { return index != other.index; }
T& operator*() { return obj.get(index); }
private:
int index;
ring& obj;
};
template<typename T>
void BubbleSort(ring<T>& arr, std::size_t n) { // here is the function of the sorting.
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr.value[j] > arr.value[j + 1]) {
swap(arr.value[j], arr.value[j + 1]);
}
}
}
}
I did not check the functionality. Sorting a ringbuffer sounds somehow strange . . .
|
70,918,658 | 70,918,679 | Printing text on screen Unreal Engine C++ | how can i print not debug text (GEngine->AddOnScreenDebugMessage (-1, 5.f, FColor::Red, FString::Printf(TEXT(""));) on screen in unreal engine?
| You'd need to use a widget with text then be able to spawn the widget or always have it open in your level. Create a Widget blueprint and simply add a textbox.
|
70,918,786 | 70,918,928 | Partial specialization tempate c++ | I was exploring the JUCE framework and find this interesting code,
namespace SampleTypeHelpers // Internal classes needed for handling sample type classes
{
template <typename T, bool = std::is_floating_point<T>::value>
struct ElementType
{
using Type = T;
};
template <typename T>
struct ElementType<T, false>
{
using Type = typename T::value_type;
};
}
I've found out reading a little bit that, this is called partial specialization in c++, and I think it's pretty clear, but there is a thing i do not understand, in the first template there is that bool initialized, what is doing?
Thanks to everyone that will be answering!
| Look at this function declaration:
void frob(float f, bool g = true) {
// ...
}
As you might know, you can drop parameter name from declarations:
void frob(float f, bool = true) {
// ...
}
You can also set the default value using an expression. This is equivalent as the previous example:
void frob(float f, bool = std::is_floating_point<float>::value) {
// ...
}
Then, let's add a simple template for the sake of the exercise:
template<typename T>
void frob(T f, bool = std::is_floating_point<T>::value) {
// ...
}
Technically, you could move parameters to be template parameters, if you know them at compile time:
template<typename T, bool = std::is_floating_point<T>::value>
void frob(T f) {
// ...
}
Now it's beginning to look like your own template declaration isn't it?
Now that you understand the syntax, let's see how it's useful with partial specialization.
Imagine you're the compiler and you expand the template instantiation of ElementType for float and std::integral_constant<int, 0>:
template<>
struct ElementType<float, std::is_floating_point<float>::value> { ... };
template<>
struct ElementType<
std::integral_constant<int, 0>,
std::is_floating_point<int>::value
> { ... };
Expands the constants, you get this:
template<>
struct ElementType<float, true> { ... };
template<>
struct ElementType<std::integral_constant<int, 0>, false> { ... };
Now that you expanded this, you see that you have both true and false as the second parameter. You pick the specialization for each:
template<>
struct ElementType<float, true> { using Type = float; };
template<>
struct ElementType<std::integral_constant<int, 0>, false> {
// int
using Type = typename std::integral_constant<int, 0>::value_type;
};
|
70,918,879 | 70,920,090 | How can a vector of integers hold objects if an integer is not a class? | While I was reading C++ primer fifth edition I came across this definition of a vector:
A vector is a collection of objects, all of which have the same type.
Every object in the collection has an associated index, which gives
access to that object. A vector is often referred to as a container
because it “contains” other objects.
If I have a vector of integer values then what class do all these objects belong? Because "int" is not a class as these answers from this link already explain:
Is int (built in data types) a class in c++?
I also came across the concept of "Data Objects" from IBM, are these the objects that the vectors hold in this case? Because I have been reading this concept of "Data object" a lot and it still puzzles me. And even if it is the object that the vectors hold, my question still remains: what class does it belong?
|
If I have a vector of integer values then what class do all these objects belong?
No class at all. The elements of a vector of integers are objects of the integer type. Integer types are fundamental types.
|
70,918,947 | 70,919,387 | Construct n-dimensional boost point | Problem:
boost/geometry/geometries/point.hpp point template does not provide a way to construct an n-dimensional point type with non-zero values.
For example:
#include <boost/geometry/geometries/point.hpp>
namespace bg = boost::geometry;
...
typedef bg::model::point<double,4,bg::cs::cartesian> point;
auto nDimPoint1 = point(); // creates a point with 4 values each 0
auto nDimPoint2 = point(1,2,3,4); // !!!compiler error!!! since point's template does not provide a strategy past 3 dimensions.
// workaround, but must be hard-coded
nDimPoint1.set<0>(1);
nDimPoint1.set<1>(2);
nDimPoint1.set<2>(3);
nDimPoint1.set<3>(4);
What I've tried:
After reading through boost's documentation I was not able to find any examples with n-dimensional points, though it is possible I missed them.
I did encounter creating custom point classes and registering them, but the built in point class accomplishes exactly what I want. Unfortunately I can't solve this by inheriting from the base point since the point representation is a private variable.
Point's template contains a private array variable, m_values, by creating a new constructor which takes a vector and copying the vector into m_values I was able to fix the issue.
I'm also pretty new to C++'s templates, since I usually use C and python. Is it possible to extend the Point template outside the Point.hpp file to include the n-dimensional constructor I want? Or is there a better way of building n-dimensional points in boost such as cast from vector?
Ideally (imho) boost would provide a generic copy constructor which accepts std::vector and copies each value into its internal array.
Related questions:
In this question Defining a dimensional point in Boost.Geometry, the author is attempting to utilize point for rtree (I am also attempting to do this), however the accepted answer claims this is not possible and a second solution https://stackoverflow.com/a/62777496/10448495, claims to solve the issue, but I don't see how it can work.
| You are right. The model::point class template doesn't afford direct/aggregate initialization and it's not possible to add that (m_values is private e.g., but also there is optional access-tracking debug metadata that would get out of sync).
Note the class is documented
\details Defines a neutral point class, fulfilling the Point Concept.
Library users can use this point class, or use their own point classes.
This point class is used in most of the samples and tests of Boost.Geometry
This point class is used occasionally within the library, where a temporary
point class is necessary.
And:
\tparam DimensionCount number of coordinates, usually 2 or 3
So, you can - and probably should - use your own type. The simplest thing would be to use an array directly (so, just the m_values member data really). There's very little magic about that:
Live On Compiler Explorer
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/adapted/std_array.hpp>
#include <fmt/ranges.h>
namespace bg = boost::geometry;
BOOST_GEOMETRY_REGISTER_STD_ARRAY_CS(bg::cs::cartesian)
using point = std::array<double, 4>;
int main() {
auto a = point(); // creates a point with 4 values each 0
auto b = point{1, 2, 3, 4};
// generic Boost code will still work:
bg::set<0>(a, 10);
bg::set<1>(a, 20);
bg::set<2>(a, 30);
bg::set<3>(a, 40);
fmt::print("default:{}, a:{}, b:{}\n", point{}, a, b);
}
Prints
default:[0, 0, 0, 0], a:[10, 20, 30, 40], b:[1, 2, 3, 4]
|
70,919,228 | 70,919,291 | Do you always have to declare a default constructor and destructor for unions containing members with user-defined default constructor? | This class containing a union:
struct foo
{
union
{
std::vector<int> vec;
int i;
};
};
cannot be instantiated. If I try, the compiler throws an error saying 'foo::foo(void)': attempting to reference a deleted function. To get it to work, I have to add an empty constructor and destructor to the union like so:
struct foo
{
union U
{
U() {}
~U() {}
std::vector<int> vec;
int i;
} u_;
};
It can then be instantiated successfully. Is this always the case? Why? It seems silly to write an empty constructor and destructor for every union that contains member with user-defined default constructors.
|
It seems silly to write an empty constructor and destructor for ...
Not only silly, but actually wrong.
Why [does the compiler doesn't generate one and you need to]?
A union doesn't know which of its members is active. As such if at least one of its members has a non-trivial special method the union can't generate that special method because it doesn't know on which member to call that special method.
And now we come to your case. You do need to write a special method, but having it empty achieves nothing. You need to write a special method that correctly delegates to the active member. For instance inside foo you can have a data member (an enum or an index) which tells you which union member is active. And in your union special method you check that index and call the special method on the active member of the union.
Or you can forget about all this and just use the type in the standard library that not only has everything set up for you, but also is type safe: std::variant.
|
70,919,341 | 70,919,406 | Declare reference member variable that you won't have at instantiation | Coming from Java, C++ is breaking my brain.
I need a class to hold a reference to a variable that's defined in the main scope because I need to modify that variable, but I won't be able to instantiate that class until some inner loop, and I also won't have the reference until then. This causes no end of challenges to my Java brain:
I'm used to declaring a variable to establish its scope, well in advance of knowing the actual value that will go in that variable. For example, creating a variable that will hold an object in my main scope like MyClass test; but C++ can't abide a vacuum and will use the default constructor to actually instantiate it right then and there.
Further, given that I want to pass a reference later on to that object (class), if I want the reference to be held as a member variable, it seems that the member variable must be initialized when it's declared. I can't just declare the member variable in my class definition and then use some MyClass::init(int &myreference){} later on to assign the reference when I'll have it in my program flow.
So this makes what I want to do seemingly impossible - pass a reference to a variable to be held as a member variable in the class at any other time than instantiation of that class. [UPDATE, in stack-overflow-rubber-ducking I realized that in this case I CAN actually know those variables ahead of time so can side-step all this mess. But the question I think is still pertinent as I'm sure I'll run into this pattern often]
Do I have no choice but to use pointers for this? Is there some obvious technique that my hours of Google-fu have been unable to unearth?
TLDR; - how to properly use references in class member variables when you can't define them at instantiation / constructor (ie: list initialization)?
|
Declare reference member variable that you won't have at instantiation
All references must be initialised. If you don't have anything to initialise it to, then you cannot have a reference.
The type that you seem to be looking for is a pointer. Like references, pointers are a form of indirection but unlike references, pointers can be default initialised, and they have a null state, and can made to point to an object after their initialisation.
Important note: Unlike Java references, C++ references and pointers do not generally extend the lifetime of the object that they refer to. It's very easy to unknowingly keep referring to an object outside of its lifetime, and attempting to access through such invalid reference will result in undefined behaviour. As such, if you do store a reference or a pointer to an object (that was provided as an argument) in a member, then you should make that absolutely clear to the caller who provides the object, so that they can ensure the correct lifetime. For example, you could name the class as something like reference_wrapper (which incidentally is a class that exists in the standard library).
In order to have semantics similar to Java references, you need to have shared ownership such that each owner extends the lifetime of the referred object. In C++, that can be achieved with a shared pointer (std::shared_ptr).
Note however, that it's generally best to not think in Java, and translate your Java thoughts into C++, but it's better to rather learn to think in C++. Shared ownership is convenient, but it has a cost and you have to consider whether you can afford it. A Java programmer must "unlearn" Java before they can write good C++. You can also subsitatute C++ and Java with most other programming languages and same will apply.
it seems that the member variable must be initialized when it's declared.
Member variables aren't directly initialised when they are declared. If you provide an initialiser in a member declaration, that is a default member initialiser which will be used if you don't provide an initialiser for that member in the member initialiser list of a constructor.
You can initialise a member reference to refer to an object provided as an argument in a (member initialiser list of a) constructor, but indeed not after the class instance has been initialised.
Reference member variables are even more problematic beyond the lifetime challenges that both references and pointers have. Since references cannot be made to point to other objects nor default initialised, such member necessarily makes the class non-"regular" i.e. the class won't behave similar ways as fundamental types do. This makes such classes less intuitive to use.
TL;DR:
Java idioms don't work in C++.
Java references are very different from C++ references.
If you think that you need a reference member, then take a step back and consider another idea. First thing to consider: Instead of referring to an object stored elsewhere, could the object be stored inside the class? Is the class needed in the first place?
|
70,919,881 | 70,919,924 | Pointer being freed was not allocated - destructor | Slowly learning about copy/move constructors, rule of 5 etc. Mixed with not-so-well understanding of usage of pointers/reference, I cannot understand why my destructor throws the error below. I know that it's caused by destructor and destructor only, and after the copy constructor.
untitled(19615,0x104a60580) malloc: *** error for object 0x600000b74000: pointer being freed was not allocated
untitled(19615,0x104a60580) malloc: *** set a breakpoint in malloc_error_break to debug
Code:
#include <string>
using namespace std;
typedef int size_type;
class user{
public:
user():
rank(1),
name("default"){
}
private:
int rank;
string name;
};
class account{
public:
account(size_type max_size):
owners(new user[max_size]),
max_size(max_size){
cout<<"normal constructor"<<endl;
}
account(account& other):
owners(other.owners),
max_size(sizeof(owners)){
cout<<"copy constructor called"<<endl;
}
account(account&& other):
owners(other.owners),
max_size(sizeof(owners)){
cout<<"move constructor called"<<endl;
}
~account(){
if(owners!= NULL) {
delete[] owners;
owners= 0;
}
cout<<"destructor called"<<endl;
}
private:
user* owners;
size_type max_size;
};
int main(){
account f(3);
account n(f);
}
|
I cannot understand why my destructor throws the error below. I know that it's caused by destructor and destructor only
account f(3);
The constructor of this object allocates an array.
account n(f);
The copy constructor that you wrote copies the pointer that points to the dynamic array.
n is destroyed first. Its destructor deletes the array. f is destroyed after that. Its destructor also deletes the same array and the behaviour of the program is undefined, which lead to the output that you observed.
To prevent the allocation from being deleted multiple times, you must enforce a class invariant (a post condition that applies to all member functions) that any non-null owners value must be unique across all instances of the class. To maintain that invariant in the copy constructor (as well as move constructor and copy and move assignment operators), you must not copy the pointer, as you do now. I recommend studying the RAII idiom.
Better solution: Don't use owning bare pointers. Use std::vector<user> and don't have user defined special member functions at all.
P.S. The copy constructor should accept a reference to const.
Also:
if(owners!= NULL) {
delete[] owners;
owners= 0;
}
The check is redundant because it's safe to delete null. The assignment is redundant because the object is about to be destroyed and the member cannot be accessed after that anyway.
|
70,919,957 | 70,920,041 | How can I build two executables that share a main function in CMake? | I have a project that's becoming large enough that I want to switch to from a plain Makefile to CMake. My project contains only one application, but supports two different boards (each board has a set of source files, and some defines specific to the board). The (simplified) project structure currently looks like this:
CMakeLists.txt
src/
├─ board/
│ ├─ board_a/
│ │ ├─ board.c
│ ├─ board_b/
│ │ ├─ board.c
├─ app/
│ ├─ main.c
CMakeLists.txt
I could (and currently have) just put everything in the root CMakeLists.txt file, but I don't want that file to become enormous as the project expands. Essentially, I am wondering how I can create a project which allows me to build an executable for either board where each executable can have a separate set of defines (that are used in both the board.c and main.c files), source files (board.c in this case, while sharing the main.c), and can share compile/linker options (I want to share some common compilation settings between both executables) without having one enormous CMakeLists.txt.
| You already have a src/CMakeLists.txt, so you are part of the way there. Put your overall build settings -- dependencies, C standard version, global compiler flags -- in the top-level CMakeLists.txt. In the subdirectories, put only your CMake commands for the executables, or whatever target makes sense locally.
(As an aside, define "enormous"? I've got top-level CMakeLists here that are anywhere between 200-950 lines, but I've seen 3000-line monstrosities as well)
Personally, from the minimal sketch of the source layout here, I'd do:
src/CMakeLists.txt does an add_subdirectory() command for each board, e.g. add_subdirectory(board/board_a) . If you like, set() a variable to a list of board names and you can iterate over it.
In each board's subdirectory, create a library -- shared, static, or OBJECT -- named after the board, with the sources for that board. For instance add_library(board_a OBJECT board.c)
Back in src/CMakeLists.txt again, for each board, add an executable with the source from app/ and link to the library defined for the board, like
add_executable(exe_board_a app/source.c)
target_link_library(exe_board_a PRIVATE board_a)
If there are special considerations for that executable, set them there as well. Compile flags can be obtained from the library targets (use STATIC then, not OBJECT).
This moves most of the long-lists-of-sources and potentially compile flags to the per-board CMakeLists.txt and turns the intermediate level into a long list of "make this executable".
|
70,920,100 | 70,921,790 | Errant segments in cellular automata encryption algorithm | I've been implementing a paper that is targeting IoT encryption using a 64-bit block cipher via elementary cellular automata. The paper is in the repository/linked in the README.
I am trying to verify that an implementation of this algorithm actually works.
Current state
The first and third segments do not decrypt properly, I believe this is due to rule 153 being used.
P: deadbeefcafebabe
K: f6c78663f3578746
E: ce09ac834be8ba8d
D: df8cbeefcbcbbabe
Things I've verified
The CA works like Wolfram's and the specified rules in the paper
Splitting/concatenating segments works as expected
Errata I've noticed in the paper
There are unspecified CA boundaries (implementation should be correct as I'm getting half the plaintext out)
Selected rule 204 is essentially a NOP
16x4 bit split in decryption should be 4x6
Correct in diagram (figure 3), not in algorithm listing
Decryption needs to invert the even/odd segment check
Question
Does rule 153 actually work for reversing the automata during decryption? Rule 51 is essentially a NOT on the previous epoch, so I would expect rule 153's inverse to be in use during decryption, but doesn't appear to be reversible.
If anyone could take a look and provide feedback on where I went wrong I'd greatly appreciate it. I've already mailed the author and have yet to receive a response.
Code
https://github.com/optimisticninja/caencryption
| After iterating through all automata rules, only linear rules work in place of 153 for alternating segments. Rule 29 appears to be the best alternate for diffusion of the plaintext.
RULE 29
P: deadbeefcafebabe
K: f6c78663f3578746
E: ce09bfd34be8a898
D: deadbeefcafebabe
RULE 51
P: deadbeefcafebabe
K: f6c78663f3578746
E: ce09bfd34be8a898
D: deadbeefcafebabe
RULE 204
P: deadbeefcafebabe
K: f6c78663f3578746
E: ce09bfd34be8a898
D: deadbeefcafebabe
RULE 205
P: deadbeefcafebabe
K: f6c78663f3578746
E: ce09bfd34be8a898
D: deadbeefcafebabe
|
70,920,106 | 70,920,312 | libao: os_types.h.in not converted to os_types.h by autoreconf | I am using libao in my C++ code. To set up the build system, I run the autogen.sh script (which uses autoreconf) in the repo. It works, but the os_types.h.in in include/ao/ doesn't get converted to os_types.h.
os_types.h is needed because when I try to include #include <libao/include/ao/ao.h> the compiler says that it cannot open source file "os_types.h" (dependency of "libao/include/ao/ao.h").
| Turns out that I needed to run ./configure and then make and I had the os_types.h file. Answer found from: Can't run Makefile.am, what should I do?
|
70,920,136 | 70,920,209 | Get default argument value from a function call c++ | Code will probably better explain my problem better than words:
#include <string>
struct Something {};
struct Context
{
std::string GetUniqueInentifier()
{
return "";
}
// ERROR
void Register(const Something& something, const std::string& key = GetUniqueInentifier())
{
}
};
int main()
{
Context c;
c.Register(Something{}); //<- want to be able to do this
// and a unique identifier will
// be automatically assigned
c.Register(Something{}, "Some Key"); //<- want to be able to let the user
// pick an identifier if they want
}
That is clearly not allowed but how can I simulate this behaviour ?
| You can't use non-static member functions or variables as a default value to member functions.
Since the value returned by GetUniqueInentifier() doesn't require an instance of Context, make it static and you can then use it as you tried using it.
static std::string GetUniqueInentifier()
{
return "";
}
|
70,920,177 | 70,920,200 | How to remove extra space in output of code? | Help! I am trying to print my code is giving the correct output BUT with an extra space that is not supposed to be there.
for (int i = i; i <= input; i++)
{
cout << factorial(input)/ (factorial(i) * factorial (input - i)) << " ";
}
return 0;
}
| Dont pad with space at the end on the last element
for (int i = 1; i <= input; i++)
{
cout << factorial(input)/ (factorial(i) * factorial (input - i));
if(i < input)
cout << " ";
}
|
70,920,272 | 70,920,327 | QObject::connect: No such slot QMainWindow::On_clicked_delCare() in ../Gestion_parc_auto/choice_page_2.cpp:91 | oplease, help me to solve this probleme. I don't know the proble but if I put QObject in file.h he generate error !
file.h
#include <QMainWindow>
class choice_page_2 : public QMainWindow
{
public:
choice_page_2();
QWidget* M_Widget = new QWidget();
public slots:
void On_clicked_delCare();
};
#endif // CHOICE_PAGE_2_H
fill.cpp
choice_page_2::choice_page_2()
{QPushButton *ManageBtn = new QPushButton(tr("Gérer une voiture"));
QMenu *menu = new QMenu(this);
QAction* AddCare = new QAction(tr("Ajouter une voiture"), this);
QAction* DelCare = new QAction(tr("Supprimer une voiture"), this);
QObject::connect( DelCare, SIGNAL(triggered()),this, SLOT(On_clicked_delCare()));
}
I get this error: **QObject::connect: No such slot QMainWindow::On_clicked_delCare()
| All classes that contain signals or slots must mention Q_OBJECT at the top of their declaration.
|
70,920,364 | 70,920,850 | cmake to link to dll without lib | I've been given a dll without libs.
The dll comes with hpp and h files.
I used dumpbin to create an exports.def file and lib to create a library.
I'm using the following CMakeLists.txt
cmake_minimum_required ( VERSION 3.22 )
project ( mytest )
include_directories("${PROJECT_SOURCE_DIR}/libincludedir")
add_executable ( mytest main.cpp)
target_link_libraries ( mytest LINK_PUBLIC ${PROJECT_SOURCE_DIR}/libincludedir/anewlib.lib )
The original dll and created lib and h and hpp files are all in the libincludedir. Dll is also copied to the bin dir where the exe would be.
I get no linker errors with the lib, but no functions defined in the include headers have bodies found. Types are Undefined. Classes are incomplete.
How do I fix this? Can I progress with what I was given or should I ask for more?
| Assuming that you created the .lib correctly, this is how you would set up something linkable:
cmake_minimum_required(VERSION 3.22)
project(example)
add_library(anewlib::anewlib SHARED IMPORTED)
set_target_properties(
anewlib::anewlib
PROPERTIES
IMPORTED_IMPLIB "${PROJECT_SOURCE_DIR}/libincludedir/anewlib.lib"
IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/libincludedir/anewlib.dll"
IMPORTED_NO_SONAME "TRUE"
INTERFACE_INCLUDE_DIRECTORIES "${PROJECT_SOURCE_DIR}/libincludedir"
)
add_executable(mytest main.cpp)
target_link_libraries(mytest PRIVATE anewlib::anewlib)
Always link to targets since they provide CMake with much more information than a raw library file. Here, we're telling CMake about the locations of both the .lib and the .dll, that it doesn't have a SONAME (a *nix only thing, anyway, but good to include), and the include path that linkees should use to find its associated headers.
Then when you link mytest to it, mytest will have a correct link line constructed and it will see the right headers.
|
70,920,935 | 70,924,135 | is there a "semi-pure" virtual function in c++? | Is there a way to write an abstract base class that looks like it's forcing an implementer to choose among a myriad of pure virtual functions?
The abstract base classes I'm writing define a mathematically tedious function, and request that the deriving code define only building block functions. The building block functions can be generalized to take on more arguments, though. For example, in the code below, it might "make sense" to allow another_derived::first() to take three arguments. The "mathematically tedious" part of this is the multiplication by 3. Unsurprisingly, it won't allow won't compile unless I comment out the creation of d2. I understand why.
One option is to create different base classes. One would request a single parameter function to be defined, and the other would request a two parameter function to be defined. However, there would be an enormous amount of code being copy and pasted between the two base class' definition of final_result(). This is why I'm asking, so I don't write WET code.
Another option would be to have one pure virtual function, but change the signature so that its implementation can do either of these things. I want to explore this, but I also don't want to start using fancier techniques so that it puts a barrier to entry on the type of people trying to inherit from these base classes. Ideally, if the writers of the base class could get away with barely knowing any c++, that would be great. Also, it would be ideal if the inheritors didn't even have to know about the existence of related classes they could be writing.
#include <iostream>
class base{
public:
virtual int first(int a) = 0;
int final_result(int a) {
return 3*first(a);
}
};
class derived : public base {
public:
int first(int a) {
return 2*a;
}
};
class another_derived : public base {
public:
int first(int a, int b) {
return a + b;
}
};
int main() {
derived d;
std::cout << d.final_result(1) << "\n";
//another_derived d2; // doesn't work
return 0;
}
| Not sure it matches exactly what you want, but with CRTP, you might do something like:
template <typename Derived>
struct MulBy3
{
template <typename... Ts>
int final_result(Ts... args) { return 3 * static_cast<Derived&>(*this).first(args...); }
};
class derived : public MulBy3<derived> {
public:
int first(int a) { return 2*a; }
};
class another_derived : public MulBy3<another_derived > {
public:
int first(int a, int b) { return a + b; }
};
With usage similar to
int main() {
derived d;
std::cout << d.final_result(1) << "\n";
another_derived d2;
std::cout << d2.final_result(10, 4) << "\n";
}
Demo
|
70,921,546 | 70,924,267 | Overloading operators with multiple member fields | I'm trying to overload different operators, such as >, +=, -=, >=, but for some reason I keep getting same error, expression must be bool type (or be convertable to bool)
Example
Money operator>=(const Money& lhs, const Money& rhs)
{
return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
}
I've also tried
Money operator>=(const Money& lhs, const Money& rhs)
{
return std::tie(lhs.pounds, rhs.pounds) < (lhs.pence, rhs.pence);
}
I'm trying to compare objects that inherit the object that I'm trying to compare, for example.
accounts[paramB] is an account object inside std::vector<Account*>. The Accounts class inherits Money class, and has a Money balance; member;
Account::Money getBalance(); { return 0; }
Savings::Money getBalance { return (balance.pounds, balance.pence) }
Money amount;
if(accounts[paramB]->getBalane() > amount)
...
Is there a way I can compare the same object without have to specify pounds and pence seperately?
if(accounts[paramB]->getBalane().pounds > amount.pounds && accounts[paramB]>getBalance().pence > amount.pence)
...
| return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
is parsed as
return lhs.pounds, (rhs.pounds >= lhs.pence), rhs.pence;
so is equivalent to
return rhs.pence;
std::tie is the way to go (in general case), but you don't use it correctly (and your return type is wrong). It should be
bool operator < (const Money& lhs, const Money& rhs)
{
return std::tie(lhs.pounds, lhs.pence) < (rhs.pounds, rhs.pence);
// Might be more appropriate in your case
// return (100 * lhs.pounds + lhs.pence) < (100 * rhs.pounds + rhs.pence);
// or, with appropriate helper function
// return to_pence(lhs) < to_pence(rhs);
}
bool operator > (const Money& lhs, const Money& rhs)
{
return rhs < lhs;
}
bool operator <= (const Money& lhs, const Money& rhs)
{
return !(rhs < lhs);
}
bool operator >= (const Money& lhs, const Money& rhs)
{
return rhs <= lhs;
}
|
70,921,684 | 70,921,711 | Python libclang how do you use a compilation database? | This has been asked twice already one answer seems very popular:
How to use compile_commands.json with clang python bindings?
This other one not as much:
How to use compile_commands.json with llvm clang (version 7.0.1) python bindings?
However neither solution seems to work. If you try the most popular solution, i.e. if you do this:
index = clang.cindex.Index.create()
compdb = clang.cindex.CompilationDatabase.fromDirectory('/home/makogan/neverengine_personal/build/')
file_args = compdb.getCompileCommands(path)
translation_unit = index.parse(path, file_args)
You will get this error:
Traceback (most recent call last):
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 178, in <module>
main()
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 175, in main
CreateNotebookFromHeader(args.path, args.out_path)
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 165, in CreateNotebookFromHeader
nb['cells'] = GetHeaderCellPrototypes(path)
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 148, in GetHeaderCellPrototypes
tokens = ExtractTokensOfInterest(path)
File "/home/makogan/neverengine_personal/Source/../Scripts/notebook_generator.py", line 54, in ExtractTokensOfInterest
translation_unit = index.parse(path, file_args)
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 2688, in parse
return TranslationUnit.from_source(path, args, unsaved_files, options,
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 2783, in from_source
args_array = (c_char_p * len(args))(*[b(x) for x in args])
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 2783, in <listcomp>
args_array = (c_char_p * len(args))(*[b(x) for x in args])
File "/home/makogan/.local/lib/python3.9/site-packages/clang/cindex.py", line 109, in b
return x.encode('utf8')
AttributeError: 'CompileCommand' object has no attribute 'encode'
If you try the second option:
I.e. this:
print( list(iter(file_args).next().arguments))
You get this error:
AttributeError: 'iterator' object has no attribute 'next'
How are people getting that first solution to work for them?
| The correct way seems to be doing this:
index = clang.cindex.Index.create()
token_dict = {}
compdb = clang.cindex.CompilationDatabase.fromDirectory('/home/makogan/neverengine_personal/build/')
commands = compdb.getCompileCommands(path)
file_args = []
for command in commands:
for argument in command.arguments:
file_args.append(argument)
translation_unit = index.parse(path, file_args)
|
70,921,712 | 70,921,762 | Finding GCD and LCM giving correct output for some test cases but my submission shows wrong answer | My c++ code of finding gcd and lcm is giving correct output for some test cases but my submission shows wrong answer.
int T;
cin>>T;
int x,y,a,b;
while(T--)
{
cin>>x>>y;
a=(x>y)?x:y; // a will be the greater number
b=(y>x)?x:y; // b will be the smaller number
int product=a*b;
///we will find gcd, and lcm will be a*b/gcd
if(a%b==0)
cout<<b<<" "<<a<<endl; // the smaller one will be gcd and the greater one, lcm
else
{
int rem=a%b;
while(rem!=0)
{
a=b;
b=rem;
rem=a%b;
}
cout<<b<<" "<<product/b<<endl;
}
}
Are there certain test cases I am missing? Or maybe my code is wrong.
| There are few cases on which it might fail:
When numbers x and y are not able to fit in int data type.
What if either x or y = 0?
You are doing product = a*b. This also can lead to overflow resulting wrong output in else part.
|
70,921,779 | 70,921,836 | C++ template function to concatenate both std::vector and std::array types | I have project where I am working with both fixed and variable length arrays of bytes. I want to have a function that can concatenate two arbitrary containers of bytes and return a single vector. Currently I am using
std::vector<uint8_t> catBytes(uint8_t const* bytes1, size_t const len1,
uint8_t const* bytes2, size_t const len2) {
std::vector<uint8_t> all_bytes;
all_bytes.reserve(len1 + len2);
all_bytes.insert(all_bytes.begin(), bytes1, bytes1 + len1);
all_bytes.insert(all_bytes.begin() + len1, bytes2, bytes2 + len2);
return all_bytes;
} // catBytes
However, I would like more generic way to do this, which better uses the capabilities of C++. I do not want to just accept iterators. I am trying to figure out how to accept two arbitrary containers and return a vector containing their contents. Ideally I would also not like to have to know the type inside the vector.
Something like
std::vector<unit_8> v1 = { 1, 2, 3, 4 };
std::array<unit_8, 4> a1 = { 1, 2, 3, 4 };
std::array<unit_8, 2> a2 = { 1, 2 };
auto res1 = concat(v1, a1); // std::vector<uint_8> of size 8
auto res2 = concat(a1, a2); // std::vector<uint_8> of size 6
// or
std::vector<char> v2 = { 1, 2, 3, 4 };
std::array<char, 4> a3 = { 1, 2, 3, 4 };
auto res3 = concat(v1, a1); // std::vector<char> of size 8
I think there is a templated approach to this but I just have not been able to figure it out.
| In general, generic + arbitrary, means templates.
Something like this?
template<class SizedRange1, class SizedRange2>
auto concat(SizedRange1 const& r1, SizedRange2 const& r2) {
std::vector<typename SizedRange1::value_type> ret;
ret.reserve(r1.size() + r2.size());
using std::begin; using std::end;
ret.insert(ret.end(), begin(r1), end(r1));
ret.insert(ret.end(), begin(r2), end(r2));
return ret;
}
EDIT:
The advantage of @康桓瑋's solution (which assumes that you are only interested in concatenating contiguous memory containers as you stated) is that you have a single function and you avoid code bloat.
As you noticed in the comments, the problem with that you can not deduce the element type, which can be anything in principle, so you are back to needing templates anyway.
Fortunately, you can combine the two approaches and reduce the number of functions generated as machine code, in the case that you have many different input containers, which is combinatorial.
template<class T>
std::vector<T>
concat_aux(std::span<const T> x, std::span<const T> y) {
std::vector<T> ret;
ret.reserve(x.size() + y.size());
ret.insert(ret.end(), x.begin(), x.end());
ret.insert(ret.end(), y.begin(), y.end());
return ret;
}
template<class ContinuousRange1, class ContinuousRange2>
auto concat(ContinuousRange1 const& r1, ContinuousRange2 const& r2) {
return concat_aux<typename ContinousRange1::value_type>(r1, r2);
}
The advantage is marginal here, but if the function concat is very complicated this last approach will pay off because it will generate code only for the different types of elements, not the number of containers squared in your instantiating code.
|
70,922,092 | 70,922,192 | Bitwise right shift operator >> didn't worked as intended | I am writing a code to find the number of ones in binary representation of a number
here is the code:
int main(void)
{
int n,tNum,count = 0;
cin >> n;
tNum = n;
while(tNum > 0)
{
int i = 0;
int bit = getBit(n,i);// get bit
if (bit == 1)
{
count++;
}
tNum >> 1;
i++;
}
cout << count << endl;
}
Above code gives an endless loop and tNum didn't change its value
I didn't understand where I am doing wrong
|
Bitwise right shift operator >> didn't worked as intended
The bitwise right shift operator >> is working as intended but you are not storing the result of >> operator anywhere. This expression
tNum >> 1;
will right shift the value of tNum by 1 but the result of this expression is unused.
Use >>= operator instead of >>. It should be:
tNum >>= 1;
This is same as tNum = tNum >> 1.
Another problem in your code:
This
getBit(n,i);
will give the 0th bit of n (as the i is initialised with 0 in every iteration) and which is going to be same for every iteration. Instead, you should get the 0th bit of tNum as you are using shift operator on tNum below in your code. Also, you don't need i at all, just remove it. The statement should be:
int bit = getBit(tNum, 0);// get 0th bit
One more important point, the result of right shift >> of a negative number is implementation defined. May, you should use unsigned int type for n and tNum.
You can do:
int main (void)
{
unsigned int n, tNum;
int count = 0;
cin >> n;
tNum = n;
while(tNum > 0)
{
int bit = getBit(tNum, 0);// get bit
// You can also do
// int bit = tNum & 1;
if (bit == 1)
{
count++;
}
tNum >>= 1;
}
cout << count << endl;
return 0;
}
Note: There is scope of improvement in the implementation of your code. I am leaving it up to you to identify those improvements and make respective changes in your code.
|
70,922,215 | 73,900,773 | Debugging CMake Visual Studio project with PATH environment set by VS_DEBUGGER_ENVIRONMENT | I've created a CMake project using visual studio 2019. It has one executable target, which links to some shared libraries (DLL). I cannot directly set the system environment variable PATH because the DLL path is determined by find_package. Therefore, set VS_DEBUGGER_ENVIRONMENT target property is my choice to debug that executable target.
However, the VS_DEBUGGER_ENVIRONMENT property is not working when I directly open the CMake project and debug that target. I've checked the .vsproj it has the correct LocalDebuggerEnvironment tag generated.
But if I run cmake -G "Visual Studio 16 2019" ../ and open the generated visual studio solution and then debug the subproject from there, everything turns out to be ok.
I think maybe the visual studio doesn't support LocalDebuggerEnvironment when opening project as a CMake project. Or perhaps I didn't debug it the right way. Is there anything else I can do to change the visual studio debug runtime PATH environment using CMake?
Any suggestion would be greatly appreciated!
| This is just to share what I finally ended up with after some painful hours of digging through the web.
First, a variable to store the required debugging paths is needed (example):
list(APPEND VS_DEBUGGING_PATH "%PATH%")
list(APPEND VS_DEBUGGING_PATH "${PostgreSQL_ROOT}/bin")
The next step is to create a ${CMAKE_PROJECT_NAME}.vcxproj.user template file for C/C++ and in my case also a ${CMAKE_PROJECT_NAME}.vfproj.user template for FORTRAN (just for the record):
file(
WRITE "${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}.vcxproj.user"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">
<PropertyGroup Condition=\"'\$(Configuration)'=='Release'\">
<LocalDebuggerEnvironment>PATH=@VS_DEBUGGING_PATH@</LocalDebuggerEnvironment>
</PropertyGroup>
<PropertyGroup Condition=\"'\$(Configuration)'=='MinSizeRel'\">
<LocalDebuggerEnvironment>PATH=@VS_DEBUGGING_PATH@</LocalDebuggerEnvironment>
</PropertyGroup>
<PropertyGroup Condition=\"'\$(Configuration)'=='RelWithDebInfo'\">
<LocalDebuggerEnvironment>PATH=@VS_DEBUGGING_PATH@</LocalDebuggerEnvironment>
</PropertyGroup>
<PropertyGroup Condition=\"'\$(Configuration)'=='Debug'\">
<LocalDebuggerEnvironment>PATH=@VS_DEBUGGING_PATH@</LocalDebuggerEnvironment>
</PropertyGroup>
</Project>"
)
file(
WRITE "${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}.vfproj.user"
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<VisualStudioUserFile>
<Configurations>
<Configuration Name=\"Release|x64\" Environment=\"PATH=@VS_DEBUGGING_PATH@\"/>
<Configuration Name=\"MinSizeRel|x64\" Environment=\"PATH=@VS_DEBUGGING_PATH@\"/>
<Configuration Name=\"RelWithDebInfo|x64\" Environment=\"PATH=@VS_DEBUGGING_PATH@\"/>
<Configuration Name=\"Debug|x64\" Environment=\"PATH=@VS_DEBUGGING_PATH@\"/>
</Configurations>
</VisualStudioUserFile>"
)
As you might see, both template files are just dumped into the root of ${CMAKE_BINARY_DIR} in this case. The base name ${CMAKE_PROJECT_NAME} is also arbitrary.
Those templates can then finally be "configured" (copied) into each target folder of your setup. Either for C/C++
configure_file(
"${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}.vcxproj.user"
"${CMAKE_CURRENT_BINARY_DIR}/${target_name}.vcxproj.user"
@ONLY
)
or FORTRAN
configure_file(
"${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}.vfproj.user"
"${CMAKE_CURRENT_BINARY_DIR}/${target_name}.vfproj.$ENV{USERNAME}.user"
@ONLY
)
or even both if necessary. The variable ${target_name} needs to replaced with your target name of course. :-)
This should suffice. It is however important to close VS 2019 before (re-)configuring/(re-)generating with CMake. Otherwise VS 2019 might simply overwrite those files for each target.
I strongly hope this is helpful.
Please let me know if you need more details.
Here is the result for C/C++ targets and here for FORTRAN targets
|
70,922,277 | 70,922,338 | Kth smallest element in a array | I was writing this code for finding Kth smallest element in array where l= starting index and r = ending index is given to us as input parameter in function.
class Solution{
public:
int kthSmallest(int arr[], int l, int r, int k) {
//code here
arr.sort(l,l+r+1);
int count =1,i=1,var =0;
while(count<=k)
{
var = arr[i];
count++;
i++;
}
return var;
}
};
I tried to use sort function in my code but this code is giving error in my sort function ,given below which is not understood by me.
prog.cpp: In member function int Solution::kthSmallest(int*, int, int, int):
prog.cpp:18:13: error: request for member sort in arr, which is of non-class type int*
arr.sort(l,l+r+1);
^
| arr is type int *, so a primitive type and a primitive type don't have any member function. So arr don't have any sort() member function, so it cause an error.
If you want to sort arr, use std::sort from <algorithm>.
std::sort(arr + l, arr + r + 1);
|
70,922,356 | 70,922,377 | Why I can pass a number to function which accepts const reference? (C++) | I'm new to C++, while I'm learning pass by reference I realized that I can't create a reference to a number directly, it has to be a variable. But if I define a function which accepts const reference, I can pass numbers in it.
int SumVal(const int& a, int b)
{
return a + b;
}
As far as I understand, I can pass a number directly like SumVal(1, 2) if the function declared with a const reference because I'll NOT be able to change the reference so the number(or variable) no matter what. The compiler knows this and doesn't complain about it.
But if I define it with normal reference like int SumVal(int& a, int b) I have the chance to change the passed variable inside the function so If I pass a number into this function, the compiler will complain about this.
So I would like to ask that my approach is correct or non-sense.
Thank you for your comments in advance.
(You can also check it out CB Bailey's this answer about pass by reference/value difference)
| Yes. It's because a const reference can bind to an r-value, but normal reference can't
|
70,922,392 | 70,922,445 | Performance of std::vector::swap vs std::vector::operator= | Given two vectors of equal length:
std::vector<Type> vec1;
std::vector<Type> vec2;
If the contents of vec2 need to be replaced with the contents of vec1, is it more efficient to use
vec2.swap(vec1);
or
vec2 = vec1;
assuming that vec1 will remain in memory but its contents after the operation don't matter? Also, is there a more efficient method that I haven't considered?
| swap will be more efficient since no copy is made. = will create a copy of vec1 in vec2, keeping the original intact.
If you check the documentation, you'll see that swap is constant while = is linear.
|
70,922,624 | 70,923,186 | What approach should I use in this question? approach I used below is not getting accepted | IPL Auctions are back. There are n players who will go under hammer in the sequence. There prices are given in a form an array in the order. A team wants to buy as much as player they can, but they have a condition that, they can only buy the current player if and only if the price of their last buyed player is less than the price of current player. Team can buy any player as their first player.
You need to find out the maximum player the team can buy following the above condition.
Input Format
First line of input contains an integer N, denoting the number of players in the auction.
Second line of input contains N space seperated integers denoting prices of players.
Constraints
1 ≤ N ≤ 10^5
0 ≤ A[i] ≤ 10^6
Output Format
The largest number of players they can buy
Sample Input :
array size = 6
5 8 3 7 9 1
Sample Output :
3
Explanation:
Largest number of the player will be when team will buy players with prices 5,8 and 9 that is 3.
What I have tried:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n ;
cin>>n;
int a[n];
for(int i = 0;i<n;i++){
cin>>a[i];
}
int mxcount = 0;
for(int i = 0;i<n;i++){
int k = i;
int count = 1;
for(int j = i;j<n;j++){
if(a[j] > a[k]){
count++;
k++;
}
}
mxcount = max(mxcount,count);
}
cout<<mxcount;
return 0;
}
| Inner for loop logic that have been used is wrong because the k-th index should always be the last player you have bought in the Auction, instead you are incrementing k-value instead of using the last bought player index.
We can implement below algorithm for this problem:
"We will always have two options during auction either to buy or not. so we can simply use a recursive approach of choosing and not choosing a player "
def auctionOptimizer(players, index_of_last_player_picked, current_index_of_player):
if(current_index_of_player >= players.size()) :
return 0;
if (players[current_index_of_player] > players[index_of_last_player_picked]):
int count_if_current_player_picked = 1 + auctionOptimizer(players, current_index_of_player, current_index_of_player+1);
int count_if_current_player_not_picked = auctionOptimizer(players, index_of_last_player_picked, current_index_of_player+1);
return max(count_if_current_player_picked, count_if_current_player_not_picked)
return auctionOptimizer(players, index_of_last_player_picked, current_index_of_player+1);
def main():
//Take players input array here
int max_players_we_can_buy = 0;
for(int player_index = 0 ; player_index < players.size(); players_index++) {
int count_if_current_player_index_picked = 1 + auctionOptimizer(players, player_index, player_index+1);
max_players_we_can_buy = max(max_players_we_can_buy, count_if_current_player_index_picked);
}
return max_players_we_can_buy;
We can further optimize this problem as there will be overlapping sub-problems i.e., we will be calling same function calls multiple times which would result in timeout. We can using DP for further optimising above approach.
Please approve the solution, if you found this helpful,
Thanks :-)
|
70,922,705 | 70,922,782 | How I can write a monotonic allocator in C++? | I'm trying to write a very simple monotonic allocator that uses a fixed total memory size. Here is my code:
#include <map>
#include <array>
template <typename T, size_t SZ>
class monotonic_allocator
{
public:
using value_type = T;
monotonic_allocator() noexcept {}
[[nodiscard]]
value_type* allocate(std::size_t n)
{
size_t start = 0;
for (const auto& [alloc_start, alloc_size] : alloc_list_) {
if ((alloc_start - start) <= n) {
alloc_list_[start] = n;
return mem_.data() + start;
}
start = alloc_start + alloc_size;
}
throw std::bad_alloc{};
}
void deallocate(value_type* p, std::size_t n) noexcept
{
alloc_list_.erase(static_cast<size_t>(p - mem_.data()));
}
template <typename T1, size_t SZ1, typename T2, size_t SZ2>
friend bool operator==(monotonic_allocator<T1, SZ1> const& x, monotonic_allocator<T2, SZ2> const& y) noexcept;
private:
std::array<value_type, SZ> mem_;
std::map<size_t, size_t> alloc_list_{};
};
template <typename T1, size_t SZ1, typename T2, size_t SZ2>
bool operator==(monotonic_allocator<T1, SZ1> const& x, monotonic_allocator<T2, SZ2> const& y) noexcept
{
return SZ1 == SZ2 && x.mem_.data() == y.mem_.data();
}
template <typename T1, size_t SZ1, typename T2, size_t SZ2>
bool operator!=(monotonic_allocator<T1, SZ1> const& x, monotonic_allocator<T2, SZ2> const& y) noexcept
{
return !(x == y);
}
int main()
{
std::vector<int, monotonic_allocator<int, 4096>> vec = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,6};
}
But I get a strange error which says:
error: no type named 'type' in 'std::__allocator_traits_base::__rebind<monotonic_allocator<int, 4096>, int>'
Any idea how I can solve this problem? BTW, this code may have other problems too.
| According to cppreference, rebind (which is part of the Allocator requirements) is only optional if your allocator is a template of the form <typename T, [possibly other type arguments]>. But your template is of the form <typename T, size_t N>, so it doesn't match (the size_t argument is a non-type argument).
So you have to add the rebind implementation yourself, like in the example in this question: How are allocator in C++ implemented?
|
70,923,814 | 70,928,447 | Firestore real-time updates with REST API | I'm developing c++ app which connects to Firestore DB via REST API. Is there any workaround to implement real-time updates when some fields in DB are modified? I'm thinking about getting collection document in certain time interval and checking whether there are any updates but it doesn't seem to be very efficient way. On the other side, the size of the downloaded data wouldn't be very large.
I know that gRPC allows using listeners, but I would prefer to stay with REST.
| The Firestore REST API does not implement realtime listeners. If having realtime listeners is a requirement for your use-case, you will have to use one of the SDKs or the gRPC API.
|
70,924,025 | 70,925,793 | C++20 NTTP specialization | There is disagreement between gcc/clang and msvc when trying to compile the following code:
struct foo {
};
// primary template
template<auto>
struct nttp {
static constexpr int specializaion = 0;
};
// specialization
template<foo f>
struct nttp<f> {
static constexpr int specializaion = 1;
};
int main() {
// Does not compile with msvc 19.30
nttp<5> x{};
}
Full example here.
Msvc is complaining that there is no viable conversion from int to foo which is obviously true, but shouldn't be of any relevance here as far as I understand the rules of partial template specialization.
Quoting cppreference:
When a class or variable (since C++14) template is instantiated, and there are partial specializations available, the compiler has to decide if the primary template is going to be used or one of its partial specializations.
If only one specialization matches the template arguments, that specialization is used
If more than one specialization matches, partial order rules are used to determine which specialization is more specialized. The most specialized specialization is used, if it is unique (if it is not unique, the program cannot be compiled)
If no specializations match, the primary template is used
I'd argue that there is no matching spezialization for int in this case hence the primary template should be selected.
Interestingly, the situation can be fixed by constraining the auto in the specialization by a concept:
template<class T>
concept Foo = std::is_same_v<T, foo>;
template<auto>
struct nttp {
static constexpr int specializaion = 0;
};
template<Foo auto f>
struct nttp<f> {
static constexpr int specializaion = 2;
};
// compiles with all compilers
static_assert(nttp<5>{}.specializaion == 0);
Function templates work as expected, too:
constexpr int test(auto) {
return 0;
}
constexpr int test(foo) {
return 1;
}
// compiles with all compilers
static_assert(test(5) == 0);
Long story short: empirically and intuitively I'd say that this is a bug in MSVC, but as always there's a chance that UB is involved here. So the question would be: are clang/gcc correct, or MSVC, or even all of them?
| This is open MSVC bug report:
Specialization of class template with auto parameter fails to compile for an unclear reason
Your program is well-formed as per [temp.class.spec.match]/2 and [temp.class.spec.match]/3:
/2 A partial specialization matches a given actual template argument
list if the template arguments of the partial specialization can be
deduced from the actual template argument list, and the deduced
template arguments satisfy the associated constraints of the partial
specialization, if any.
/3 If the template arguments of a partial specialization cannot be
deduced because of the structure of its template-parameter-list and
the template-id, the program is ill-formed.
/3 was specifically updated as part of P0127R2 (Declaring non-type template parameters with auto), which re-wrote the previously revised wording from the resolution of CWG1315
(After CWG1315, before P0123R2) /3 Each template-parameter shall appear at least once in the template-id outside a non-deduced context.
This re-write was done particularly to allow partial specialization over non-template parameters declared with the auto placeholder type.
|
70,924,232 | 70,925,042 | What is the equivalent of python's faiss.normalize_L2() in C++? | I want to perfom similarity search using FAISS for 100k facial embeddings in C++.
For the distance calculator I would like to use cosine similarity. For this purpose, I choose faiss::IndexFlatIP .But according to the documentation we need to normalize the vector prior to adding it to the index. The documentation suggested the following code in python:
index = faiss.IndexFlatIP(dimensions)
faiss.normalize_L2(embeddings)
But as I would like to implement the same thing in C++, I noticed I couldnot find any functions in C++ that is similar to the one in python faiss.normalize_L2().
Can anyone help?
Thank's in advance.
| You can build and use the C++ interface of Faiss library (see this).
If you just want L2 normalization of a vector in C++:
std::vector<float> data;
float sum = 0;
for (auto item : data) sum += item * item;
float norm = std::sqrt(sum);
for (auto &item : data) item /= norm;
|
70,924,991 | 70,925,149 | Check if directory exists using <filesystem> | I have a string that contains the path to some file. The file doesn't need to exist (in my function it can be created), but it's necessary that directory must exist. So I want to check it using the <filesystem> library.
I tried this code:
std::string filepath = {"C:\\Users\\User\\test.txt"};
bool filepathExists = std::filesystem::exists(filepath);
Also, the path is absolute. For example, for "C:\Users\User\file.txt" I want to check if "C:\Users\User" exists.
I have tried to construct a string using iterators: from begin to the last occurrence of '\\', but it very rough solution and I get exception if path contains only the name of the file.
Therefore, can somebody provide more elegant way to do it?
| The ansewer provided by @ach:
std::filesystem::path filepath = std::string("C:\\Users\\User\\test.txt");
bool filepathExists = std::filesystem::is_directory(filepath.parent_path());
It checks if "C:\Users\User" exists.
|
70,925,004 | 70,931,748 | How to copy the subsection of the 3 dimensional array in CUDA C++ | I had followed example of Using cudaMemcpy3D to transfer *** pointer
Yet my task is to copy the 3d subsection of the device global memory array to device global memory array for example:
Nx =10;
Ny=10;
Nz = 10;
struct cudaPitchedPtr sourceTensor;
cudaMalloc3D(&sourceTensor, make_cudaExtent(Nx * sizeof(int), Ny, Nz))
... // here I am populating sourceTensor with some Data
NxTarget = 5;
NyTarget = 5;
NzTarget = 5;
struct cudaPitchedPtr targetTensor;
cudaMalloc3D(&targetTensor, make_cudaExtent(NxTarget* sizeof(int), NyTarget, NzTarget))
// here I get lost ...
cudaMemcpy3DParms cpy = { 0 };
cpy.srcPtr = make_cudaPitchedPtr(sourceTensor[0][0], Nx * sizeof(int), Nx, Ny); // How to make it start in chosen location like for example 1,2,3
cpy.dstPtr = targetTensor;
cpy.extent = make_cudaExtent(NxTarget * sizeof(int), NyTarget , NzTarget );
cpy.kind = cudaMemcpyDeviceToDevice;
cudaMemcpy3D(&cpy);
So in above I am looking for a way to copy from sourceTensor to target tensor all the data where
x indices are in range (1,6)
y indices are in range (2,7)
z indices are in range (3,8)
So only subsection of the source array but I do not know How to define make_cudaPitchedPtr and make_cudaExtent properly, in order to achieve my goal.
| The srcPos parameter in your cudaMemcpy3DParams should make this pretty easy. Here is an example:
$ cat t1957.cu
#include <cstdio>
typedef int it; // index type
typedef int dt; // data type
__global__ void populate_kernel(struct cudaPitchedPtr sourceTensor, it Nx, it Ny, it Nz) {
for (it z = 0; z < Nz; z++)
for (it y = 0; y < Ny; y++)
for (it x = 0; x < Nx; x++) {
char *ptr = (char *)sourceTensor.ptr + sourceTensor.pitch*(z*Ny+y);
((dt *)ptr)[x] = z*100+y*10+x;
}
};
__global__ void verify_kernel(struct cudaPitchedPtr targetTensor, it NxTarget, it NyTarget, it NzTarget, it NxOffset, it NyOffset, it NzOffset) {
if (((dt *)targetTensor.ptr)[0] != 321) {
printf("%d\n", ((dt *)targetTensor.ptr)[0]);
}
};
int main(){
it Nx =10;
it Ny=10;
it Nz = 10;
struct cudaPitchedPtr sourceTensor;
cudaMalloc3D(&sourceTensor, make_cudaExtent(Nx * sizeof(dt), Ny, Nz));
populate_kernel<<<1,1>>>(sourceTensor, Nx, Ny, Nz);
it NxTarget = 5;
it NyTarget = 5;
it NzTarget = 5;
struct cudaPitchedPtr targetTensor;
cudaMalloc3D(&targetTensor, make_cudaExtent(NxTarget* sizeof(dt), NyTarget, NzTarget));
cudaMemcpy3DParms cpy = { 0 };
it NxOffset = 1;
it NyOffset = 2;
it NzOffset = 3;
cpy.srcPos = make_cudaPos(NxOffset*sizeof(dt), NyOffset, NzOffset);
cpy.srcPtr = sourceTensor;
cpy.dstPtr = targetTensor;
cpy.extent = make_cudaExtent(NxTarget * sizeof(dt), NyTarget , NzTarget );
cpy.kind = cudaMemcpyDeviceToDevice;
cudaMemcpy3D(&cpy);
verify_kernel<<<1,1>>>(targetTensor, NxTarget, NyTarget, NzTarget, NxOffset, NyOffset, NzOffset);
cudaDeviceSynchronize();
}
$ nvcc -o t1957 t1957.cu
$ cuda-memcheck ./t1957
========= CUDA-MEMCHECK
========= ERROR SUMMARY: 0 errors
$
Note that when neither source nor destination are specified as cudaArray types, then the element size is always assumed to be unsigned char (ie. 1 byte).
|
70,925,263 | 70,925,402 | switch statement over performing with char variable in c++ | #include<iostream>
using namespace std;
void fun() {
while(1) {
char choice;
cout<<"(D)isplay, (E)xit"<<endl;
start:
cout<<">> ";
cin>>choice;
switch(choice) {
case 'd':
case 'D':
cout<<"hello world"<<endl;
break;
case 'e':
case 'E':
return;
default:
cout<<"INVALID!"<<endl;
goto start;
}
}
}
int main() {
system("clear");
fun();
return 0;
}
This is a simple c++ program.
I am faciing following problem:
(D)isplay, (E)xit
>> mnop
INVALID!
>> INVALID!
>> INVALID!
>> INVALID!
>>
The symbol '>>' prompt user to enter a character and with that it give apppropriate result but if entered a string it behaves something like this. I want to know why this happens and how to stop it :)
| Your code does what you told it to but not more: cin>>choice; reads a single character. When the user types more than a single character then the other characters are left in the stream and will be read by the next call.
If you want to handle input of more than a single character properly then you need to extract more than single character from the stream. For example:
while (true) {
std::string input;
std::cin >> input;
if (input.size() > 1 || input.size() == 0) {
std::cout << "enter only a single character\n";
} else {
choice = input[0];
break;
}
}
Alternatively you could check if there are more characters left in the stream after reading one and/or simply discard them (via ignore).
|
70,925,450 | 70,925,563 | cpp/arduino: classes call inherited virtual method | I'm struggling to find the right answer on below question on the internet.
I'm not a native C++ programmer and have more knowledge of OOP programming in PHP, Pascal, and JavaScript, but i can manage.
I want to create a class hierarchy to handle some tasks like displaying content on a LCD screen.
It looks like the following classes:
class base {
public:
base() { };
virtual void display() { // Need to be called first from all child objects };
virtual bool keyPress(int state) { //Need to be called first from all child objects };
};
class child : public base {
public:
child():base() {};
virtual void display() {
>> call base->display()
// do some stuff
};
virtual bool keyPress(int state) {
>> call base->keyPress(state)
// check some stuff
};
};
Most program language that i know of has some 'parent::' solution to call the inherited virtual method but i cant find anything comparable for C++.
an option that i going to use for now is:
class base {
protected:
virtual void _display() =0;
virtual bool _keyPress(int state) =0;
public:
base() { };
void display() {
// do basic stuff
_display();
};
bool keyPress(int state) {
if (!_keyPress(state)) {
// do basic stuff.
};
};
class child : public base {
protected:
virtual void _display() {
// do some stuff
};
virtual bool _keyPress(int state) {
// check some stuff
};
public:
child():base() {};
};
I do not like this method but it will work.
| The right syntax is base::display():
class base {
public:
base() { };
virtual void display() { /* Need to be called first from all child objects*/ };
virtual bool keyPress(int state) { /*Need to be called first from all child objects*/ return 42; };
};
class child : public base {
public:
child():base() {};
virtual void display() {
base::display();
// do some stuff
};
virtual bool keyPress(int state) {
return base::keyPress(state);
// check some stuff
};
};
However, if it is the same in all child classes you better let base call its methods like you do it in your second code. It is not clear why you "do not like this method". It works, does what you want, and avoids lots of duplicate code and decreases chances for mistakes in the derived classes. Just note that the virtual methods need not be protected, because the derived classes are not supposed to call them directly, you can make them private: https://godbolt.org/z/1qjooKq85 (perhaps that is what you didn't like?).
|
70,925,635 | 70,928,568 | Gtest on new keyword | new keyword in C++ will throw an exception if insufficient memory but below code trying to return "NO_MEMORY" when new failed. This is bad because it will raise std::bad_alloc exception .
I am writing a unit test(gtest). How to create a scenario to catch this problem.
class base{
public: base(){
std::cout<<"base\n";
}
};
std::string getInstance(base** obj){
base *bObject = new base();
*obj = bObject; //updated
return (NULL == bObject) ? "NO_MEMORY" : "SUCCESS"; // here is problem if new fail it raise an exception. How to write unit test to catch this?
}
int main()
{
base *base_obj;
getInstance(&base_obj);
}
| Have you looked into EXPECT_THROW?
If you cannot absolutely change your code, (which is required if you want to use gmock), you can globally overload the new operator as the other answer suggested.
However, you should do this carefully since this operator is used by other functions including the ones in google test.
One way to do this is to use a global variable that makes the new operator throw conditionally. Note that this is not the safest way, specially if your program is using multithreading
Below is one way of testing the scenario you described using this method and the global variable g_testing.
// https://stackoverflow.com/questions/70925635/gtest-on-new-keyword
#include "gtest/gtest.h"
// Global variable that indicates we are testing. In this case the global new
// operator throws.
bool g_testing = false;
// Overloading Global new operator
void *operator new(size_t sz) {
void *m = malloc(sz);
if (g_testing) {
throw std::bad_alloc();
}
return m;
}
class base {
public:
base() { std::cout << "base\n"; }
};
std::string getInstance(base **obj) {
base *bObject = new base();
*obj = bObject; // updated
return (NULL == bObject)
? "NO_MEMORY"
: "SUCCESS"; // here is problem if new fail it raise an exception.
// How to write unit test to catch this?
}
TEST(Test_New, Failure) {
base *base_obj;
// Simple usage of EXPECT_THROW. This one should THROW.
g_testing = true;
EXPECT_THROW(getInstance(&base_obj), std::bad_alloc);
g_testing = false;
std::string result1;
// You can put a block of code in it:
g_testing = true;
EXPECT_THROW({ result1 = getInstance(&base_obj); }, std::bad_alloc);
g_testing = false;
EXPECT_NE(result1, "SUCCESS");
}
TEST(Test_New, Success) {
base *base_obj;
std::string result2;
// This one should NOT throw an exception.
EXPECT_NO_THROW({ result2 = getInstance(&base_obj); });
EXPECT_EQ(result2, "SUCCESS");
}
And here is your working example: https://godbolt.org/z/xffEoW9Kd
|
70,926,139 | 70,926,289 | Issue with a math rule of three in c++ | I started learning c++, but I have an issue.
I'm trying to do a rule of three in c++ but I get a wrong result. Should give me 55.549,38775510204, and I get -41842.000000000000
What I'm doing wrong??
In C# I do this and works fine:
decimal ruleOfThree = decimal.Divide(decimal.Multiply(32000, 76554), 44100);
In C++ I'm doing this:
long double ruleOfThree = ((32000 * 76554) / 44100);
| I haven't tested this on a C++ compiler, but something like:
long double ruleOfThree = ((32000.0 * 76554.0) / 44100.0);
I.e. make sure the 3 multipliers are doubles, not integers.
|
70,926,826 | 70,926,991 | C++ test for validation UTF-8 | I need to write unit tests for UTF-8 validation, but I don't know how to write incorrect UTF-8 cases in C++:
TEST(validation, Tests)
{
std::string str = "hello";
EXPECT_TRUE(validate_utf8(str));
// I need incorrect UTF-8 cases
}
How can I write incorrect UTF-8 cases in C++?
| You can specify individual bytes in the string with the \x escape sequence in hexadecimal form or the \000 escape sequence in octal form.
For example:
std::string str = "\xD0";
which is incomplete UTF8.
Have a look at https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt for valid and malformed UTF8 test cases.
|
70,927,817 | 70,930,741 | c++ How do I find length of buffer in non-windows platforms using fread() | I have a function using ReadFile() where I append a '\0' at the end of the buffer :
HANDLE InFile;
FILE* InputFile;
DWRD len = ftell(InputFile);
buffer = new BYTE[len + 1];
if (ReadFile(InFile, buffer , len, &len2, NULL))
{
...
buffer [len2] = 0;
}
Now I want to adapt this function for use with non-windows platforms. I already changed ReadFile() and use fread() now. But then I do not have len2 available which I would like to use for appending the '\0':
FILE* InputFile;
DWRD len = ftell(InputFile);
buffer = new BYTE[len + 1];
if (fread(buffer ,1,len,InputFile))
{
// how can I find the length of the buffer (len2) now ?
buffer [len2] = 0; // Does not work !
...
}
How can I get the position of the end of my buffer ?
| fread() returns the numbers of items actually read, eg:
FILE* InputFile;
...
DWORD len = ftell(InputFile);
buffer = new BYTE[len + 1];
size_t len2;
if ((len2 = fread(buffer, 1, len, InputFile)) > 0)
{
buffer [len2] = 0;
...
}
else
{
// use feof() and ferror() to check for errors...
}
|
70,928,047 | 70,928,173 | Invoking a tuple containing both the invocable and the arguments | I am trying to invoke the first parameter in a tuple with the second one as a parameter, but can't figure out how to do it.
Example:
#include <tuple>
#include <functional>
struct S {
void operator()(int) {}
};
int main() {
S s;
auto t = std::make_tuple(s, 3);
std::invoke(s, 3);
// std::apply(std::invoke, t); // This is what I want to do
// std::apply(std::invoke<S, int>, t); // I would settle for this "Good Enough"
}
but the code above doesn't compile, and the error is very unhelpful (to me):
error: no matching function for call to '__invoke(void (&)(S&&, int&&), std::__tuple_element_t<0, std::tuple<S, int> >&, std::__tuple_element_t<1, std::tuple<S, int> >&)'
(this is from the "good enough" attempt)
Anyone know how to do this, or if it can't be done?
| Wrapping overload/template function in lambda solves lot of issues:
std::apply([](auto&&... args){ std::invoke(args...); }, t);
Possibly with forwarding:
std::invoke(std::forward<decltype(args)>(args)...);
Else as std::invoke is a template function (taking forwarding reference), you need to correct type:
std::apply(std::invoke<S&, int&>, t);
std::apply(std::invoke<S, int>, std::move(t));
Demo
About the error reading: std::__tuple_element_t<0, std::tuple<S, int> >& is S&, so error simplify to
error: no matching function for call to __invoke(void (&)(S&&, int&&), S&, int&)"
You would need void (&)(S&, int&) (or pass S&&, int&& as argument of the function)
|
70,928,300 | 70,936,138 | Beginning on boost::asio : Having problems using io_context | I've been coding in c++ and wanted to try out boost asio to create a TCP asynchronous server.
I read the documentation that boost provides and I used boost 1.75 to try and code this server.
However, I don't seem to understand how to use the io_context from the documentation.
When I am compiling the code for the Day 3: Asynchronous TCP daytime server (this link which is in boost 1.78 but doesn't seem to differ a lot from 1.75) I constantly get the error that io_context cannot be copied due to their inheritance from execution_context, which inherits from noncopyable.
So I don't understand how to write and compile the documentation code since it tries to make a copy of an io_context in it.
Thanks in advance for any replies.
Edit : I've been compiling the code on C++ 17 and used conan to manage boost, the problem I am having comes from the constructor where I try to copy an io_context to an attribute of my class :
class Server {
public:
Server(boost::asio::io_context& io_context) : _io_context(io_context), _acceptor(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 13))
{
startAccept();
}
~Server();
private:
void startAccept();
void handleAccept(ConnectionHandler::pointer new_connection, const boost::system::error_code &error);
boost::asio::io_context _io_context;
boost::asio::ip::tcp::acceptor _acceptor;
};
And here are the compilation error I was getting with the example :
error: use of deleted function
‘boost::asio::io_context::io_context(const boost::asio::io_context&)’17 | Server(boost::asio::io_context& io_context) :
_io_context(io_context), _acceptor(io_context,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 13))
/home/romsnouk/.conan/data/boost/1.75.0/_/_/package/634391908be52704fdd5c332658475fe91ab3b1d/include/boost/asio/io_context.hpp:639:3: note: declared here
639 | io_context(const io_context&) BOOST_ASIO_DELETED;
| The problem? When you try to initialize the _io_context member you copy the un-copyable io_context object.
The _io_context member needs to be a reference:
boost::asio::io_context& _io_context;
// ^
// Note ampersand, to make it a reference
This is what's done in the full example.
Of course make sure that the life-time of the original io_context object is at least as long as the Server object you create.
|
70,928,438 | 70,929,005 | Is there a faster, other, different way to use an if statement | This is my first mini project (I'm intermediate c++ programmer)
I wanted to practice using if statements because I wanted to find the extent of the command, and what I could use it for.
However, throughout my program, I constantly became very annoyed that I'm having to write all this code, to perform a simple task.
The basics of the code is that the user inputs their birth month, and the program outputs their astrology related sign and meaning. My question is,
Is there a way, that I could perform the same task, but in less code? Is there a command I could use, or something?
------extra-------------------------------------
In my cs1 class, we recently learned about switch cases. I was thinking that I could use switch cases to fix 1 problem I had, accuracy
Improving the accuracy of the users b-day. Instead of using tons of if statements which can only look for a specific month (or with even more if's month and day) I could use a case that said "1. January 1-20th"
However, now this just makes me want to be more accurate about the month.
***Could I possible use more if statements or perhaps something in the case that basically says if the user says <20 then they are Aquarius?
Is there also a different way I could do the program other than switch cases?
string user_month;
cout << "This program currently accepts these months in this spelling\n";
cout << "january, february, march\n\n";
cout << "Whats the month of your birthday? (lowercase)\n";
getline(cin, user_month);
cout << endl;
cout << user_name << " ... You are about to see your astrological sign and its qualities.\n";
cout << "Know that they might not be truly accurate and this is just for fun.\n\n";
if (user_month == "january")
{
;
cout << endl;
cout << "You are a Capricorn.\n";
cout << "Capricorns are usually hardworking, tenacious, diligent, and responsible\n";
cout << "No matter what the job is, you'll get it done to the best of your ability.\n";
cout << "Even if you don t have a natural aptitude for a skill, you won t stop working until you ve mastered "
"it\n.";
}
if (user_month == "february")
{
cout << endl;
cout << "You are a Aqaurius.\n";
cout << "An Aquarius ascribes to a progressive ideology. \n";
cout << "Because of this you are willing to let go of ";
cout << "past traditions that no longer serve the people of the future.\n";
cout << "You aren t content with the answer 'but that s the way it s always been done.' \n";
cout << "You are willing to try new things, because you know that even if they fail, \n";
cout << "you know that your getting closer to the right solution.\n";
}
if (user_month == "march")
{
cout << endl;
cout << "You are an Aries.\n";
cout << "At your core, you do what they want and do things your way.\n";
cout << "You are unafraid of conflict, highly competitive, honest and direct.\n";
cout << "An Aries is not weighed down by the freedom of choice, and is the sign that is least conflicted about "
"what they want.\n";
cout << "You might throw themselves at the world eagerly and without fear.\n";
cout << "It is one of your most commendable qualities, but also what causes you a great deal of pain and "
"grief.\n";
}
// yes I'm aware my code does not include all the months
return 0;
}
| Sometimes, when you have to handle n different values in different ways, you end up with a switch or if-cascade with n branches.
But often, when you perform the same action (with different data) in all branches, there are other ways, e.g., a look-up table.
What are you trying to do? For each month, print a text. So the same action, different data.
Before we look at more complicated solutions, let's improve what you have with the stuff you have learned so far.
First off, you don't need to repeat cout every time, you can chain the stream operator <<:
std::cout << "Hello\n" << "My name is Bob.\n" << "I like potatoes.\n";
Even better, C++ will merge string literals "that are" "adjacent":
std::cout << "Hello\n"
"My name is Bob.\n"
"I like potatoes.\n";
You can also put these large text blocks into variables outside of your main, so you have them out of sight:
const char *capricorn = "You are a Capricorn.\n"
"Capricorns are hard...";
So you end up with code like:
string user_month;
getline(cin, user_month);
if (user_month == "january") {
cout << capricorn;
} else if (user_month == "february") {
cout << aquarius;
} else if (// etc...
A bit easier to read. Now we see the structure of our program much clearer. We just want to cout something depending on month.
Now, there are things you haven't learned about. E.g., using a "map" (a lookup table):
#include <unordered_map>
// In your function
// Map of key-value pairs
std::unordered_map<std::string, std::string> um =
{ {"january", "You are a Capricorn\n etc etc\n"} };
// Read month, then:
auto res = um.find(user_month);
if (res != um.end()) {
// Found in map. res->first is key, res->second is value.
std::cout << res->second;
} else {
// Invalid month
std::cout << "Error: invalid input";
}
Another way would be to store the strings in an array and map the months to array indices (0-11). But you'd need an if-cascade for that too, so maybe that defeats the purpose.
Note that for actual zodiac signs, the task would be a bit more difficult, because they are not about months, but date ranges (e.g., march 21. - april 19.).
|
70,928,527 | 70,928,566 | Unable to visit a variant if one of its alternatives does not have a specific field | I am trying to visit a variant containing several classes. One of them does not have a specific field value but I handle it with constexpr, however, the compiler still fails to compile.
#include <variant>
#include <iostream>
struct A {};
struct B {
int value = 1;
};
struct C {
int value = 2;
};
int main() {
const auto d = std::variant<A, B, C>{B{}};
auto n = std::visit(
[&](auto &data) -> int {
if constexpr (std::is_same_v<decltype(data), A>) {
return int{0};
} else {
return data.value;
}
},
d);
std::cout << n << std::endl;
return 0;
}
Error:
error: ‘const struct A’ has no member named ‘value’
22 | return data.value;
Compiler version:
clang --version
clang version 10.0.0-4ubuntu1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Do I miss something or it is impossible by design?
EDIT:
The shortest solution was to use std::decay_t, however, I don't know if there can be any consequences:
if constexpr (std::is_same_v<std::decay_t<decltype(data)>, A>)
| You need remove reference and cv-qualifiers of the data:
auto n = std::visit(
[&](auto &data) -> int {
if constexpr (std::is_same_v<std::remove_cvref_t<decltype(data)>, A>) {
return int{0};
} else {
return data.value;
}
},
d);
Demo
In C++20, you can just use the requires clause to detect whether the data.value expression is valid.
const auto d = std::variant<A, B, C>{B{}};
auto n = std::visit(
[&](auto& data) -> int {
if constexpr (requires { data.value; }) {
return data.value;
} else {
return int{0};
}
},
d);
|
70,929,336 | 70,929,441 | Function definition with default value (c++) | Consider the following class:
class A{
public:
void fun(int i=0) {cout<<"Base::fun("<<i<<")";}
};
If I understand correctly, when the compiler sees void fun(int i=0), it will define 2 functions for us. One is the function:
void fun() {cout<<"Base::fun("<<0<<")";}
And the other one is the function:
void fun(int i) {cout<<"Base::fun("<<i<<")";}
Next, as I understand, we cannot define 2 functions with the same name in a class. For example:
class A{
public:
void fun() {cout<<"Base::fun()";}
void fun() {cout<<"Base::fun("<<0<<")";}
};
does not compile and returns error:
error: 'void A::fun()' cannot be overloaded with 'void A::fun()'
So, my question is why does the following definition compiles :
class A{
public:
void fun() {cout<<"Base::fun()";}
void fun(int i=0) {cout<<"Base::fun("<<i<<")";}
};
Thanks in advance.
|
If I understand correctly, when the compiler sees void fun(int i=0), it will define 2 functions for us.
No you do not understand correctly. It only defines one single function returning void and taking an int parameter. Simply if you call it with no parameter and if not function with same name and declared with no parameter exists, the compiler will implicitely add the default parameter.
Said differently the compiler will under the hood replace this call:
fun();
with that one:
fun(0);
|
70,929,696 | 70,930,710 | make std::ostream automatically ident when encountering special characters | I would like to have some facility which makes a std::ostream (or derived) automatically ident on encountering special characters (or special objects). Let's assume that the special characters are < and >. In this case the following input test0<test1<test2, test3<test4> > > should produce the following output:
test0<
test1<
test2,
test3<
test4
>
>
>
How would one go to implement this?
| boost::iostreams makes this fairly easy, you can define filters then chain them together with an output stream to transform the input to the desired output:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
namespace io = boost::iostreams;
struct QuoteOutputFilter {
typedef char char_type;
typedef io::output_filter_tag category;
int indent = 0;
template<typename Sink>
bool newLine(Sink& snk)
{
std::string str = "\n" + std::string(indent * 4, ' ');
return io::write(snk, str.c_str(), str.size());
}
template<typename Sink>
bool put(Sink& snk, char c)
{
switch (c)
{
case '<':
io::put(snk, c);
indent += 1;
return newLine(snk);
case ',':
io::put(snk, c);
return newLine(snk);
case '>':
indent -= 1;
newLine(snk);
return io::put(snk, c);
default:
return io::put(snk, c);
}
}
};
int main()
{
io::filtering_ostream out;
out.push(QuoteOutputFilter());
out.push(std::cout);
out << "test0<test1<test2, test3<test4> > >";
}
|
70,929,819 | 70,930,039 | Can const data members have different values between translation units? | I'm wondering if it is permitted to declare the same class multiple times using different values for a const member, or if this would be an ODR violation? Consider this example with two independent translation units that are going to be linked into some libx library:
// x.h
#pragma once
class X {
const int x = VALUE;
};
// x1.cpp
#define VALUE 1
#include "x.h"
int fn1() {
X x;
return x.x;
}
// x2.cpp
#define VALUE 2
#include "x.h"
int fn2() {
X x;
return x.x;
}
Also, in case this is not legal, does it make a difference whether x is declared const or not?
| Yes, different objects can have different const data members. The issue that the comments are focussing on is in the way that the data member gets initialized, which doesn't really address the issue.
struct s {
const int x;
s(int xx) : x(xx) {}
};
s s1(1);
s s2(2);
What you can't do is define the same name in multiple translation units with a different definition:
// a1.cpp
s s1(1);
// a2.cpp
s s1(2);
that's a violation of the one definition rule. But it has nothing to do with the const data member; the same problem would occur if s::x was not const. And you'd have an ODR violation in your original example if x was plain int, not const.
|
70,930,072 | 70,933,061 | Using UTF-8 string-literal prefixes portably between C++17 and C++20 | I have a codebase written in C++17 that makes heavy use of UTF-8, and the u8 string literal introduced in c++11 to indicate UTF encoding. However, c++20 changes the meaning of what the u8 literal does in C++ from producing a char or const char* to a char8_t or const char8_t*; the latter of which is not implicitly pointer convertible to const char*.
I'd like for this project to support operating in both C++17 and C++20 mode without breakages; what can be done to support this?
Currently, the project uses a char8 alias that uses the type-result of a u8 literal:
// Produces 'char8_t' in C++20, 'char' in anything earlier
using char8 = decltype(u8' ');
But there are a few problems with this approach:
char is not guaranteed to be unsigned, which makes producing codepoints from numeric values not portable (e.g. char8{129} breaks with char, but not with char8_t).
char8 is not distinct from char in C++17, which can break existing code, and may cause errors.
Continuing from point-2, it's not possible to overload char with char8 in C++17 to handle different encodings because they are not unique types.
What can be done to support operating in both C++17 and C++20 mode, while avoiding the type-difference problem?
| I would suggest simply declaring your own char8_t and u8string types in pre-C++20 versions to alias unsigned char and basic_string<unsigned char>. And then anywhere you run into conversion problems, you can write wrapper functions to handle them appropriately in each version.
|
70,930,278 | 70,931,237 | How to speed up C++ MySQL connector? | I am using C++ MySQL connector.
sql::Connection * db = nullptr;
try {
db = get_driver_instance()->connect("tcp://localhost:3306", "admin", "admin");
db->setSchema("test_db");
}
catch(exception &e) {
return 1;
}
The MySQL connector is dynamically linked to the application.
LDFLAGS = -L/usr/local/mysql-connector-c++/lib64
LDLIBS = -lmysqlcppconn
CXXFLAGS = -Wall -Wextra -g -std=c++11 -O3
When I run my application it takes about 13 033 µs and about 10 000 µs is only this connection to MySQL. I also tried to compile it using static library, but it didn't help.
Is there any way to speed up the database connection?
|
how to say to server: give me pointer to DB connection
MySQL connections cannot be shared between processes. If your C++ process starts when an http request is handled, it must open a new MySQL connection at that time.
More typically, a high-performance web app does not fork a new process for every http request. You're designing code using the 1990's-era CGI protocol and expecting high performance, you should change your architecture.
For example, a FastCGI implementation should handle many http requests with a single process. That way you can use a connection pool that provides MySQL connections to request handlers without needing to reopen the connection every time.
To speed up individual MySQL connections, consider:
Upgrade at least to MySQL 5.7, to take advantage of improved connection speed. I thought I read that 8.0 improved this speed even further, but I can't find a reference for that right now.
Use the UNIX domain socket interface, which is faster than TCP/IP connections. It should be as simple as using "localhost" when connecting the client to the MySQL server.
If you do use TCP/IP, then set the option skip_name_resolve.
https://dev.mysql.com/doc/refman/8.0/en/host-cache.html says:
If you have a very slow DNS and many hosts, you might be able to improve performance either by enabling skip_name_resolve to disable DNS lookups, or by increasing the value of host_cache_size to make the host cache larger.
|
70,930,455 | 70,931,213 | How do I handle subdirectory dependencies in CMake? | I have a project where I need to run one application on multiple boards. To do this I have two exectuables that share a main.c, but are compiled with a different board.c. The directory tree is as follows:
CMakeLists.txt
src/
├─ board/
│ ├─ board_a/
│ │ ├─ board.c
| | ├─ CMakeLists.txt
│ ├─ board_b/
│ │ ├─ board.c
| | ├─ CMakeLists.txt
├─ app/
│ ├─ main.c
├─ lib/
│ ├─ somelib/
│ │ ├─ somelib.h
│ │ ├─ somelib.c
In an attempt to make the root CMakeLists.txt smaller and more maintainable, I've created a CMakeLists.txt for both boards, and would like to compile each board as an object library for the main executable in the root CMakeLists.txt to add_subdirectory on and link in.
My problem is that board.c (as well as main.c) depends on somelib. How can I add this dependency to the subdirectory CMakeLists.txt? Is there a way I can do that without hard-coding a path to somelib? My feeling is that I should create a CMakeLists.txt in somelib, and I feel this would be easy if I were handling the library linking from the root CMakeLists.txt, but my confusion is that board is adjacent to lib. I'm relatively new to CMake and am not sure how to best structure these dependencies.
|
My problem is that board.c (as well as main.c) depends on somelib. How can I add this dependency to the subdirectory CMakeLists.txt? Is there a way I can do that without hard-coding a path to somelib? My feeling is that I should create a CMakeLists.txt in somelib, and I feel this would be easy if I were handling the library linking from the root CMakeLists.txt, but my confusion is that board is adjacent to lib. I'm relatively new to CMake and am not sure how to best structure these dependencies.
This is very straightforward start by linking each board_<X> to somelib's target.
# in each board_<X>/CMakeLists.txt
add_library(board_<X> OBJECT ...)
target_link_libraries(board_<X> PUBLIC proj::somelib)
then create the target for somelib:
# src/lib/somelib/CMakeLists.txt
add_library(somelib somelib.c)
add_library(proj::somelib ALIAS somelib)
target_include_directories(
somelib PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>")
As long as the top-level CMakeLists.txt includes these subdirectories via add_subdirectory (multiple levels is fine), then other targets can #include <somelib.h> and CMake will handle linking.
|
70,930,812 | 70,930,907 | What does each of these `const`s mean? | Normally people write the main function like this:
int main( int argc, char** argv )
However, this came to my mind:
int main( const int argc, const char* const* const argv )
or maybe I should write it like this cause it seems more intuitive:
int main( const int argc, const char *const *const argv )
What does each of the consts mean in argv (I think I understand them all but am still not sure)?
Also is this a valid code? What issues/limitations can it cause when using argv inside main?
Now what's the difference between this one and the latter:
int main( const int argc, const char* const argv[] )
| The prototype is defined as "int main( int argc, char** argv )"
There is really no point in using a const pointer to access the parameters later unless you don't want to get it changed, which is up to you
The purpose of const pointers is to make sure that they are not changed throughout the code. You can live without them, but it helps avoid other issues, bugs for example.
On the other side, there is no performance gain (Optimizing_compiler)
1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner.
2 If they are declared, the parameters to the main function shall obey the following
constraints:
— The value of argc shall be nonnegative.
— argv[argc] shall be a null pointer.
— If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.
— If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment.
If the value of argc is greater than one, the strings pointed to by argv1 through argv[argc-1] represent the program parameters.
— The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination
so, in short, adding the const is illegal and probably technically not possible (depending on the compiler)
Checking the standard you see the following rules: (ISO/IEC 9899:TC3), go to 5.1.2.2.1
|
70,931,404 | 70,931,653 | If we convert a value with one constructor, will there also be copy constructor needed to copy the newly created temp object? | I am having a trouble understanding the topic, and so it might be a stupid question but I am still wondering:
When we have a function, for example:
void func(const StringClass & param1, const StringClass & param2);
And then we pass to the function for example, a C string:
func("test", test);
Where "test" is a C string and test is an object of our StringClass.
And let's say our StringClass has defined a copy constructor and also a conversion constructor which can convert our "test" C string into a StringClass object. I have tested it already and what I have seen is that, that there is only conversion happening and not copying, and for the other object there is only assignment which I understand, since we pass it by reference. If our function is declared like this:
void func(const StringClass param1, const StringClass param2);
And we still pass previous arguments func("test", test), then the first argument gets converted, but no copy constructor is invoked. And for the second parameter copy constructor is invoked.
But my question is - will it always be like that? I mean, can other compiler treat it like that: convert the "test" C string into a StringClass object and then use the copy constructor to copy the temp object to param argument inside the function, or a conversion is enough since it creates a temp object anyways, so it won't differ between compilers?
| As a first hint you can add a copy constructor that prints something to see if it gets called:
#include <iostream>
struct foo {
template <size_t n>
foo(const char(&str)[n]){
std::cout << "converting constructor\n";
}
foo(const foo& f){
std::cout << "copy constructor\n";
}
};
void bar(foo){}
int main() {
bar("asdf");
}
Output is:
converting constructor
No copy constructor is called in this example. This is only a hint, because it is the output with one specific compiler and one specific C++ standard. However, once a foo has been created by calling the converting constructor, there is no reason to call the copy constructor. The string literal "asdf" is converted to a foo and thats it. There is no additional copy in the code, hence no compiler should create another copy.
|
70,931,587 | 70,931,764 | How to initialize std::array member in constructor initialization list when the size of the array is a template parameter | In the following example, I need to initialize the std::array in the A::A(H h) constructor initializer list (because class H doesn't have a default constructor), but I can't do it with an initializer list since the array size is a template parameter.
Is there a way around this?
#include <array>
using namespace std;
struct Hash {
const vector<int> &data;
Hash(const vector<int> &data)
: data(data) {
}
uint64_t operator()(int id) const {
return data[id];
}
};
template <class H, size_t N>
class A {
public:
A(H h) {
}
std::array<H, N> hashes;
};
int main () {
vector<int> data{1, 2, 3, 4};
A<Hash, 4> a{Hash(data)};
}
| std::index_sequence was provided in order to simplify the metaprogramming task of creating and expanding a pack whose size is not fixed. Use std::make_index_sequence and delegate the construction to some private constructor that deduces the pack:
A(H h) : A(h, std::make_index_sequence<N>{}) {}
template <std::size_t... i>
A(H h, std::index_sequence<i...>) : hashes{((void)i, h)...} {}
Here, ((void)i, h) is a comma expression that evaluates to h, but since we mentioned the pack i inside it, it's eligible to be expanded using .... The result is N copies of h (one for each element of i). This expansion occurs inside a braced-init-list, so the result is a braced-init-list contaning N copies of h, which will then initialize the hashes member.
|
70,932,394 | 70,932,465 | Is Big-O Notation also calculated from the functions used? | I'm learning about Big-O Notation and algorithms to improve my interview skills, but I don't quite understand how to get the time complexity.
Suppose I want to sum all the elements of the following list.
std::vector<int> myList = {1,2,3,4,5} ;
Case 1:
int sum = 0;
for (int it: myList)
{
sum += it;
}
Case 2:
int sum = std::accumulate(std::begin(myList), std::end(myList), 0);
Case 1 is O(N), and case 2 is apparently O(1), but I'm sure those functions do some kind of iteration, so the question is whether Big-O notation is calculated only from of the written code of that block or also of the functions used.
| If you talk about big-O, you have to talk in respect of some unit of data being processed. Both your case 1 and case 2 are O(N) where N is the number of items in the container: the unit is an int.
You tend to want the unit - and N to be the count of - the thing that's likely to grow/vary most in your program. For example, if you're talking about processing names in phonebooks, then the number of names should be N; even though the length of individual names is also somewhat variable, there's no expected pattern of increasing average name length as your program handles larger phonebooks.
Similarly, if your program had to handle an arbitrary number of containers that tended to be roughly the same length, then your unit might be a container, and then you could think of your code - case 1 and case 2 - as being big-O O(1) with respect to the number of containers, because whether there are 0, 1, 10 or a million other containers lying around someone in your program, you're only processing the one - myList. But, any individual accumulate call is O(N) with respect to any individual container's ints.
|
70,932,785 | 70,932,841 | I have been trying both write and read a file, but have been unable to | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
fstream a_file_that_will_be_working_with("storage.txt");
if (a_file_that_will_be_working_with.is_open()) {
cout << "is open";
}
else
{
cout << "is not open";
}
a_file_that_will_be_working_with << "first text" << endl;
a_file_that_will_be_working_with << "second text" << endl;
while (a_file_that_will_be_working_with)
{
// read stuff from the file into a string and print it
string strInput;
a_file_that_will_be_working_with >> strInput;
cout << strInput << '\n';
}
return 0;
}
What have I done wrong?
When I use ifstream to read from a file it works, but it doesnt for fstream, I thought fstream is both ofstream and ifstream combined.
| See https://en.cppreference.com/w/cpp/io/basic_fstream for an example.
You need to "rewind" the file to read just written stuff (s.seekp(0);).
|
70,932,913 | 70,933,106 | Type trait to identify classes derived from a CRTP class | I am looking to implement the function is_type_of_v, able to identify the templated instances of type Skill. Please, see the main function in source code below to fully understand the request. It is harder to explain by words than by code.
The solution should work in VS 2017 under c++17. The next link contains the example: https://godbolt.org/z/4x3xoh1Pb
#include <iostream>
#include <type_traits>
template<class T>
struct Base
{
private:
constexpr Base() = default;
friend T;
};
struct Derived1 : Base<Derived1>
{
};
struct Derived2 : Base<Derived2>
{
};
template<class T, class F, int... Ints>
struct Skill : T
{
};
int main()
{
Skill<Derived1, std::equal_to<int>, 1, 2> object1;
Skill<Derived2, std::equal_to<int>, 3> object2;
Derived1 other;
constexpr auto res1 = is_type_of_v<Skill, decltype(object1)>;//Must be true
constexpr auto res2 = is_type_of_v<Skill, decltype(object2)>;//Must be true
constexpr auto res3 = is_type_of_v<Skill, decltype(other)>;//Must be false
}
| For Skill, you can write something as
template <template <typename, typename, auto...> class, typename>
struct is_type_of : public std::false_type
{};
template <template <typename, typename, auto...> class C,
typename T1, typename T2, auto ... Is>
struct is_type_of<C, C<T1, T2, Is...>> : public std::true_type
{};
template <template <typename, typename, auto...> class C, typename T>
constexpr auto is_type_of_v = is_type_of<C, T>::value;
so you can verify that
static_assert( true == is_type_of_v<Skill, decltype(object1)> );
static_assert( true == is_type_of_v<Skill, decltype(object2)> );
static_assert( false == is_type_of_v<Skill, decltype(other)> );
Unfortunately this solution works only for template-template parameters receiving a couple of typename, before, and a variadic list of values, after.
I don't think it's possible (C++17 but also C++20) a generic solution for a generic template-template parameter in first position.
And before C++17 (C++11 and C++14) is even worse, because you can't use auto... for values.
|
70,932,917 | 70,932,965 | scanf skipping string with a defined size with a proceeding space | I'm trying to read 3 different strings of max 15 characters each. When I try to read them with scanf("%s %s %s", a, b, c), only the last one is picked up (I'm asuming the spaces between every string has something to do with this).
#include <iostream>
#include <string.h>
using namespace std;
#define DIM 15
int main()
{
char a[DIM], b[DIM], c[DIM];
scanf("%s %s %s", a,b,c);
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << "Cadenes introduides: " << a << " " << b << " " << c << endl;
}
the input is CadenaDe15chars CadenaDe15chars CadenaDe15chars
And I'm only seeing
CadenaDe15chars
Cadenes introduides: CadenaDe15chars
when the actual output should be
CadenaDe15chars
CadenaDe15chars
CadenaDe15chars
Cadenes introduides: CadenaDe15chars CadenaDe15chars CadenaDe15chars
I'm kinda new to c++ so I don't really know how to make scanf ignore the whitespace, I've found examples with strings delimited by a new line \n, but not with a space.
| This call
scanf("%s %s %s", a,b,c);
invokes undefined behavior because at least this input "CadenaDe15chars" contains 15 characters. So the appended terminating zero character '\0' will be written by the function outside the corresponding array used as an argument.
You should at least declare the macro constant like
#define DIM 16
to reserve space in the arrays for potentially appended zero character.
|
70,933,076 | 70,943,808 | Access UI components in QT by entering the name of the component? | I have a lot of ui components in my .ui file.
They have a similar name e.g analogRead0, analogRead1, analogRead2 and they have the same data type.
Is it possible for me to acces these fields inside the .ui file by using only the name?
I was thinking of I can make an instance of an object by just entering the name of the object, and not the class. Is that possible in QT?
For example, instead of writing
DoubleSpinBox *mySpinBox0 = ui->analogDifferentialInput0MaxDoubleSpinBox;
DoubleSpinBox *mySpinBox1 = ui->analogDifferentialInput1MaxDoubleSpinBox;
DoubleSpinBox *mySpinBox2 = ui->analogDifferentialInput2MaxDoubleSpinBox;
DoubleSpinBox *mySpinBox3 = ui->analogDifferentialInput3MaxDoubleSpinBox;
..
..
..
DoubleSpinBox *mySpinBoxN = ui->analogDifferentialInputNMaxDoubleSpinBox;
I can access all these DoubleSpinBoxes by entering the name analogDifferentialInput + a number + MaxDoubleSpinBox?
| If you set the object name of the element in the Designer, then you can directly access them via findChild (once you have set up the ui...)
Here is an example, where I change the text for my 3 QPushButtons
ui->setupUi(this);
for(int i = 1; i <= 3; ++i){
auto btn = findChild<QPushButton*>("button"+QString::number(i));
if(btn)
btn->setText("newName"+QString::number(i));
}
|
70,933,384 | 70,934,176 | pybind11 - Return a shared_ptr of std::vector | I have a member variable that stores a std::shared_ptr of std::vector<uint32_t>. I want to create a Python binding for test_func2() so that I can access that vector without any additional copy. Here is a skeleton code.
#include <vector>
#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
class TestLoader
{
private:
std::shared_ptr<std::vector<uint32_t>> tileData;
public:
TestLoader();
~TestLoader();
void test_func1();
std::shared_ptr<std::vector<uint32_t>> test_func2() const;
};
void TestLoader::test_func1() {
tileData = std::make_shared<std::vector<uint32_t>>(100000000);
for(auto &x: *tileData){ x = 1;}
}
std::shared_ptr<std::vector<uint32_t>> TestLoader::test_func2() const{
return tileData;
}
The interface code is like the following:
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
PYBIND11_MODULE(fltest_lib, m) {
py::class_<TestLoader, std::shared_ptr<TestLoader>>(m, "TestLoader")
.def(py::init<const std::string &>())
.def("test_func1", &TestLoader::test_func1)
.def("test_func2", &TestLoader::test_func2, py::return_value_policy::reference_internal);
}
However, this does not compile and I get a long error message. One particular line is the following:
/home/samee/fl_test/lib/pybind11/include/pybind11/cast.h:653:61: error: static assertion failed: Holder classes are only supported for custom types
653 | static_assert(std::is_base_of<base, type_caster<type>>::value,
| ^~~~~
Any help to circumvent this will be really helpful.
| According to this issue, it doesn't work because std::vector<uint32_t> is not converted to a python type. So, you will have to return the dereferenced vector. To avoid copies, you can use PYBIND11_MAKE_OPAQUE
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include "test_loader.h"
namespace py = pybind11;
PYBIND11_MAKE_OPAQUE(std::vector<uint32_t>);
PYBIND11_MODULE(fltest_lib, m) {
py::bind_vector<std::vector<uint32_t>>(m, "VectorUInt32");
py::class_<TestLoader, std::shared_ptr<TestLoader>>(m, "TestLoader")
.def(py::init())
.def("test_func1", &TestLoader::test_func1)
.def("test_func2",
[](const TestLoader& tl) -> const std::vector<uint32_t>& {
return *tl.test_func2();
}, py::return_value_policy::reference_internal);
}
|
70,933,410 | 70,944,248 | wxWidgets 3.1.5 MSW - HiDPI scaling problems causing controls to have the incorrect size | Information about my setup
wxWidgets: 3.1.5 (also tried the latest source from github)
wxWidgets: built using gcc-11.2 under msys2 (ucrt64)
Windows 10 Application: build using gcc-11.2 under msys2 (ucrt64)
Monitor native resoultion: 3840 x 2160
IDE: Eclipse 2021-09
My Problem
If I build my application and link against a resource file that is not using a HiDPI aware manifest then everything works correctly but the fonts are, as one would expect, pixelated. However, once I link with a HiDPI aware resource file then the controls are not resized proportionally with their associated text. Please see the following screenshots.
The image above shows the test wxFrame being rendered without a HiDPI aware resource file. The monitor scaling was 200%. As you can see, the wxFrame has rendered correctly.
The image above shows the test wxFrame being rendered without a HiDPI aware resource file. The monitor scaling was 350%. As you can see, (aside from the blurry text) the wxFrame has rendered correctly..
The image above shows the test wxFrame being rendered with a HiDPI aware resource file. The monitor scaling was 200%. As you can see, the wxFrame has rendered badly. This wxFrame renders correctly at 100% scale.
Here is a minimal fully functional code sample to demonstrate my problem.
#include <wx/wx.h>
#include <wx/frame.h>
#include <wx/sizer.h>
#include <wx/button.h>
class HiDPI_Test: public wxFrame
{
public:
HiDPI_Test() :
wxFrame(NULL, wxID_ANY, "HiDPI Test")
{
wxBoxSizer *sizer_master = new wxBoxSizer(wxHORIZONTAL);
m_btn_1 = new wxButton(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);
m_btn_1->SetMinSize(wxSize(-1, 30));
m_btn_1->SetMaxSize(wxSize(120, 30));
m_btn_1->SetLabel("Button Label Test");
m_btn_2 = new wxButton(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);
m_btn_2->SetMinSize(wxSize(-1, 30));
m_btn_2->SetMaxSize(wxSize(120, 30));
m_btn_2->SetLabel("Button Label Test");
sizer_master->Add(m_btn_1, 0, wxALL | wxEXPAND, 0);
sizer_master->Add(m_btn_2, 0, wxALL | wxEXPAND, 0);
this->SetSizerAndFit(sizer_master);
this->Layout();
this->Centre(wxBOTH);
}
private:
wxButton *m_btn_1, *m_btn_2;
};
class HiDPI: public wxApp
{
public:
bool OnInit() override
{
HiDPI_Test *mainApp = new HiDPI_Test();
mainApp->Show();
return true;
}
};
wxIMPLEMENT_APP(HiDPI);
The calls to SetMinSize() and SetMaxSize() are vital to my overall UI design.
I built the wxWidgets resource file by using the following:
windres --use-temp-file -ires.rc -ores.o -I/home/user/resource -DwxUSE_DPI_AWARE_MANIFEST=2
I then pass the resulting object file to the linker when building my application.
It's important to add that my application renders correctly on wxWidgets/GTK3 (Linux) and wxWidgets macOS/Cocoa. That is to say, it works correctly (without pixelated fonts) on macOS and Linux at any scale value.
Does anybody have any idea why my application is not rendering correctly when I use a HiDPI aware resource file on Windows 10?
| It's a pretty bad idea to use sizes in pixels in general, as this doesn't take the current font size into account, and so using dialog units or just the result of GetTextExtent("something") would be better.
But if you absolutely want to use pixels, you need to at least convert them to the proper units using FromDIP(), see HiDPI overview in the manual for more information.
And if you use
m_btn_1->SetMinSize(FromDIP(wxSize(-1, 30)));
m_btn_1->SetMaxSize(FromDIP(wxSize(120, 30)));
your code works as expected in 200% scaling, at least with the current master (I think that this should work with 3.1.5 too, but there have been tons of high DPI-related improvements since then, so I strongly recommend using master/3.1.6 when it is released soon if you care about high DPI support).
|
70,933,676 | 70,934,388 | Using sockets to send a string from a C++ client on one computer to a Python server on another. Getting `send: Bad file descriptor` | I'm trying to send a string from a C++ client on one computer to a Python server on another computer.
My error is send: Bad file descriptor
The Python server is killed if it is contacted by the client but it doesn't receive a string. While the Python server is running it does end the program when I attempt to send the string from the C++ client. So I know the server is being reached by the client when I execute it.
I am able to send strings to the server from the C++ client's computer with a Python client script. Since it's not a basic problem with the server I don't think this and other answers apply to my problem.
On the Python script I have tried changing this number.
s.listen(11)
Here is the Python server
import os
import sys
import socket
s=socket.socket()
host='192.168.0.101'
port=12003
s.bind((host,port))
s.listen(11)
while True:
c, addr=s.accept()
content=c.recv(1024).decode('utf-8')
print(content)
if not content:
break
Here is the C++ client
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
#define ADDR "192.168.0.101"
#define PORT "12003"
void sendall(int socket, char *bytes, int length)
{
int n = 0, total = 0;
while (total < length) {
n = send(socket, bytes + total, total-length, 0);
if (n == -1) {
perror("send");
exit(1);
}
total += n;
}
}
int main()
{
struct addrinfo hints = {0}, *addr = NULL;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(ADDR, PORT, &hints, &addr);
if (status != 0) {
fprintf(stderr, "getaddrinfo()\n");
exit(1);
}
int sock = -1;
{
struct addrinfo *p = NULL;
for (p = addr; p != NULL; p = addr->ai_next) {
int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sock == -1) {
continue;
}
if (connect(sock, p->ai_addr, p->ai_addrlen) != -1) {
break;
}
close(sock);
}
if (p == NULL) {
fprintf(stderr, "connect(), socket()\n");
exit(1);
}
freeaddrinfo(addr);
/* Do whatever. */
sendall(sock, "Hello, World", 12);
/* Do whatever. */
}
close(sock);
return 0;
}
UPDATE:
In the client there was an unessacary int in front of sock = socket...
I removed it and now I'm getting an error on the server side when I send the string that reads..
$ python server.py
Traceback (most recent call last):
File "/home/computer/server.py", line 35, in <module>
content=c.recv(1024).decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 29: invalid start byte
| You're redeclaring the sock variable in the for loop, so the value of sock when you call sendall() is the original -1. Change
int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
to
sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
so it assigns the outer variable.
|
70,933,726 | 70,934,355 | C++ can't compile code using PROCESSENTRY32 | I'm trying to compile simple lines of code but I'm getting C2664 Error code.
#include <TlHelp32.h>
PROCESSENTRY32 pe32 = { 0 };
if (wcscmp(pe32.something, something) == 0)
Error:
int wcscmp(const wchar_t *,const wchar_t *)': cannot convert argument 1 from 'CHAR [260]' to 'const wchar_t
The definition of wcscmp() is:
_Check_return_
_ACRTIMP int __cdecl wcscmp(
_In_z_ wchar_t const* _String1,
_In_z_ wchar_t const* _String2
);
I can't use PROCESSENTRY32W because then Process32First() breaks because it needs PROCESSENTRY32.
How could I change this to make it compilable?
| Use PROCESSENTRY32W instead of PROCESSENTRY32.
Use Process32FirstW instead of Process32First.
|
70,933,755 | 70,947,008 | Vector of mutex to synchronize access to vector cells | I wrote code to do some parallel operations on a vector, my goal is to protect a single cell of a vector so other cells can be accessed in parallel, so I tried to use a vector of mutex of the same size of the other vector
vector<int> myIntVec(n,0);
vector<mutex> mtxVec(n);
then the critical section, each thread executes this (goal is to mark seen cells)
for (i of something)
{
mtxVec[i].lock();
if (myIntVec[i] == 0 ){
myIntVec[i]++;
mtxVec[i].unlock();
}
else
mtxVec[i].unlock();
}
no other operations on these 2 vectors.
but doing some tests, what i got is that myIntVec cells contain numbers greater than 1, when they should contain at least 1.
What am I missing?
| In order you share this link https://codecollab.io/@proj/InternetDivisionTrucks# in comments. Seems that you try to protect vector<bool> visited(nn); by mutexes vector<mutex> vis_lock(nn);. As i know there is special implementation for std::vector<bool> in which bools stored packed https://en.cppreference.com/w/cpp/container/vector_bool. so when it accesses to i-th element near elements also will be touched and with concurrency it's explodes because of accessing in one byte of memory at the same time. try replace std::vector<bool> to std::vector<char> or std::vector<int>
|
70,933,910 | 70,933,953 | Just started out learning to code and it won't execute | So i am watching youtube tutroials and trying to write hello world but i am already failing
Here is an screenshot
enter image description here
Why won't it execute?
Any help would be really welcome (From Belgium so excuse my broken english)
| You're on Windows. Instead of a.out, the default name for gcc is a.exe. You can see that in the directory listing on the left.
|
70,934,469 | 70,936,291 | How to copy memory from an SSBO to CPU without getting a buffer performance warning? | I'm using a compute shader to generate terrain values. I create my SSBO, I dispatch the compute shader and then I want to copy the values stored in the SSBO into CPU side memory so that I can use it further on. The code works perfectly, I copy into my CPU side buffer with no issues, however I get a performance warning, which made me think I am not copying the compute shader memory correctly. I get the same issue when using both glGetBufferSubData and glMapBuffer. Here is the warning:
Debug message (131186): Buffer performance warning: Buffer object 1 (bound to GL_SHADER_STORAGE_BUFFER, and GL_SHADER_STORAGE_BUFFER (3), usage hint is GL_STREAM_READ) is being copied/moved from VIDEO memory to HOST memory.
Source: API
Type: Performance
Severity: medium
Here is the offending code
void Terrain::generate()
{
glGenBuffers(1, &mSSBO);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, mSSBO);
glBufferData(GL_SHADER_STORAGE_BUFFER, (mSize*mSize*mSize)*sizeof(float), mData, GL_STREAM_READ);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, mSSBO);
mGenerator.use();
mGenerator.setInt("tSize", mSize);
glDispatchCompute(mSize, mSize, mSize);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
// Line that triggers the warning
glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, (mSize*mSize*mSize)*sizeof(float), mData);
}
What is the correct way to copy memory from an SSBO to the CPU without incurring performance penalties + warnings?
| Figured out my own answer in the docs, I have switched to using immutable storage. Instead of using glBufferData I instead am using glBufferStorage
So
glBufferData(GL_SHADER_STORAGE_BUFFER, (mSize*mSize*mSize)*sizeof(float), mData, GL_STREAM_READ);
becomes
glBufferStorage(GL_SHADER_STORAGE_BUFFER, (mSize*mSize*mSize)*sizeof(float), NULL, GL_CLIENT_STORAGE_BIT | GL_MAP_READ_BIT);
and I have given it explicit flags to let me map it and a hint that the implementation of the buffer storage should come from client memory. Now when I call
glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, (mSize*mSize*mSize)*sizeof(float), mData);
I don't get hit with any performance warnings
|
70,934,723 | 70,938,279 | REGEX for first and last names involving dots (.) | I want to be able to get the first and last name always starting with a capital letter... This I've already achieved in a post here on stackoverflow, it's this one:
[A-Z][a-z]+([ ][A-Z][a-z]+)*
However, according to my business rules, I need to be able to validate names and surnames with only the first letter of the first and last name followed by a period and space, or only by a period if the period is at the end of the string.
For example:
"John Doe" -> true
"John D." -> true
"John D. D." -> true
"John D. D. " -> false (as here we have a space after the last dot in S.)
"John D. D." -> false (as here two spaces after the first . in B.)
"John D.oe" -> false (as here we have a point not being followed by a space)
In order to get around this situation, I wrote the following code that simply means a dot ( .) followed by a space ( ), however I don't know what else to do and I don't know how to introduce this code there in the REGEX specified above...
([.][\s]?)
The regex I came up with is incomplete and does not produce the result I am seeking for:
^[A-Z](?:[a-z]|[\.])+(?:[ ][A-Z](?:[a-z]|[\.])+)*$
John D.oe -> matches true, however it should not as there is supposed to have a space after every dot...
Does someone out there know how can I solve this issue?
| (?:[a-z]|[\.])+ is equivalent to [a-z.]+ (no need for dot to be escaped here)
You want [A-Z](?:[a-z]+|\.) (not sure if + should be *, can name have only one letter (without abbreviation)).
Result would be:
^[A-Z](?:\.|[a-z]*)(?: [A-Z](?:\.|[a-z]*))+$
Demo
"John Doe" // true
"John D." // true
"John D. D." // true
"John D. D. "
"John D. D."
"John D.oe"
"J. Doe" // true
"J. D." // true
"John DDoe"
|
70,934,849 | 70,934,897 | C++ Polymorphism: How to write function to accept any abstract class implementation | I want to be able to pass whatever implementation of an abstract class into a function defined in a separate file, so that I can use the functionality for other projects and write the child class however it suits me.
main.cpp:
#include "my_process.h"
struct my_guy : V2 {
my_guy(float x, float y)
: V2(x, y) { }
void double_me() override {
x *= 2.f;
y *= 2.f;
}
};
int main() {
process(my_guy(1.f,2.f));
return 0;
}
my_process.h:
#pragma once
#include <iostream>
struct V2 {
float x, y;
V2(float x, float y) {
this->x = x;
this->y = y;
}
virtual void double_me() { }
};
std::ostream& operator<<(std::ostream& output_stream, V2 vector) {
output_stream << vector.x << ", " << vector.y;
return output_stream;
}
void process(V2 vector) {
vector.double_me();
std::cout << vector << std::endl;
}
The above example prints 1,2 instead of the expected 2,4
| Your function process currently passes is parameter by value.
Because you currently pass by value, a new V2 value is created as the parameter, which will always have type V2 and act like a V2.
Change it to take a reference to whatever object is passed to it:
void process(V2 & vector)
Since the parameter is also modified, you will need to pass a named variable to convince the C++ compiler that you aren't accidentally modifying a temporary.
int main() {
auto guy = my_guy(1.f,2.f);
process(guy);
}
|
70,934,858 | 70,935,745 | Program Exits Unintentionally When Entering Elements in Array-Based Queue and Does not Continue to Compile the Rest of the Program | I am having this bug where my program unexpectedly exits after entering elements for my array-based queue. It is supposed to run like so:
~ User enters the number of elements they want in the queue (in this case, the size of the array).
~ After user enters their elements, a menu with the methods' corresponding number should pop up.
~ User picks the number corresponding to what method they want to run, then that specific
method executes.
~ Then the program is supposed to exit.
The methods that I have included manipulate the queue such as adding elements, deletion, printing the queue, counting the index, clearing the queue. As I said, the program exits only when two elements are entered even though I set the size to ten. It does not continue compilation. I suspect that the bug is somewhere in the AddToEnd() method, which is the first constructor in the program, but I do not get any syntax errors whatsoever. Let me know if I could provide more information in relation to the bug. Code is below:
#include <iostream>
using namespace std;
// AddToEnd - at the end of the queue
// DeleteFront - delete element from the front of the queues
// ShowQueue - show all elements of queue
// CountElements - print number of elements
// Clear - initializes the queue
int queue[10], front = -1, back = -1, limit, item;
void AddToEnd () {
cout << "Enter element to add:\n";
cin >> item;
// variable for the element to add
int add = limit - 1;
// if the back = add, queue is filled
// otherwise set the front to 0 and increment the back
if (back == add) {
cout << "queue is filled up" << endl;
} else {
if (front == -1 && back == -1) {
front = 0;
}
back++;
queue[back] = item;
}
}
void DeleteFront () {
if (front == -1) {
cout << "queue is empty\n";
} else {
// item is chosen and front is incremented or set to 0
item = queue[front];
if (front == back) {
back--;
front--;
} else {
front++;
}
}
}
void ShowQueue () {
cout << "Here are the elements in the queue:\n";
for (int i = front; i<= back; i++) {
cout << queue[i] << " " << endl;
}
}
void CountElements () {
if(front == -1) {
cout << "index is zero" << endl;
} else {
int index = 0;
for (int i = front; i <= back; i++) {
index++;
cout << "Index contains " << index << " elements." << endl;
}
}
}
void Clear () {
// iterate through array and set index to 0
for (int i = 0; i < limit; i++) {
queue[i] = 0;
}
}
int main () {
int UserChoice = 0;
cout << "Enter the size of the queue (max is 10 elements)." << endl;
cin >> limit;
cout << "\n1. ADD\n 2. DELETE\n 3. SHOW THE QUEUE\n 4. COUNT THE ELEMENTS\n 5. CLEAR\n";
cin >> UserChoice;
switch (UserChoice) {
case 1: AddToEnd();
break;
case 2: DeleteFront();
break;
case 3: ShowQueue();
break;
case 4: CountElements();
break;
case 5: Clear();
break;
default: cout << "ERROR: Not an option." << endl;
break;
}
cin >> UserChoice;
return 0;
}
| As Johnny Mopp suggested, you should repeat the process of reading a user choice and handling that choice. The easiest way to do that is to surround the relevant code with a while loop, as shown below:
int main () {
int UserChoice = 0;
cout << "Enter the size of the queue (max is 10 elements)." << endl;
cin >> limit;
cout << "\n1. ADD\n 2. DELETE\n 3. SHOW THE QUEUE\n 4. COUNT THE ELEMENTS\n 5. CLEAR\n";
// Add an "infinite" loop.
// You can exit this loop with a break statement,
// return statement, or exit() function call
// instead of using a condition.
while (true) { // <-- Begin loop
cin >> UserChoice;
switch (UserChoice) {
case 1: AddToEnd();
break;
case 2: DeleteFront();
break;
case 3: ShowQueue();
break;
case 4: CountElements();
break;
case 5: Clear();
break;
// Add a case 6 as you mentioned in your comment
// that calls exit(0), so you can get out of your
// while loop.
default: cout << "ERROR: Not an option." << endl;
break;
}
// Since this will run at the top of the loop,
// you don't need it here.
// cin >> UserChoice;
} // <-- End loop
return 0;
}
Note that some professors don't like while (true) loops, so you may need to invent a simple bool running = true; flag and use it as your condition. Set it to false to cause the loop to stop repeating.
|
70,934,924 | 70,940,132 | Does `wil::com_ptr` overload operator &, aka "address of"? | I found this code snippet here.
wil::com_ptr<IStream> stream;
CHECK_FAILURE(SHCreateStreamOnFileEx(
L"assets/EdgeWebView2-80.jpg", STGM_READ, FILE_ATTRIBUTE_NORMAL,
FALSE, nullptr, &stream));
According to the manual of SHCreateStreamOnFileEx, the type of the last argument is supposed to be IStream **. However the code snippet passes a wil::com_ptr<IStream> * to the function instead of a IStream **. I'm wondering how it works. Does wil::com_ptr<IStream> overload operator & (aka "address of")?
By the way, I cannot find the online manual of wil::com_ptr. Is it the same as winrt::com_ptr struct template (C++/WinRT)? Thanks.
| The Windows Implementation Libraries (WIL) has its documentation published through its repository's wiki. The wil::com_ptr_t class template1 is described on the WinRT and COM wrappers page.
The section on Object management methods lists three class members that allow clients to get the address of the stored interface pointer:
T** addressof()
Returns the address of the internal pointer without releasing the current COM object. Do not use this for _Out_ parameters2 because it will leak the current COM object. For _Out_ parameters, use the & operator, which releases the current COM object before returning the address.
T** put()
Releases the current COM object and returns the address of the internal pointer. Use this method when passing the com_ptr_t as a _Out_ parameter.
T** operator&()
Same as put().
So to answer the literal question: Yes, wil::com_ptr_t does overload operator&() to return the address of the internal interface pointer after doing some housekeeping.
wil::com_ptr_t is unrelated to the winrt::com_ptr class template3, part of the C++/WinRT library. Neither of them are related to ATL's CComPtr or Visual Studio's _com_ptr_t. Those are the four official implementations, and while all of them have the same goal of automating lifetime management of COM objects they are subtly different in their implementations, with surprising consequences4.
The differences are in the following areas:
Constructors with an interface pointer argument
Implementations get to choose whether they assume ownership of the passed in interface pointer, or model shared ownership leaving the caller with the responsibility of Release()-ing the incoming interface pointer.
Assignment operators accepting an interface pointer
Same as above concerning the incoming pointer, with the added twist of having to handle the case where the instance is already holding an interface pointer. Implementations can:
Silently drop the currently held interface pointer (the fact that this is a bug doesn't mean that you won't see it)
Silently Release() the current interface prior to assigning the incoming interface pointer
Throw an exception in case the instance is holding an interface pointer
Retrieving the address of the raw interface pointer
Similar to the assignment above, the case where the smart pointer instance is already holding an interface needs to be handled, one way or another:
Silently drop the stored interface (e.g. addressof())
Silently Release() the current interface (e.g. put())
Throw an exception in case the stored pointer is not a nullptr
If you decide to use a COM smart pointer implementation, make sure you have a firm grasp on its semantics. The same literal piece of C++ code will potentially behave differently depending on the library in use.
1 wil::com_ptr is an alias template for wil::com_ptr_t with the err_policy template argument set to err_exception_policy.
2 The snippet in the question could have safely passed stream.addressof() even though ppstm is marked as an _Out_ parameter. I'm guessing that the author used operator&() instead for consistency, readability, and maintainability.
3 While the WIL and C++/WinRT are independent libraries they can interoperate with surprisingly little effort.
4 We're using a smart pointer, so we can't possibly be the source of the leak
|
70,935,031 | 70,935,072 | Shall the caller deallocate the return value of `SHCreateMemStream`? | This is a dumb question, but I'm sorry I cannot find this information in the online manual of the function. I came from Linux realm. I'm not familiar with convention in Windows world.
All examples I found use smart pointer, e.g. wil::com_ptr, but GCC obviously doesn't provide those tools. Shall I call Release on the return value? Or leave it alone? Thanks.
| IStream is built on top of the classic COM IUnknown interface, and as such any COM interface pointer returned from a function has had IUnknown::AddRef() called on it, and so you must call IUnknown::Release() when you're done using the interface pointer or else you'll leak memory.
GCC obviously doesn't provide those tools
Just in case you needed a reason to use cl on Windows and the Windows SDK, you found it.
|
70,935,437 | 70,935,490 | Syntax for pointers to a structure | When declaring a pointer to a struct, both the following code snippets compile without error:
A)
struct Foo
{
int data;
Foo* temp; // line in question
}
B)
struct Foo
{
int data;
struct Foo* temp; //line in question
}
What is the significance to repeating the word "struct" in the declaration of the struct pointer (as in (B))? Are there any differences compared to not doing so (as in (A))?
Thank you for your consideration.
| In C, struct keyword must be used for declaring structure variables, but it is optional in C++.
For example, consider the following examples:
struct Foo
{
int data;
Foo* temp; // Error in C, struct must be there. Works in C++
};
int main()
{
Foo a; // Error in C, struct must be there. Works in C++
return 0;
}
Example 2
struct Foo
{
int data;
struct Foo* temp; // Works in both C and C++
};
int main()
{
struct Foo a; // Works in both C and C++
return 0;
}
In the above examples, temp is a data member that is a pointer to non-const Foo.
|
70,935,717 | 70,937,435 | ALLEGRO5 change pixel color of text based on background | First attempt:
void Tower::_DrawHealthBarText(std::string text, int x, int y, ALLEGRO_FONT* font)
{
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
ALLEGRO_BITMAP* bmp = al_create_bitmap(196, 17);
int bmpIndex[196][17] = { };
al_set_target_bitmap(bmp);
al_draw_rectangle(5, 20, 200, 20 + 15, al_map_rgb(255, 255, 255), 1.0f);
al_draw_filled_rectangle(5, 20, 5 - 195.0f + ((195.0f / _player->playerMaxHealth) * _player->playerHealth) + 195.0f, 20 + 15, al_map_rgb(255, 255, 255));
al_draw_filled_rectangle(4, 19, 201, 20 + 15 + 1, al_map_rgb(0, 0, 0));
for (int x = 0; x < 196; x++)
{
for (int y = 0; y < 17; y++)
{
unsigned char r, g, b;
al_unmap_rgb(al_get_pixel(bmp, x, y), &r, &g, &b);
if ((r + g + b) / 3 == 255)
{
bmpIndex[x][y] = 0;
}
else if ((r + g + b) / 3 == 0)
{
bmpIndex[x][y] = 1;
}
}
}
// Clear to transparent background
al_clear_to_color(rgba(0, 0, 0, 0));
al_draw_text(getFont(12), al_map_rgb(255, 255, 255), 0, 0, 0, text.c_str());
al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
al_set_target_backbuffer(g_Window);
al_draw_bitmap(bmp, x, y, 0);
al_destroy_bitmap(bmp);
}
Second attempt:
int bmpIndex[196][17] = { };
void Tower::_DrawHealthBarText(std::string text, int _x, int _y, ALLEGRO_FONT* font)
{
al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
al_hold_bitmap_drawing(true);
for (int x = 0; x < 196; x++)
{
for (int y = 0; y < 17; y++)
{
unsigned char r, g, b;
al_unmap_rgb(al_get_pixel(al_get_backbuffer(g_Window), _x + x, _y + y), &r, &g, &b);
if ((r + g + b) / 3 == 255)
{
bmpIndex[x][y] = 0;
}
else if ((r + g + b) / 3 == 0)
{
bmpIndex[x][y] = 1;
}
}
}
al_hold_bitmap_drawing(false);
al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
}
I've googled and tried my own code as you can see above... However using this multi-leveled loop is very slow. My thought was to use a shader but I haven't the slightest clue how to use them yet.
I want the text to change color based off the background of where the text is located...
Basically it's a health bar and I want to show the text ontop of the health bar and change colors based on the background... If the background is black, the corresponding pixels are changed to white. Subsequently if the background pixels are white, the pixels of the text change to black.
like this:
photoshop render concept
MY FIX:
// Hacky bullshit
_DrawText(std::to_string((int)_player->playerHealth), 5 + ((195.0f - al_get_text_width(getFont(12), std::to_string((int)_player->playerHealth).c_str())) / 2), py + 18, getFont(12), al_map_rgb(255, 0, 0), 0);
al_draw_rectangle(px + 5, py + 20, px + 200, py + 20 + 15, al_map_rgb(255, 255, 255), 1.0f);
ALLEGRO_BITMAP* bmp = al_create_bitmap(200, 20);
{
al_set_target_bitmap(bmp);
al_draw_filled_rectangle(5, 0, 5 + ((195.0f / _player->playerMaxHealth) * _player->playerHealth), 15, al_map_rgb(255, 255, 255));
_DrawText(std::to_string((int)_player->playerHealth), 5 + ((195.0f - al_get_text_width(getFont(12), std::to_string((int)_player->playerHealth).c_str())) / 2), -2, getFont(12), al_map_rgb(155, 0, 0), 0);
al_set_target_backbuffer(g_Window);
al_draw_bitmap_region(bmp, 0, 0, 5 + ((195.0f / _player->playerMaxHealth) * _player->playerHealth), 20, px, py + 20, 0);
}
al_destroy_bitmap(bmp);
| The simplest way is to use the clipping rectangle, a common feature of most graphics APIs. When you set the clipping rectangle, nothing can be drawn outside of it.
First, set the clipping rectangle to cover the white part of the progress bar. Draw your text in black.
Then, set the clipping rectangle to cover the black part of the progress bar. Draw your text in white, in the same position as it was drawn in black.
int x = 0, y = 0;
int bar_width = 196, bar_height = 17;
int bar_position = static_cast<int>(
bar_width * _player->playerHealth / _player->playerMaxHealth);
// Set the clipping rectangle so text only appears on the left
// side of the bar (which is white),
al_set_clipping_rectangle(x, y, bar_position, bar_height);
// Draw black text.
al_draw_text(getFont(12), al_map_rgb(0, 0, 0), x, y, 0, text.c_str());
// Set the clipping rectangle so text only appears on the right
// side of the bar (which is black).
al_set_clipping_rectangle(x + bar_position, y, bar_width - bar_position, bar_height);
// Draw white text in the same position as the black text.
al_draw_text(getFont(12), al_map_rgb(255, 255, 255), x, y, 0, text.c_str());
// Reset clipping rectangle so you can draw graphics as usual again.
al_reset_clipping_rectangle();
|
70,935,758 | 70,935,819 | Does the size of the element matter to the speed of std::sort? | Given that they have the same size, would a vector of an element of size 4 byte sort faster than an element of say 128 bytes? Do I have to index them and sort the indicies manually or does std::sort does it under the hood for me?
|
Given that they have the same size, would a vector of an element of size 4 byte sort faster than an element of say 128 bytes?
That depends on CPU architecture but it is quite possible and reasonable to expect that bigger objects would be sorted slower (assuming everything else is equal) as std::sort moves whole objects.
Do I have to index them and sort the indicies manually or does std::sort does it under the hood for me?
If you want to sort indexes instead of objects you need to do that explicitly - apply std::sort on container of indexes, not actual objects, but use comparator that uses actual objects where indexes point to. Again std::sort moves actual objects, in this case objects would be indexes.
For example:
struct BigObject {
int value;
// some other data that makes this object big
};
std::vector<BigObject> objects;
// objects is populated with data somehow
std::vector<std::size_t> indexes( objects.size() );
// fill indexes with values from 0 to N-1
std::iota( indexes.begin(), indexes.end(), 0 );
// sort indexes
std::sort( indexes.begin(), indexes.end(), [&objects]( size_t i1, size_t i2 )
{
return objects[i1].value < objects[i2].value;
} );
Now your indexes would be sorted in ascending order of value but objects container will be left intact.
|
70,937,314 | 70,937,426 | c++ passing json object by reference | In the below code, I am taking requests from a client, put them together on a json object on my server class and sending it to a pusher(directly connected to a website, putting my data in there so I can search data easily)
The code is working perfectly fine, but my manager said that I need to pass json by reference in this code, and I have no idea what to do.
On Server Class:
grpc::Status RouteGuideImpl::PubEvent(grpc::ServerContext *context,
const events::PubEventRequest *request,
events::PubEventResponse *response){
for(int i=0; i<request->event_size();i++){
nhollman::json object;
auto message = request->events(i);
object["uuid"]=message.uuid();
object["topic"]=message.type();
pusher.jsonCollector(obj);
}
...
}
On Pusher Class:
private:
nholmann::json queue = nlohmann::json::array();
public:
void Pusher::jsonCollector(nlohmann::json dump){
queue.push_back(dump);
}
void Pusher::curlPusher(){
std::string str = queue.dump();
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, str.data());
...
}
As much as I understand, I need to send the json object by reference. How can I do that?
| The simple answer is to change
void Pusher::jsonCollector(nlohmann::json dump)
to
void Pusher::jsonCollector(const nlohmann::json& dump)
(note that if this is inside the class then Pusher:: is a non-standard visual studio extension).
This will reduce the number of times the object is copied from 2 to 1 however you can avoid the copy completely by using std::move:
void Pusher::jsonCollector(nlohmann::json dump){
queue.push_back(std::move(dump));
}
And call it with:
pusher.jsonCollector(std::move(obj));
If you want to enforce this behaviour to ensure that callers of jsonCollector always use std::move you can change jsonCollector to:
void Pusher::jsonCollector(nlohmann::json&& dump){
queue.push_back(std::move(dump));
}
|
70,937,429 | 70,939,584 | Template arguement for comparator when passing priority queue to a function | I am new to C++ and still learning the concepts. I am trying to pass a priority queue with custom comparators to a templated function. I want to abstract the comparator type in priority queue template argument list when I pass it to the function in the function definition. Below is an example of what I am trying to do.
File1.h
struct my_comparator
{
bool operator()(const some_type* c1, const some_type* c2){
c1->property < c2->property;
}
another_funtion(….)
{
std::priority_queue<const some_type*, std::vector<const some_type*>, my_comparator> my_queue;
some_function(my_queue);
}
File2.h
some_function(std::priority_queue<const some_type*, std::vector<const some_type*>, comparator_type> queue_)
{
//implementation
}
I want to understand what to pass as the comparator type in the priority queue template of some_function definition, such that it can accept any custom comparator I define (adhering to the required format), in the file that is calling the function (which is File1.h in this case).
P.S: This is my first time posting here. Apologies in advance for any format mistakes.Thank you!
| It seems that you want to allow any comparator (on your custom type some_type) to be used. To that effect, you can simply use (I'm assuming that you indeed want to passs by value) :
template<class TComparator>
void some_function(std::priority_queue<const some_type*, std::vector<const some_type*>, TComparator> queue)
{
// ...
}
Then, let the compiler deduce your argument. Let say that you have two comparators my_comp1 and my_comp2, then you can have :
template<class TComparator>
using my_queue_t = std::priority_queue<const some_type*, std::vector<const some_type*>, TComparator>;
my_queue_t<my_comp1> q1;
my_queue_t<my_comp2> q2;
// Do something with them
some_function(q1);
some_function(q2);
The comparator type will be automatically deduced by the compiler. You can also have the template alias be separated to another file (near your type some_type for instance) and be used in both files.
|
70,937,488 | 70,937,586 | The meaning of the symbol ~ on an array when that array is not a class | I'm reading a C ++ code, the code has a line like this:
for(;;)
{
if(~theArray[i] & anotherCondition)
{
DoSomeThing();
}
}
For some values i code goes back to the beginning of the loop, what exactly does this expression ~
on array, do?
Can anybody help?
| ~ operator indicates bitwise complement.
Bitwise complement operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1.
For example:
35 = 00100011 (In Binary)
complement of 35 is
~ 00100011 = 11011100 which is equal to 220 (In decimal)
Please check below resources to learn more about it
Bitwise Operators
Bitwise Complement Operator
|
70,937,697 | 70,937,835 | Calculate three angle of triangle using three sides | I want to find three angle of a Triangle using Given three sides but it gives me 'nan' value.
I have tried law of cosines to find the angles but it ain't working. It gives 'nan' value.
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
using namespace std;
double findDegree(double setDegree)
{
return setDegree * M_PI / 180;
}
double findRadian(double setRadian)
{
return acos(setRadian);
}
int main()
{
cout << endl;
cout << "Give three sides of the triangle: ";
int a, b, c;
cin >> a >> b >> c;
double angleA, angleB, angleC, getRadian, getDegree;
angleA = ((b * b) + (c * c) - (a * a)) / 2 * b * c;
angleB = ((a * a) + (c * c) - (b * b)) / 2 * a * c;
angleC = ((a * a) + (b * b) - (c * c)) / 2 * a * b;
// A
getRadian = findRadian(angleA);
getDegree = findDegree(getRadian);
angleA = getDegree;
// B
getRadian = findRadian(angleB);
getDegree = findDegree(getRadian);
angleB = getDegree;
// A
getRadian = findRadian(angleC);
getDegree = findDegree(getRadian);
angleC = getDegree;
cout << "Angle A is: " << angleA << endl;
cout << "Angle B is: " << angleB << endl;
cout << "Angle C is: " << angleC << endl;
}
| Radian to degrees is "rad * 180 / pi", you're doing it the other way around in findDegree. Why are you doing it anyway?
You also need to put the denominator in parenthesis, for example:
angleA = ((b * b) + (c * c) - (a * a)) / (2 * b * c);
a, b, c should be double probably, as well.
|
70,938,112 | 70,938,940 | How to monitor processes on linux | When an executable is running on Linux, it generates processes, threads, I/O ... etc, and uses libraries from languages like C/C++, sometimes there might be timers in question, is it possible to monitor this? how can I get a deep dive into these software and processes and what is going on in the background?
I know this stuff is abstracted from me because I shouldn't be worrying about it as a regular user, but I'm curious to what would I see.
What I need to see are:
System calls for this process/thread.
Open/closed sockets.
Memory management and utilization, what block is being accessed.
Memory instructions.
If a process is depending on the results of another one.
If a process/thread terminates, why, and was it successful?
I/O operations and DB read/write if any.
| The different things you wanted to monitor may require different tools. All tools I will mention below have extensive manual pages where you can find exactly how to use them.
System calls for this process/thread.
The strace command does exactly this - it lists exactly which system calls are invoked by your program. The ltrace tool is similar, but focuses on calls to library functions - not just system calls (which involve the kernel).
Open/closed sockets.
The strace/ltrace commands will list among other things socket creation, but if you want to know which sockets are open - connected, listening, and so on - right now, there is the netstat utility, which lists all the connected (or with "-a", also listening) sockets in the system, and which process they belong to.
Memory management and utilization, what block is being accessed.
Memory instructions.
Again ltrace will let you see all malloc()/free() calls, but to see exactly what memory is being access where, you'll need a debugger, like gdb. The thing is that almost everything your program does will be a "memory instruction" so you'll need to know exactly what you are looking for, with breakpoints, tracepoints, single-stepping, and so on, and usually don't just want to see every memory access in your program.
If you don't want to find all memory accesses but rather are searching for bugs in this area - like accessing memory after it's freed and so on, there are tools that help you find those more easily. One of them called ASAN ("Address Sanitizer") is built into the C++ compiler, so you can build with it enabled and get messages on bad access patterns. Another one you can use is valgrind.
Finally, if by "memory utilization" you meant to just check how much memory your process or thread is using, well, both ps and top can tell you that.
If a process is depending on the results of another one.
If a process/thread terminates, why, and was it successful?
Various tools I mentioned like strace/ltrace will let you know when the process they follow exits. Any process can print the exit code of one of its sub-processes, but I'm not aware of a tool which can print the exit status of all processes in the system.
I/O operations
There is iostat that can give you periodic summaries of how much IO was done to each disk. netstat -s gives you network statistics so you can see how many network operations were done. vmstat gives you, among other things, statistics on IO caused by swap in/out (in case this is a problem in your case).
and DB read/write if any.
This depends on your DB, I guess, and how you monitor it.
|
70,938,946 | 70,939,155 | QSpinBox prevent the user from enternig thousand separators | In a QSpinBox, when the range is sufficient, the user is allowed to enter thousand separators.
Eg: 1.2.3.4 is a valid entry, en then fixup() just removes the dots. Resulting in 1234.
How can I prevent the user from entering thousand separators?
Previously I made something similar based on QLineEdit which uses validators.
But QAbstractSpinbox doesn't use QValidators. So I'm not sure how to proceed.
| Just override validate and reject input if contains undesired character.
It could be something like that:
QValidator::State MySpinBox::validate(QString &input, int &pos) const
{
if (input.contains(ThousandSeparator)) {
return QValidator::Invalid;
}
return QSpinBox::validate(input, pos);
}
Please do not be to greedy what user can and can't do, since to restrictive rules are annoying for the end user.
validate is called whenever content changes. fixup is called when value should be committed (widget losses focus or enter is pressed) and must be able to transform input from intermediate state to valid.
|
70,939,312 | 70,939,385 | Not able to connect in socket programming in C++ whereas in python, it works | I have a piece of code in python. It is related to client Socket programming. I want to get the NTRIP data from "www.rtk2go.com". The code written in python works well and serves the purpose.
import socket
import base64
server = "www.rtk2go.com"
port = "2101"
mountpoint = "leedgps"
username = ""
password = ""
def getHTTPBasicAuthString(username, password):
inputstring = username + ':' + password
pwd_bytes = base64.standard_b64encode(inputstring.encode("utf-8"))
pwd = pwd_bytes.decode("utf-8").replace('\n', '')
return pwd
pwd = getHTTPBasicAuthString(username, password)
print(pwd)
header = "GET /{} HTTP/1.0\r\n".format(mountpoint) + \
"User-Agent: NTRIP u-blox\r\n" + \
"Accept: */*\r\n" + \
"Authorization: Basic {}\r\n".format(pwd) + \
"Connection: close\r\n\r\n"
print(header)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server, int(port)))
s.sendto(header.encode('utf-8'), (server, int(port)))
resp = s.recv(1024)
try:
while True:
try:
data = s.recv(2048)
except:
pass
finally:
s.close()
I wanted to implement the same thing in c++ code and after going through few online tutorials, I wrote the following code in C++ (I am very new to C++)
#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>
using namespace std;
#define SIZE 1000
#define PORT 2101
string base64Encoder(string input_str, int len_str) {
char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *res_str = (char *) malloc(SIZE * sizeof(char));
int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
int i, j, k = 0;
for (i = 0; i < len_str; i += 3) {
val = 0, count = 0, no_of_bits = 0;
for (j = i; j < len_str && j <= i + 2; j++) {
val = val << 8;
val = val | input_str[j];
count++;
}
no_of_bits = count * 8;
padding = no_of_bits % 3;
while (no_of_bits != 0) {
// retrieve the value of each block
if (no_of_bits >= 6) {
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
} else {
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
for (i = 1; i <= padding; i++) {
res_str[k++] = '=';
}
res_str[k] = '\0';
string a = res_str;
return a;
}
int main() {
string input_str = ":";
int len_str;
len_str = input_str.length();
string pwd = base64Encoder(input_str, len_str);
string mountpoint = "leedgps";
string header = "GET /" + mountpoint + " HTTP/1.0\r\n" + \
"User-Agent: NTRIP u-blox\r\n" + \
"Accept: */*\r\n" + \
"Authorization: Basic " + pwd + "\r\n" + \
"Connection: close\r\n\r\n";
struct hostent *h;
if ((h = gethostbyname("www.rtk2go.com")) == NULL) { // Lookup the hostname
cout << "cannot look up hostname" << endl;
}
struct sockaddr_in saddr;
int sockfd, connfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0;
if (sockfd) {
printf("Error creating socket\n");
}
saddr.sin_family = AF_INET;
saddr.sin_port = htons(2101);
if(inet_pton(AF_INET, "3.23.52.207", &saddr.sin_addr)<=0) //
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
cout << connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) << endl;
return 0;
}
But the connect method always returns -1 (in C++). Any idea what am I doing wrong?
| sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0;
means that sockfd is either 0 or 1, which is not a valid socket.
Do this instead:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error creating socket\n");
}
|
70,939,317 | 70,939,438 | C++ : define struct/class template differenty for class and non-class types | in my C++ projet, I use a simple struct template with one template argument (a Vec2, with x and y attributes), and I need to define it differently for two main use cases :
The type is a class, in which case i need special constructor to initialize the two instances that will be held by forwarding arguments to the constructor of that class
The type is not a class (e.g any number type, a pointer, etc), in which case i'd like to be able to use aggregate initialization, which is, from what i understand, impossible for a class/struct that has user-defined constructors.
Which brings me to the question : how can i (using C++17) make two different definitions of my class, one for class types and one for others ? Can I make some kind of partial specialization for just the class types ?
| You can add extra parameter to enable SFINAE, something like
template <typename T, typename Enabler = void>
struct Vec2
{
T x;
T y;
// ...
};
template <typename T>
struct Vec2<T, std::enable_if_t<std::is_class_v<T>>>
{
private:
T x;
T y;
public:
Vec2(T x, T y) : x(std::move(x)), y(std::move(y)) {}
// ...
};
C++20 would allow specialization with concepts instead.
|
70,939,349 | 70,940,972 | std-ranges for string splitting and permutations | I'm trying to build a view that takes a vector of strings, splits those strings into pieces on char ; and returns permutations for the resulting tokens on each line.
int main()
{
std::vector<std::string> lines;
auto strsplit_view = std::ranges::views::split(';') | std::ranges::views::transform([](auto &&rng)
{ return std::string_view(&*rng.begin(), std::ranges::distance(rng)); });
auto filesplit_view = lines |
std::ranges::views::transform([&](auto &&line)
{ return line | strsplit_view; });
for (auto line : filesplit_view)
{
do
{
print(line);
} while (std::ranges::next_permutation(line).found)
}
}
Is there a way of incorporating permutations into the view itself, or do I have to perform a separate loop like shown above?
The current code does not work on lines, what do I have to do in order to pass line into ranges::next_permutation in this case?
Error output:
no matching function for call to ‘std::basic_string_view<char>::basic_string_view(std::ranges::transform_view<std::ranges::split_view<std::ranges::ref_view<std::__cxx11::basic_string<char> >, std::ranges::single_view<char> >, main()::<lambda(auto:18&&)> >&)’
89 | } while (std::ranges::next_permutation(std::string_view(line)).found)
| First, you should not convert the split pieces into std::string_view, because it is non-modifiable, which makes it impossible to use next_permutation. You should return std::span<char>.
Second, filesplit_view is a range whose elements are range adaptors. You need to use a for loop to traverse these range adaptors to get the actual split pieces.
#include <algorithm>
#include <ranges>
#include <string>
#include <vector>
int main() {
std::vector<std::string> lines;
auto strsplit_view =
std::views::split(';') | std::views::transform([](auto rng) {
return std::span(rng);
});
auto filesplit_view = lines |
std::views::transform([&](auto&& line) { return line | strsplit_view; });
for (auto adaptor : filesplit_view) {
for (auto line : adaptor) {
do {
// ...
} while (std::ranges::next_permutation(line).found);
}
}
}
Demo
|
70,940,008 | 70,943,911 | Concept requirement and non-immediate context | I'm learning C++ concepts, and trying to realize why the following does not compile (it's just a trivial and meaningless example demonstrating the point; tested with GCC-11.1):
#include <iostream>
struct non_negatable {
};
template <class T>
auto negate(T a) {
return -a;
}
template <class T>
concept is_negatable = requires(T t) {
//just `-a;` would do the job of course
negate(t);
};
template <class T>
auto do_negate(T) {
std::cout << "here we are\n";
}
template <is_negatable T>
auto do_negate(T t) {
return negate(t);
}
int main() {
non_negatable x;
do_negate(x);
}
The above concept attempts to call a function template, whose implementation would not compile. This fact causes a "hard error", rather than failing the concept.
I guess it works this way because the concept requirements may be failed only by the expressions' "immediate context" ill-formness (like what we could observe with SFINAE).
Is my understanding correct? Where does the Standard describe this point? Is there a way to "fail" a concept based on a function template implementation ill-formness?
| Firstly, as you referred, negate<non_negatable> is not a substitution failure since the error is not in the immediate context of the function, as such it's ill-formed. From 13.10.3.1/8 of C++20 standard:
If a substitution results in an invalid type or expression, type deduction fails.
An invalid type or expression is one that would be ill-formed, with a diagnostic required, if written using the substituted arguments.
[Note 4: If no diagnostic is required, the program is still ill-formed.
Access checking is done as part of the substitution process.
— end note]
Only invalid types and expressions in the immediate context of the function type, its template parameter types, and its explicit-specifier can result in a deduction failure.
[Note 5: The substitution into types and expressions can result in effects such as the instantiation of class template specializations and/or function template specializations, the generation of implicitly-defined functions, etc. Such effects are not in the “immediate context” and can result in the program being ill-formed.
— end note]
Secondly, 7.5.7.1/6 says:
[...]
[Note 1: If a requires-expression contains invalid types or expressions in its requirements, and it does not appear within the declaration of a templated entity, then the program is ill-formed.
— end note]
[...]
So, your understanding seems correct to me. However, what you're asking in your last question boils down to whether there is a way to make an invalid expression in a template function body cause a substitution failure instead of an ill-formed program. I don't think it's possible.
|
70,940,366 | 70,940,457 | How to start a new jthread on a class member | I think the question is quite obvious. The I have tried so far:
#include <thread>
#include <chrono>
using namespace std::literals::chrono_literals;
class test
{
public:
void member(std::stop_token stoken)
{
std::this_thread::sleep_for(1s);
}
void run()
{
// None compiles correctly
// std::jthread jt(&member);
// std::jthread jt(&test::member, this);
}
};
int main()
{
test t;
t.run();
return 0;
}
Is it possible with the new jthread & with using stop_token?
Ps.: Of course it's possible to workaround it by making the member function static or by removing the stop_token. But I'm curious if there's a real & clean solution instead of extra N lines of hacking.
| You can use std::bind_front to bind this to &test::member and pass it to jthread:
#include <thread>
#include <chrono>
#include <functional>
using namespace std::literals::chrono_literals;
class test
{
public:
void member(std::stop_token stoken)
{
std::this_thread::sleep_for(1s);
}
void run()
{
std::jthread jt(std::bind_front(&test::member, this));
}
};
int main()
{
test t;
t.run();
}
|
70,940,640 | 70,940,722 | How to use std::reference_wrapper<T>::operator() | I'd like to use the std::reference_wrapper<T>::operator() "the same" as std::reference_wrapper<T>::get, but following example fails for operator()
#include <cstdint>
#include <functional>
class Foo {
public:
void Print() {
std::printf("Foo\n");
}
};
class Bar {
public:
Bar(Foo &foo): wrapper{foo} {}
void Print() {
wrapper.get().Print(); // OK
// wrapper().Print(); // FAIL
}
private:
std::reference_wrapper<Foo> wrapper;
};
int main() {
Foo foo{};
Bar bar{foo};
bar.Print();
return 0;
}
Is this possible? Where is my misunderstanding?
Thanks for the help
Zlatan
|
Is this possible? Where is my misunderstanding?
No. std::reference_wrapper<T>::operator() only exists when T::operator() exists, and it simply calls that, forwarding the arguments provided.
Are you mistaking it for std::reference_wrapper<T>::operator T&?
class Bar {
public:
Bar(Foo &foo): wrapper{foo} {}
void Print() {
Foo & f = wrapper;
f.Print()
}
private:
std::reference_wrapper<Foo> wrapper;
};
|
70,940,861 | 70,941,097 | Move assignemnt is called instead of copy, when concepts are used for source type | In the following code, when I change the source from CAssign as source for assignment operators to AnyThing auto, then the move constructor will be called instead of copy.
I'm guessing it has to do with constness but I might be wrong. What causes this and how to achieve what I want?
#include <iostream>
#include <concepts>
template<typename T>
concept AnyThing = true;
struct CAssign
{
CAssign() = default;
CAssign& operator=(const CAssign& source)
{
std::cout << "Copy called\n";
return *this;
}
CAssign& operator=(CAssign&& source)
{
std::cout << "Move called\n";
return *this;
}
};
int main() {
CAssign a1, a2;
a1 = a2;
}
EDIT:
This is the change I do:
CAssign& operator=(const AnyThing auto& source)
//...
CAssign& operator=(AnyThing auto&& source)
Tried it with both Clang and GCC. Move is called instead of copy.
| In
CAssign& operator=(CAssign&& source)
the reference parameter is a rvalue reference. It will be called only if the argument given is a rvalue (which it isn't in a1 = a2;). This is a move assignment operator and how it should normally behave.
With
CAssign& operator=(Anything auto&& source)
or just
CAssign& operator=(auto&& source)
this is not a rvalue reference parameter. auto acts as a short-hand for a template parameter and if a template parameter T of a function is used directly as T&& for a function parameter, then it is a forwarding reference.
The forwarding reference can match either a rvalue or a lvalue. If it matches a rvalue, the function parameter will be a rvalue reference. If it matches a lvalue, it will be a lvalue reference.
In your case a1 = a2; the right-hand side is a lvalue and so it will call the specialization
CAssign& operator=<CAssign&>(CAssign& source)
of the function template that the auto version defines. This overload is preferred to the copy assignment overload you defined, because it doesn't require a const conversion in the parameter. If you had made a2's type const, the copy assignment operator would be preferred, since it is not a function template.
In particular this means that such a operator= overload is not a move assignment operator (or a copy assignment operator).
You shouldn't define a template operator= overload that takes any type or if you do, add a constraint that the type doesn't match CAssign.
|
70,941,002 | 70,976,170 | Read all data during single recv() method from a socket | I am trying to continuously read the data using socket programming. I use recv() which receives data on a socket. I store it in a buffer. recv() returns the number of bytes read. Following is the snippet:
while (true) {
try {
char buff[2048];
int bytes = recv(sockfd, buff, 2048, 0);
buff[bytes] = '\0';
cout << strlen(buff) << endl;
cout << bytes << endl;
cout << "-------" << endl;
} catch (const char *e) {
}
}
Following is the output of the code:
1
1204
-------
1
1390
-------
1
25
-------
1
1204
-------
The number of bytes received are correct through recv() method but I am not able to read the exact number of data. How can I read all the data captured during single recv() method?
| The function strlen will treat the contents of buff as a null-terminated string and return the length of that string.
In the line
buff[bytes] = '\0';
you wrote a null terminating character at the end of the data. That way, you have ensured that the data is null-terminated.
However, it is possible that the bytes that were read by recv contain a byte with the value 0. The function strlen will be unable to distinguish between such a byte and the actual terminating null character. It will simply return the index of the position of the first byte with the value 0.
That is why the expression strlen(buff) does not correspond to the actual length of the data.
For this reason, you should not be using the function strlen on binary data. That function is only intended for text data, which cannot contain a character with the value 0, except to mark the end of the string.
Instead of using strlen to determine the length of the data, you should only be using the value returned by recv (which you have stored in the variable bytes). As long as you remember this value, you will always know the length, so there is no need to mark the end of the data with a terminating null character.
Provided that recv returned a positive value (negative would indicate failure), you will find all of the data in the array buff, and the return value of recv will specify the length of the data. If you want to, for example, print all of the data that you have received in your function call to recv, you could write the following immediately after the recv function call:
for ( int i = 0; i < bytes; i++ )
cout << hex << setw(2) << setfill( '0' ) << static_cast<int>(buff[i]) << ' ';
Note that you must add #include <iomanip> at the start of your program for this line to work.
|
70,941,517 | 70,948,436 | vk api on boost c++ doesn't work correctly | I wrote a some code that should send GET request and get response.
It works for ip-api.com and returns me json file.
But for api.vk.com it returns html as that:
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>kittenx</center>
</body>
</html>
The most interesting thing is that the program returns the correct link, after opening which the desired GET request will be executed.
main.cpp:
#include <iostream>
#include "client.hpp"
#include "json.hpp"
std::string get_token(const std::string &);
int main()
{
std::string token = get_token("data/token1");
std::string query = "https://api.vk.com/method/groups.getMembers?access_token=" + token + "&v=5.13&group_id=klubauto";
std::cout << query << "\n\n\n";
Client client(url);
client.send_request(query);
std::string response = client.get_response();
std::cout << response << std::endl;
return 0;
}
client.hpp:
#pragma once
#include <string>
#include <boost/beast.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace http = boost::beast::http;
class Client
{
public:
Client();
Client(const std::string &api);
~Client();
void send_request(const std::string &arguments);
std::string get_response();
private:
boost::asio::io_context io;
boost::asio::ip::tcp::resolver resolver;
boost::asio::ip::tcp::socket socket;
std::string url;
};
client.cpp
#include "client.hpp"
/*
* Constructors
*/
Client::Client() : url("google.com"), resolver(io), socket(io)
{
boost::asio::connect(socket, resolver.resolve(url, "80"));
}
Client::Client(const std::string &api) : url(api), resolver(io), socket(io)
{
boost::asio::connect(socket, resolver.resolve(url, "80"));
}
/*
* Destructor
*/
Client::~Client()
{
socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
}
/*
* Send request
*/
void Client::send_request(const std::string &arguments)
{
http::request<http::string_body> req(http::verb::get, arguments, 11);
req.set(http::field::host, url);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
http::write(socket, req);
}
/*
* Get response
*/
std::string Client::get_response()
{
std::string response;
{
boost::beast::flat_buffer buffer;
http::response<http::dynamic_body> res;
http::read(socket, buffer, res);
response = boost::beast::buffers_to_string(res.body().data());
}
return response;
}
I would like to receive a json file in the response variable, please tell me how to achieve this?
| Like I commented, that's how HTTP works: Servers can redirect to a better/new location.
I assume the prime reason for this is because your connection is not HTTPS, and that's what the end-points require. So, fix that first.
Next, your query includes the base URL, which is another error.
Live Demo
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast.hpp>
#include <string>
namespace http = boost::beast::http;
namespace ssl = boost::asio::ssl;
using boost::asio::ip::tcp;
class Client {
public:
Client(const std::string& host = "google.com") : _host(host) {
_ctx.set_default_verify_paths();
connect(_socket.lowest_layer(),
tcp::resolver{_io}.resolve(_host, "https"));
_socket.handshake(ssl::stream_base::client);
}
void send_request(const std::string& query)
{
http::request<http::string_body> req(http::verb::get, query, 11);
req.set(http::field::host, _host);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
http::write(_socket, req);
}
std::string get_response() {
http::response<http::string_body> res;
boost::beast::flat_buffer buffer;
http::read(_socket, buffer, res);
return std::move(res.body());
}
private:
boost::asio::io_context _io;
ssl::context _ctx{ssl::context::sslv23_client};
ssl::stream<tcp::socket> _socket{_io, _ctx};
std::string _host;
};
#include <iostream>
#include <boost/json.hpp>
#include <boost/json/src.hpp> // for COLIRU header-only
namespace json = boost::json;
std::string get_token(const std::string&) { return ""; }
int main()
{
Client client("api.vk.com");
client.send_request("/method/groups.getMembers?access_token=" +
get_token("data/token1") + "&v=5.13&group_id=klubauto");
std::cout << json::parse(client.get_response()) << std::endl;
}
Coliru doesn't allow public network access:
terminate called after throwing an instance of 'boost::wrapexcept<boost::system::system_error>'
what(): resolve: Service not found
But on my machine it correctly says:
{"error":{"error_code":5,"error_msg":"User authorization failed: no access_token passed.","request_params":[{"key":"v","value":"5.13"},{"key":"group_id","value":"klubauto"},{"key":"method","value":"groups.getMembers"},{"key":"oauth","value":"1"}]}}
Note I included quite a number of simplifications along the way.
|
70,941,770 | 70,942,702 | Returning a range of references to a std::vector<std::unique_ptr<T>> | I have an abstract base class T and another class holding a vector of unique pointers to T. The class should support two function returning references to the entries. One of them should provide read-access, the other one should be able to modify the values in the unique_ptrs but not the pointers:
class A {
private:
std::vector<std::unique_ptr<T>> data;
public:
auto access() -> RefRange<T>;
auto const_access() -> ConstRefRange<T>;
};
The ranges should satisfy the requirements of a std::random_access_range.
How can I do this without allocating additional memory in C++17 (boost is available)?
| If you have boost, much of this is done by the range adaptor indirected
class A {
private:
static auto add_const(T & t) -> const T & { return t; }
std::vector<std::unique_ptr<T>> data;
using indirected = boost::adaptors::indirected;
using transformed = boost::adaptors::transformed;
public:
auto access() { return data | indirected; }
auto const_access() const { return data | indirected | transformed(add_const); }
};
Or with std::views::transform in C++20
class A {
private:
static auto indirect(const std::unique_ptr<T> & ptr) -> T & { return *ptr; }
static auto add_const(T & t) -> const T & { return t; }
std::vector<std::unique_ptr<T>> data;
using transform = std::views::transform;
public:
auto access() { return data | transform(indirect); }
auto const_access() const { return data | transform(indirect) | transform(add_const); }
};
If you have <experimental/propagate_const>, I'd use that instead of whichever transform(add_const).
class A {
private:
std::vector<std::experimental::propagate_const<std::unique_ptr<T>>> data;
using indirected = boost::adaptors::indirected;
public:
auto access() { return data | indirected; }
auto const_access() const { return data | indirected; }
};
|
70,941,875 | 70,942,312 | How does stringstream works with operators << and >>? | Input would be something like : 07:10
I'm getting correct value for hour but for min, I'm getting weird values.
void timeConversion(string s)
{
int hour,min;
stringstream ss;
ss << s.substr(0,2);
ss >> hour;
cout << hour <<endl;
ss << s.substr(3,2);
ss >> min;
cout << min<<endl;
}
| Mixing input and output like this is problematic. The initial extraction of hour sets the eofbit, which means when you try to extract min it immediately fails.
You can add ss.clear() to reset the flags.
void timeConversion(std::string s)
{
int hour,min;
std::stringstream ss;
ss << s.substr(0,2);
ss >> hour;
std::cout << hour << std::endl;
ss.clear();
ss << s.substr(3,2);
ss >> min;
std::cout << min << std::endl;
}
Or you use separate streams
void timeConversion(std::string s)
{
int hour,min;
std::stringstream { s.substr(0,2) } >> hour;
std::stringstream { s.substr(3,2) } >> min;
std::cout << hour << std::endl << min << std::endl;
}
Or you could use a different conversion function
void timeConversion(std::string s)
{
int hour = std::stoi(s.substr(0,2));
int min = std::stoi(s.substr(3,2));
std::cout << hour << std::endl << min << std::endl;
}
Aside: I'd recommend using std::string_view to avoid copying segments of strings, it has the same methods as a const std::string
|
70,941,883 | 70,944,485 | boost-ext::sml will not compile visitor example | I am trying to compile from source and experiment with the examples in boost::sml. The visitor example in particular will not compile, so my application with sml is missing a straightforward way to just status which states its state machines are in.
I am running on a machine with the following statuses when doing the initial cmake setup:
-- The CXX compiler identification is GNU 7.5.0
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Performing Test HAS_CXX14_FLAG
-- Performing Test HAS_CXX14_FLAG - Success
-- Performing Test HAS_CXX17_FLAG
-- Performing Test HAS_CXX17_FLAG - Success
-- Performing Test HAS_CXX20_FLAG
-- Performing Test HAS_CXX20_FLAG - Failed
-- Boost version: 1.65.1
-- Configuring done
-- Generating done
Most of the code compiles, but for example/visitor.cpp, I get these errors:
In file included from /data/sml/example/visitor.cpp:8:0:
/data/sml/include/boost/sml.hpp: In instantiation of ‘struct boost::ext::sml::v1_1_4::back::sm_impl<boost::ext::sml::v1_1_4::back::sm_policy<state_name_visitor<boost::ext::sml::v1_1_4::back::sm<boost::ext::sml::v1_1_4::back::sm_policy<composite> > > > >’:
/data/sml/include/boost/sml.hpp:1789:72: required from ‘boost::ext::sml::v1_1_4::back::sm< <template-parameter-1-1> >::operator T&() [with T = state_name_visitor<boost::ext::sml::v1_1_4::back::sm<boost::ext::sml::v1_1_4::back::sm_policy<composite> > >; TSM = boost::ext::sml::v1_1_4::back::sm_policy<composite>]’
/data/sml/example/visitor.cpp:68:62: required from here
/data/sml/include/boost/sml.hpp:1362:68: error: no matching function for call to ‘state_name_visitor<boost::ext::sml::v1_1_4::back::sm<boost::ext::sml::v1_1_4::back::sm_policy<composite> > >::operator()()’
compilation terminated due to -Wfatal-errors.
Any suggestions? Is C++20 required?
| C++20 is not required. The current revision on Github contains:
#error "[Boost::ext].SML requires C++14 support (Clang-3.4+, GCC-5.1+, MSVC-2015+)"
And indeed, it compiles fine with -std=c++14, even with GCC 7.5 on my Ubuntu 18.04 box.
However, since your CMake output suggests that C++17 is selected, I tried, and that gives the same problem. I might try to find a fix (after dinner)
UPDATE
I cannot say I fully understand this, but the following change makes it work:
const auto state_name = state_name_visitor<decltype(sm)>{sm};
Should be
const auto state_name = state_name_visitor<decltype((sm))>{sm};
Or alternatively
const auto state_name = state_name_visitor<decltype(sm)&>{sm};
Now it compiles in C++17 mode on GCC 7.5.
|
70,941,992 | 70,942,072 | passing "const ..." as "this" argument discards qualifiers [-fpermissive] | I'm writing a header file to learn more about operator overloading in C++, and I got the following error while implementing the division method for two complex numbers.
Here is the source code:
#ifndef __COMP_H
#define __COMP_H
#include <iostream>
class Complex{
private:
double real;
double imag;
public:
//constructor
Complex(double r=0, double i=0){real = r; imag = i;}
//operator overloading
Complex operator + (Complex const &obj){
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
Complex operator - (Complex const &obj){
Complex res;
res.real = real - obj.real;
res.imag = imag - obj.imag;
return res;
}
Complex operator * (Complex const &obj){
Complex res;
res.real = real*obj.real + (-1)*imag*obj.imag;
res.imag = real*obj.imag + imag*obj.real;
return res;
}
Complex operator * (double const i){
Complex res;
res.real = i*real;
res.imag = i*imag;
return res;
}
Complex operator / (Complex const &obj){
Complex conj(obj.real, (-1)*obj.imag);
Complex res = (*this)*obj; //numerator
Complex den = obj*conj; //denominator, it will be 0 as it's imaginary value
res = res*(1/den.real); //multiply it with a scalar value
return res;
}
void print(){
std::cout << real << " + " << imag << "j\n";
}
};
#endif
and the error looks as follows
In file included from main.cpp:2:
comp.h: In member function 'Complex Complex::operator/(const Complex&)':
comp.h:52:27: error: passing 'const Complex' as 'this' argument discards qualifiers [-fpermissive]
Complex den = obj*conj; //denominator, it will be 0 as it's imaginary value
^~~~
comp.h:32:13: note: in call to 'Complex Complex::operator*(const Complex&)'
Complex operator * (Complex const &obj){
^~~~~~~~
I've seen other answers on stackoverflow but did not understand it, what is meant by this error and how to fix it? Thanks!
| This
Complex operator - (Complex const &obj) { ...
and others are non-const member functions. Member functions are non-const by default, meaning they are declared to modify this. You cannot call them on a const instance. Most of your operators do not modify this, hence should be declared as const:
Complex operator - (Complex const &obj) const { ...
// ^^
|
70,942,530 | 71,083,646 | Is there an "undefined behavior" problem with some APIs in "node-addon-api"? | In <napi.h>, there are some overloads declaration for the static method Accessor in the class PropertyDescriptor.
One of such overloads declaration is here:
template <typename Getter>
static PropertyDescriptor Accessor(Napi::Env env,
Napi::Object object,
const std::string& utf8name,
Getter getter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
That declaration wants a reference to a const std::string
The definition of that declaration is in <napi-inl.h>:
template <typename Getter>
inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env,
Napi::Object object,
const std::string& utf8name,
Getter getter,
napi_property_attributes attributes,
void* data) {
return Accessor(env, object, utf8name.c_str(), getter, attributes, data);
}
As you can see, the implementation takes the .c_str() of the passed std::string, as the implementation in fact uses another overload which wants a const char*.
The overload used is also in <napi-inl.h>:
template <typename Getter>
inline PropertyDescriptor
PropertyDescriptor::Accessor(Napi::Env env,
Napi::Object object,
const char* utf8name,
Getter getter,
napi_property_attributes attributes,
void* data) {
using CbData = details::CallbackData<Getter, Napi::Value>;
auto callbackData = new CbData({ getter, data });
napi_status status = AttachData(env, object, callbackData);
if (status != napi_ok) {
delete callbackData;
NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor());
}
return PropertyDescriptor({
utf8name,
nullptr,
nullptr,
CbData::Wrapper,
nullptr,
nullptr,
attributes,
callbackData
});
}
That implementation uses Node-API, as node-addon-api is just a C++ wrapper arround Node-API. The fact is that the const char* utf8name obtained from .c_str() is passed as is to the constructor and is stored in the private member napi_property_descriptor _desc;
Conclusion: each time you use Napi::PropertyDescriptor::Accessor passing a std::string and then storing the PD in a vector, or just making the string goes out of scope with the PD still here, you trigger an undefined behavior!
Example:
Napi::Object TheNewObject = Napi::Object::New(env);
std::vector<Napi::PropertyDescriptor> vProps;
for (size_t index = 0; index < 2; ++index ) {
std::string strName("MyName_");
strName += std::to_string(index);
auto PD = Napi::PropertyDescriptor::Accessor(env, TheNewObject, strName, Caller);
vProps.push_back(PD);
}
I opened an issue here, 12 days ago, with no avail.
EDIT: After reading comments, I should add that:
The napi_property_descriptor is a simple C structure.
Address of that struct will later be passed to the Node-API napi_define_properties
| There is indeed a problem with current implementations of PropertyDescriptor.
See https://github.com/nodejs/node-addon-api/issues/1127#issuecomment-1036394322
Glad I wasn't completely delirious.
|
70,942,644 | 70,942,812 | How to fix warning "Found OpenCV Windows Pack but it has no binaries compatible with your configuration"? | I am trying to use OpenCV in VS Code.
Here's what I've done:
Installed OpenCV for windows.
Added "C:\opencv\build\x64\vc15\bin","C:\opencv\build\x64\vc15\lib" PATH environment variable.
Here's my CMakeLists.txt file.
cmake_minimum_required(VERSION 3.0.0)
project(opencvtest VERSION 0.1.0)
include(CTest)
enable_testing()
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable(opencvtest main.cpp)
target_link_libraries( opencvtest ${OpenCV_LIBS} )
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
But the file throws the following error:
[proc] Executing command: "C:\Program Files\CMake\bin\cmake.EXE" --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_C_COMPILER:FILEPATH=C:\TDM-GCC-64\bin\x86_64-w64-mingw32-gcc.exe -DCMAKE_CXX_COMPILER:FILEPATH=C:\TDM-GCC-64\bin\x86_64-w64-mingw32-g++.exe -Hc:/Users/Administrator/Desktop/open -Bc:/Users/Administrator/Desktop/open/build -G "MinGW Makefiles"
[cmake] Not searching for unused variables given on the command line.
[cmake] -- OpenCV ARCH: x64
[cmake] -- OpenCV RUNTIME: mingw
[cmake] -- OpenCV STATIC: OFF
[cmake] CMake Warning at C:/opencv/build/OpenCVConfig.cmake:190 (message):
[cmake] Found OpenCV Windows Pack but it has no binaries compatible with your
[cmake] configuration.
[cmake]
[cmake] You should manually point CMake variable OpenCV_DIR to your build of OpenCV
[cmake] library.
[cmake] Call Stack (most recent call first):
[cmake] CMakeLists.txt:7 (find_package)
[cmake]
[cmake]
[cmake] CMake Error at CMakeLists.txt:7 (find_package):
[cmake] Found package configuration file:
[cmake]
[cmake] C:/opencv/build/OpenCVConfig.cmake
[cmake]
[cmake] but it set OpenCV_FOUND to FALSE so package "OpenCV" is considered to be
[cmake] NOT FOUND.
[cmake]
[cmake]
[cmake] -- Configuring incomplete, errors occurred!
I am trying to run a C++ file in VS Code that includes <opencv2/opencv.hpp>.
| As the error suggests, CMake found your OpenCV installation, but it is not compatible. What is it not compatible with? Your compiler. The OpenCV installation is built with MSVC 15 (it also includes a 14 build). You have asked CMake to use MinGW as your compiler. Libraries need to have been built with the same (well, with some leeway) compiler for everything to work.
You have two options:
Build OpenCV yourself with MinGW, or try a third-party MinGW binary distribution of OpenCV. Web searches for "opencv mingw" turn up some
possibilities.
Use the MSVC compiler for your project. Microsoft offers some free versions of its tools. Just be sure to install the optional older toolsets so that you have access to the VC 15 tools to match OpenCV.
|
70,942,654 | 70,943,174 | Generic ranges-compatible functions | I have a function that operates on standard iterators of a common type:
template <typename I>
bool next_combination(const I first, I k, const I last)
I'm trying to use it with std::ranges::views, but I'm not able to pass its iterators as input arguments to the function:
auto view = std::ranges::views::split(';') |
std::ranges::views::transform(
[](auto &&rng)
{
bool ok = next_combination(rng.begin(),rng.begin() + 2, rng.end());
// ...
}
The view-iterators does not support operator+ for the second input argument of next_combination, and the begin and end iterator types are different.
How do I adapt function next_combination to handle ranges/views, or (alternatively) adapt the input arguments in order to make this compile?
Edit: Full example:
#include <string>
#include <ranges>
#include <span>
#include <vector>
#include <algorithm>
template <typename I>
bool next_combination(const I first, I k, const I last)
{
/* Credits: Mark Nelson http://marknelson.us */
if ((first == last) || (first == k) || (last == k))
return false;
I i1 = first;
I i2 = last;
++i1;
if (last == i1)
return false;
i1 = last;
--i1;
i1 = k;
--i2;
while (first != i1)
{
if (*--i1 < *i2)
{
I j = k;
while (!(*i1 < *j))
++j;
std::iter_swap(i1, j);
++i1;
++j;
i2 = k;
std::rotate(i1, j, last);
while (last != j)
{
++j;
++i2;
}
std::rotate(k, i2, last);
return true;
}
}
std::rotate(first, k, last);
return false;
}
int main()
{
std::string line;
std::vector<std::string> lines{"bcd;zac", "cad;c"};
auto strsplit_view =
std::ranges::views::split(';') | std::ranges::views::drop(1) |
std::ranges::views::transform(
[](auto &&rng)
{
bool ok = next_combination(rng.begin(),rng.begin() + 2, rng.end());
return std::span(&*rng.begin(), std::ranges::distance(rng)); });
auto filesplit_view = lines | std::ranges::views::transform(
[&](auto &&line)
{ return line | strsplit_view; });
}
| You are using a version of gcc that has not yet implemented the P2210, that is, the split subranges obtained by views::split (renamed views::lazy_split in the latest standard) can only be a forward_range.
Since next_combination requires bidirectional_iterators (which support operator--), you cannot pass an iterator of forward_range to it.
There is no simple solution until using a compiler that implements P2210.
|
70,942,887 | 70,943,291 | How can I make a typedef or alias for a template function that can also be used in friend function declarations? | If I have something like this:
mytemplates.h
#ifndef MYTEMPLATES_H
#define MYTEMPLATES_H
#include <iostream>
#include <memory>
#include <string>
class BaseClass;
// Alias (non-working) version:
//class DerivedClass1;
namespace MyTemplates
{
typedef std::unique_ptr<BaseClass> object_up;
template<typename SomeDerivedClass>
object_up createFromIntFloat(int intParam, float floatParam)
{
SomeDerivedClass *newObject_raw = new SomeDerivedClass(intParam, floatParam);
object_up uniqueObject {newObject_raw};
std::cout << "createFromIntFloat." << "\n";
return uniqueObject;
}
// Alias (non-working) version:
//using createFromIntFloatPtrType = object_up(*)(int intParam, float floatParam);
template<typename SomeDerivedClass>
object_up createFromString(std::string stringParam)
{
SomeDerivedClass *newObject_raw = new SomeDerivedClass(stringParam);
object_up uniqueObject {newObject_raw};
std::cout << "createFromString." << "\n";
return uniqueObject;
}
// Alias (non-working) version:
//using createFromStringPtrType = object_up(*)(std::string stringParam);
// Alias (non-working) version:
// createFromStringPtrType createDerivedClass1 = createFromString<DerivedClass1>;
}
#endif // MYTEMPLATES_H
baseclass.h
#ifndef BASECLASS_H
#define BASECLASS_H
class BaseClass
{
protected:
BaseClass(){};
};
#endif // BASECLASS_H
derivedclass1.h
#ifndef DERIVEDCLASS1_H
#define DERIVEDCLASS1_H
#include "baseclass.h"
#include "mytemplates.h"
class DerivedClass1 : public BaseClass
{
std::string stringParam;
protected:
DerivedClass1(std::string aStringParam) : BaseClass(), stringParam(aStringParam) {};
// Alias (non-working) version:
// friend MyTemplates::object_up MyTemplates::createDerivedClass1(std::string stringParam);
// Non-alias version:
friend MyTemplates::object_up MyTemplates::createFromString<DerivedClass1>(std::string stringParam);
};
#endif // DERIVEDCLASS1_H
main.cpp
#include "mytemplates.h"
#include "derivedclass1.h"
int main(int argc, char *argv[])
{
// Alias (non-working) version:
// MyTemplates::object_up uniqueClass1 = MyTemplates::createDerivedClass1("creation info for class 1");
// Non-alias version:
MyTemplates::object_up uniqueClass1 = MyTemplates::createFromString<DerivedClass1>("creation info for class 1");
}
I would like to create some kind of alias like the Alias (non-working) version on the above code so that I could use this alias - createDerivedClass1 - both in direct calling like in main.cpp and in friend declarations like in derivedclass1.h
How can I change the code above from the Non-alias version to the Alias version and make it work?
| Aliases are for types because types are not first class objects in C++. But you do not need aliases for plain functions because you can simply use function pointers.
But a function pointer is just a pointer and you must declare the real function to be friend. It all boil down to:
...
class DerivedClass1 : public BaseClass
{
std::string stringParam;
protected:
DerivedClass1(std::string aStringParam) : BaseClass(), stringParam(aStringParam) {};
// Alias (non-working) version:
//friend MyTemplates::object_up MyTemplates::createDerivedClass1(std::string stringParam);
// Non-alias version:
friend MyTemplates::object_up MyTemplates::createFromString<DerivedClass1>(std::string stringParam);
};
namespace MyTemplates {
object_up(*createDerivedClass1)(std::string) = createFromString<DerivedClass1>;
}
int main(int argc, char* argv[])
{
// Alias (non-working) version:
MyTemplates::object_up uniqueClass1 = MyTemplates::createDerivedClass1("creation info for class 1");
// Non-alias version:
MyTemplates::object_up uniqueClass2 = MyTemplates::createFromString<DerivedClass1>("creation info for class 1");
}
|
70,943,108 | 70,943,118 | Conditional inclusion: integral constant expression is unlimited? | Per C++11 (and newer) this code is valid:
#if 1.0 > 2.0 ? 1 : 0
#endif
However, most (if not all) C++ compilers reject it:
$ echo "#if 1.0 > 2.0 ? 1 : 0" | g++ -xc++ - -std=c++11 -pedantic -c
<stdin>:1:5: error: floating constant in preprocessor expression
<stdin>:1:11: error: floating constant in preprocessor expression
N4849 has this (emphasis added):
The expression that controls conditional inclusion shall be an integral constant expression except that identifiers (including those lexically identical to keywords) are interpreted as described below143 and it may contain zero or more defined-macro-expressions and/or has-include-expressions and/or has-attribute-expressions as unary operator expressions.
and this (emphasis added):
An integral constant expression is an expression of integral or unscoped enumeration type, implicitly converted to a prvalue, where the converted expression is a core constant expression.
The 1.0 > 2.0 ? 1 : 0 is integral constant expression.
So, where C++ standard prohibits using floating-point literal (for example) in the expression that controls conditional inclusion?
| Answer from Richard Smith:
This is an error in the standard wording. See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1436 for details and a proposed fix -- though that fix is known to be wrong too (it permits lambda-expressions).
|
70,943,170 | 70,943,292 | What is the proper evaluation order when assigning a value in a map? | I know that compiler is usually the last thing to blame for bugs in a code, but I do not see any other explanation for the following behaviour of the following C++ code (distilled down from an actual project):
#include <iostream>
#include <map>
int main()
{
auto values = { 1, 3, 5 };
std::map<int, int> valMap;
for (auto const & val : values) {
std::cout << "before assignment: valMap.size() = " << valMap.size();
valMap[val] = valMap.size();
std::cout << " -> set valMap[" << val << "] to " << valMap[val] << "\n";
}
}
The expected output of this code is:
before assignment: valMap.size() = 0 -> set valMap[1] to 0
before assignment: valMap.size() = 1 -> set valMap[3] to 1
before assignment: valMap.size() = 2 -> set valMap[5] to 2
However, when I build a Release version with the (default) C++14 compiler, the output becomes:
before assignment: valMap.size() = 0 -> set valMap[1] to 1
before assignment: valMap.size() = 1 -> set valMap[3] to 2
before assignment: valMap.size() = 2 -> set valMap[5] to 3
In other words, all values in valMap are larger by 1 than what they should be - it looks like the map gets appended before the right-hand-side of the assignment is evaluated.
This happens only in a Release build with C++14 language standard (which is the default in VS2019). Debug builds work fine (I hate when this happens - it took me hours to find out what is going on), as do Release builds of C++17 and C++20. This is why it looks like a bug to me.
My question is: is this a compiler bug, or am I doing something wrong/dangerous by using .size() in the assignment?
| The evaluation order of A = B was not specified before c++17, after c++17 B is guaranteed to be evaluated before A, see https://en.cppreference.com/w/cpp/language/eval_order rule 20.
The behaviour of valMap[val] = valMap.size(); is therefore unspecified in c++14, you should use:
auto size = valMap.size();
valMap[val] = size;
Or avoid the problem by using emplace which is more explicit than relying on [] to automatically insert a value if it doesn't already exist:
valMap.emplace(val, size);
|
70,943,365 | 70,945,756 | Is HAL_UARTEx_RxEventCallback Size parameter calculated programmatically or by hardware | I'm realizing UART-DMA with STM_HAL library and I want to know if message size is counted by hardware (counting clock ticks till line is idle for example) or by some program method(something like strlen). So if Size in
HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
is counted by hardware, I can send data in pure HEX format, but if it is calculated by something like strline, I may recieve problems if data is 0x00 and have to send data in ASCII.
I've tried to make some research in generated code in Keil but failed (maybe I didn't try hard enough) so maybe somebody can help me.
| If you are using UART DMA, it is calculated by hardware.
If you check the call hierarchy of HAL_UARTEx_RxEventCallback using your ide, you can see how the Size variable is calculated.
The function is executed in the following flow.(Depending on the version of HAL Driver, it may be slightly different)
UART Idle Interrupt occur
Call HAL_UART_IRQHandler()
If DMA mod is enabled, Call HAL_UARTEx_RxEventCallback(huart, (huart->RxXferSize - huart->RxXferCount))
Therefore, Size variable is calculated as (huart->RxXferSize - huart->RxXferCount)
huart->RxXferSize is a set value when initializing RX DMA.
huart->RxXferCount is (huart->hdmarx)->Instance->NDTR
NDTR is a value calculated by hardware as the size of the buffer remaining after DMA transfer data to memory!!
|
70,943,406 | 70,943,484 | How to declare a dynamic 2D array in C++ | I'm trying to define a dynamic 2D Array in C++ using the following definition:
int foo(string parameter){
const int n = parameter.length();
int* Array = new int[n][n];
return 0;
}
I receive an error that array size in new expression must be constant, can't understand why because Array is supposed to be dynamic.
| (someone posted a shorter version of this in the comments while I was writing it).
What you need for a 2D array allocated with new is this:
int foo(string parameter){
const int n = parameter.length();
int* Array = new int[n*n];
return 0;
}
And then access cells with appropriate indexing.
Another solution is to use vector.
int foo(string parameter){
const int n = parameter.length();
vector<vector<int>> Array(n, vector<int>(n));
return 0;
}
|
70,943,680 | 70,943,836 | Return an array without getting a Dangling pointer as result in C++ | I want to return an array from a function in C++. I made this simple code to try to achieve it.
#include <iostream>
#include <vector>
std::vector<int> *getx()
{
std::vector<int> a[2];
a[0].push_back(0);
a[1].push_back(1);
return a;
}
int main()
{
std::vector<int>* b = getx();
return 0;
}
It works but I get this Warning:
warning C4172: returning address of local variable or temporary: a
Why if i made std::vector<int> a[2] static I solve the warning?
static std::vector<int> a[2];
Is there another way to return an array from a function without having dangling pointers warnings?
Thank you.
|
Why if i made std::vector a[2] static I solve the warning?
static std::vector a[2];
You may not return a pointer to a local array with automatic storage duration because the array will not be alive after exiting the function and as a result the returned pointer will be invalid.
But you may return a pointer to a local array with static storage duration because it will be alive after exiting the function.
However in fact there is no need to deal exactly with an array. Either use std::vector<std::vector<int>> or std::array<std::vector<int>, 2> as the return type of the function.
For example
std::vector<std::vector<int>> getx()
{
std::vector<std::vector<int>> a( 2 );
a[0].push_back(0);
a[1].push_back(1);
return a;
}
or
std::array<std::vector<int>, 2> getx()
{
std::array<std::vector<int>, 2> a;
a[0].push_back(0);
a[1].push_back(1);
return a;
}
|
70,944,492 | 70,947,172 | Get string of characters from a vector of strings where the resulting string is equivalent to the majority of the same chars in the nth pos in strings | I'm reading from a file a series of strings, one for each line.
The strings all have the same length.
File looks like this:
010110011101
111110010100
010000100110
010010001001
010100100011
[...]
Result : 010110000111
I'll need to compare each 1st char of every string to obtain one single string at the end.
If the majority of the nth char in the strings is 1, the result string in that index will be 1, otherwise it's going to be 0 and so on.
For reference, the example I provided should return the value shown in the code block, as the majority of the chars in the first index of all strings is 0, the second one is 1 and so on.
I'm pretty new to C++ as I'm trying to move from Web Development to Software Development.
Also, I tought about making this with vectors, but maybe there is a better way.
Thanks.
| First off, you show the result of your example input should be 010110000111 but it should actually be 010110000101 instead, because the 11th column has more 0s than 1s in it.
That being said, what you are asking for is simple. Just put the strings into a std::vector, and then run a loop for each string index, running a second loop through the vector counting the number of 1s and 0s at the current string index, eg:
vector<string> vec;
// fill vec as needed...
string result(12, '\0');
for(size_t i = 0; i < 12; ++i) {
int digits[2]{};
for(const auto &str : vec) {
digits[str[i] - '0']++;
}
result[i] = (digits[1] > digits[0]) ? '1' : '0';
}
// use result as needed...
Online Demo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.