question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,055,545
73,055,584
Why do some folks continue to add subsequent duplicate #include some duplicate header files in their projects?
Why do some folks continue to add subsequent duplicate #include some duplicate header files in their projects? Bat.h #include <SFML/Graphics.hpp> Pong.cpp #include "Bat.h" #include <SFML/Graphics.hpp> Wasn't they paying attention?
The idea is to include the headers that the current file depends on. E.g. in Pong.cpp, you're not obliged to know whether Bat.h (which you supposedly also included) depends on <SFML/Graphics.hpp> or on another graphics library or no graphics library at all. Since double include is something we can prevent (using includ...
73,055,625
73,056,546
Deriving class with protected equality operator results in deleted default
Suppose we have the following implementation: class A { protected: bool operator==(const A&) const = default; }; class B : public A { public: bool operator==(const B& b) const { return A::operator==(b); }; }; int main() { B x, y; x == y; } This works in gcc 12.1 and clang 14.0. I ...
The defaulted implementation does not try to call A::operator==(b) for the base comparison. It does something like static_cast<const A&>(*this) == static_cast<const A&>(b) instead and applies overload resolution to it as usual. This is described in [class.eq]/2 and [class.eq]/3. Also see [class.compare.default]/3 and [...
73,055,962
73,056,473
C++ Dynamic Stack : typedeffing a pointer-struct?
I can't understand what's happening on the beginning of this C++ code that would explain to me how to implement a stack using Dynamic Array. I'm sure the code is correct, because the program runs correctly (correct results), but I don't understand it! struct Node { char Info; Node *Link; }; typedef Node *Stack...
Let's start with the code. struct Node { char Info; Node *Link; }; typedef Node * Stack; And you wrote this: there is a struct called Node, and it has Info and *Link as "fields", like fields on a form paper. So Node is the name of a "template" (struct) with empty "fields". Each time we use Node on this progr...
73,057,294
73,057,674
Can programs detect if I am using ReadProcessMemory on it?
I'm writing a program to read a game's memory as it runs. I want to avoid the game noticing me however, since it might behave differently under observation. Is it possible for processes to detect the act of me inspecting it's memory from another process? This is the method I'm using to inspect it: // this is how I ga...
It's not possible to detect a ReadProcessMemory or WriteProcessMemory but it is possible to detect the preceding OpenProcess that is needed to gain access.
73,057,454
73,057,474
Is "(unsigned)value" cast undefined behaviour?
I am writing some code to test for a bit in a bit-field and I wrote this: return (unsigned)(m_category | category) > 0 I though this wouldn't compile, since I didn't give the integer type, but to my surprise it did. So I'm wondering, what does this do? Is it undefined?
unsigned is the same as unsigned int. The cast will convert the signed integer to unsigned as follows: https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value modulo 2n where n ...
73,057,484
73,057,927
How to compare two Blitz++ Arrays?
I am trying to compare two Blitz++ Arrays, but I am getting a compiler error saying that the expression cannot be converted into a boolean. According to the documentation this operation should be supported. What am I doing wrong? Code: #include <blitz/array.h> int main() { blitz::Array<double, 2> a(1, 1); blitz::A...
blitz::Array<bool, 2> result(a == b); or bool c = blitz::all(blitz::Array<bool, 2>(a == b)); the conversion from expression to array is explicit.
73,058,455
73,058,474
Why does passing functions by value work but not by reference
Here I have the code void foo(std::function<int(int)> stuff){ //whatever } and it is called with auto fct = [](int x){return 0;}; foo(fct); Which works great. However, when I change foo to void foo(std::function<int(int)>& stuff){ // only change is that it is passed by reference //whatever } The code doesn't ...
You are trying to bind a non-constant reference with a temporary object. You could use a constant reference. Here is a demonstration program. #include <iostream> #include <functional> void foo( const std::function<int(int)> &stuff ) { int x = 10; std::cout << stuff( x ) << '\n'; } int main() { auto fct = [...
73,058,695
73,058,837
How to zip vectors using template metaprogramming
I am practicing on template meta-programming and wanted to implement a simple trivial meta-function. I wonder how one can implement zip functionality on custom vectors. What I have in my mind is as follows: Here is how the zip operation for this custom vector look like: Inputs: Vector<1, 2, 3> Vector<2, 3, 4> Vector<3,...
You can partially specialise zip in order to expose the template parameters of the Vectors you pass. template<typename...> struct zip; template<int... Us, int... Vs, typename... Tail> struct zip<Vector<Us...>, Vector<Vs...>, Tail...> { using type = typename zip<Vector<(Us * Vs)...>, Tail...>::type; }; template<ty...
73,059,358
73,059,460
how to check if a string has matching values with a vector
I'm trying to use a for loop and an if statement to compare if any values in the string match with any in the vector. It only outputs "we have a match" if the first character in teststring is in the vector. Basically, it seems like the searching stops if the first character value in teststring isn't in the SpecialChars...
teststring has a different length than SpcialChars, and teststring is shorter, so your for loop will go out of bounds of teststring when i reaches 6, causing undefined behavior. You need 2 loops, one to iterate teststring, and one to iterate SpecialChars, eg: #include <iostream> #include <vector> #include <string> voi...
73,059,564
73,059,592
Using A Struct As Key For std::unordered_map
I am trying to use a struct as a key for an unordered_map. I added the 'spaceship' operator to the structure, which solved errors I was getting with normal comparisons, such as "is struct 1 greater than struct 2?", etc. However, I am getting attempting to reference a deleted function when using it as a key for my map. ...
To use a structure as a key in an unordered_map, you need two things: A "hasher", something that will take a const test & and compute a hash, which defaults to std:hash<test>, and A comparison predicate, which defaults to std::equal_to<test>. You've got the second one covered with your spaceship operator, but not t...
73,059,585
73,059,646
How do I fix my double-buffer not drawing to screen?
I'm working on a small operating system, and I ran into some screen-tearing, so I'm working on double-buffering to solve that. I'm just now running into the issue that now nothing prints to screen after revamping my rendering methods. A list of a few things that could be the issue, though I'm really not sure: I did a ...
I did a lot of sketchy things to get the void dst and src to be compatible with u8 d and s in memcpy function Yes, you did. And often that's an indication you're doing something wrong. Let's look at it: static inline void *memcpy(void *dst, const void *src, size_t n) { u8 *d = (u8*)(&dst); const u8 *s = (cons...
73,059,808
73,059,891
Why can my comment consist of so much forward slash (/)?
I know that there are many types of comment, I will list out a few of them (those related): // - Normal comment /// - This would make the comment bold And surprisingly, the IDE would not raise an error in this code (Even it is not executed, it should still control the programmer somewhere): /////////////////// HI! ...
As per the C++ standard: lex.comment The characters // start a comment, which terminates immediately before the next new-line character. From the above, you can infer that every character (other than newline) which follows the first two / characters is part of the comment. If that wasn't already clear enough, it goes...
73,060,094
73,060,177
For loop in c++ is not running while using this way: for(int i=-1;i<vector.size();i++) cout << i << endl;
I have a particular use case where I have to initialize i value in for loop to -1 and write the exiting condition based on vector size. But the problem is the loop is not getting executed at all. This is the code. #include <bits/stdc++.h> using namespace std; int main() { vector<int> vec = { 1, 2, 3, 4, 5 }; f...
i<size() in the first snippet compares a signed int i; to an unsigned size_t size; (size_t is the typical typedef for vector::size_type) When the compiler sees that comparison, it converts the int to an unsigned value. Typically something like 2^64 - 1, for your first value of -1. This value is much bigger than 5, so t...
73,060,302
73,060,451
std::invocable seems to be acting differently on functors within structs
Consider the following code: #include <concepts> #include <functional> struct A { auto operator()(int const &) const noexcept { return 0; } }; static_assert(std::invocable<A const &, int const &>); struct X { struct B { auto operator()(int const &) const noexcept { return 0; } }; static_as...
At the point where you write static_assert(!std::invocable<B const &, int const &>);, within X, X is not yet a complete type. As cppreference states If an instantiation of a template [in the std::is_invocable family] depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different...
73,061,125
73,061,274
In has-a relation is it a good design, to access and alter the private members of contained class directly from the Parent class method
Consider this example: class Child { private: string m_Name; public: string* GetNameAccess() { return &m_Name; } }; class Parent { private: Child m_Child; public: void DoSomething() { string *pChildName = m_Child.GetNameAccess(); // Is this the right thing to do? *...
Although having a public function that returns a pointer to a private data member is legal in C++, it breaks the whole point of encapsulation. As mentioned in the comments, if you want to provide such 'direct' access to the data member, then just make it public. But there are many good reasons why a data member should ...
73,061,333
73,063,096
How can a class have a function implementation but without its declaration?
I am reading the following source code (taken from this repository). void AVariableReplicationCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty >& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); // Variable A doesn't have any additional replication condition D...
There is already an accepted answer to this question, but it's vague and based on guessing, so I'll try to give a more definitive answer: When declaring a class that can be replicated, it has to be defined as either an AActor or a UActorComponent. Both of which use the UCLASS() macro to denote that the following class ...
73,061,555
73,097,510
Given perpendicular distance d on line1, how to find point P on line2 in C++?
Given line1, line2, and distance d, I want to write a program to calculate the point on Line2 that is perpendicular to Line1, and the perpendicular distance is d. Does anyone know where to start? In C++ or any other programming language. Thanks in advance.
Normalize line1 equation L = sqrt(a1*a1+b1*b1) a11 = a1 / L b11 = b1 / L c11 = c1 / L Now for arbitrary point (x,y) length of perpendicular projection onto line1 is d = a11*x + b11*y + c11 a11*x + b11*y + (c11-d) = 0 for vertical line2 case (b2==0) and (b11 != 0) x = c2/a2 a11*c2/a2 + b11*y + (c11-d) = 0 y = -(a11*c2...
73,062,967
73,062,999
How should I assume which iterator category an algorithm uses?
Let's say : std::sort(beg1, beg2, pred); This algorithm takes a range of iterators for the container and a predicate. It takes an LegacyRandomAccessIterator. I do understand the the 5 iterator categories are categorised by their operators. Albeit I'm having a hard time assuming which iterator the algorithm uses.
There is no need to assume anything, it is all documented. According to cppreference the iterators are LegacyRandomAccessIterator. Type requirements -RandomIt must meet the requirements of ValueSwappable and LegacyRandomAccessIterator. -The type of dereferenced RandomIt must meet the requirements of MoveAssignable and...
73,063,320
73,063,374
Is it bad to store the underlying type of an object?
If I have a class called Node, would it be bad, if objects of the Node class knew their NodeType, and the NodeType would be used to cast to a specific interface like this: // NodeType enum class NodeType : uint8_t { None = 0, Foo = 1 << 0, Bar = 1 << 1, FooBar = 1 << 2, ...
Is this a bad approach? Is there any more OO approach to this? Yes. You can just dynamic_cast to the appropriate pointer type and check the result is not null. int main() { std::vector<std::unique_ptr<Node>> nodes{ GetNodes() }; for (const auto& node : nodes) { if (auto foo = dynamic_cast<con...
73,063,464
73,065,011
Function accepting a reference to std::variant
I'm trying to pass values to a function accepting a std::variant. I noticed I can use a function accepting a const reference to a variant value, but not a reference alone. Consider this code #include <variant> #include <queue> #include <iostream> struct Foo{ std::string msg{"foo"}; }; struct Bar{ std::string msg{"bar"...
You cannot pass a temporary resulting from converting the Foo to a std::variant<Foo,Bar> to f2. C++ disallows this because binding a temporary to a non-const reference is most likely a bug. If it was possible you'd have no way to inspect the modified value anyhow. You can workaround this by using a std::variant of refe...
73,063,544
73,068,361
How to add expectations alongside with ASSERT_DEATH in GoogleTest for C++
Given those interfaces: class ITemperature { public: virtual ~ITemperature() = deafult; virtual int get_temp() const = 0; }; class IHumidity { public: virtual ~IHumidity() = deafult; virtual int get_humidity() const = 0; }; And this SUT: class SoftwareUnderTest { public: SoftwareUnderTes...
Apparently, this is a known limitation, see here and here. From what I have managed to discover by experimentation so far: If you can live with the error message about leaking mocks (haven't checked if it's true or a false positive, suppressing it by AllowLeak triggers the actual crash), it can be done by making the mo...
73,064,491
73,064,563
Trouble with pointer to templated class method
I was writing code for the following parallel processing task: A std::vector<T> contains data items that need to be processed A function process_data<T&> does that processing on such a single data item In my software I want to do this for different types T, so I wrote a template class: #include <mutex> #include <thre...
As item_thread_worker is a non-static member function, it needs a object to be called with. When you create your threads, you don't specify any objects. Those objects (which becomes the this pointer inside the functions) are passed as a hidden "first" argument. Another point is that to get a pointer to a member functio...
73,065,507
73,065,572
Implemtation of += operator oveloaded for the Class Vector. C++
I need to implement the overloading of the += operator in c++. I have a Vector class and my implentation of += needs to add an integer from the back of my Vector. For example: if my vector V1 contains of {1, 2, 3} and I write V1 += 4, it needs to give me {1, 2, 3, 4}. I have almost the same functionality with the overl...
In the += operator, you should set the new value to the vecor to be added itself. Also note that returning a reference to a non-static local variable temp is a bad idea. Try this: Vector& operator+=(const int val) { Vector temp; temp._list = new int[_size + 1]; temp._size = this->_size + 1; for (unsign...
73,065,915
73,067,958
How to test several interface implementations with different constructors with gtest in C++?
I have an interface for which I have three implementations. I am using the TYPED_TEST from google test so that I can use the same set of tests for all implementations. I have the following Fixture. template <typename T> class GenericTester : public ::testing::Test { protected: T test_class; }; I added the implem...
The easiest way is to derive from your non-default constructible class. That derived class could be default constructible: class TestableImplementationThree : public ImplementationThree { public: TestableImplementationThree() : ImplementationThree("dummy") {} }; And: using TestTypes = ::testing::...
73,067,159
73,067,616
Set all meaningful unset bits of a number
Given an integer n(1≤n≤1018). I need to make all the unset bits in this number as set (i.e. only the bits meaningful for the number, not the padding bits required to fit in an unsigned long long). My approach: Let the most significant bit be at the position p, then n with all set bits will be 2p+1-1. My all test cases ...
If you need to do integer arithmetics and count bits, you'd better count them properly, and avoid introducing floating point uncertainty: unsigned x=0; for (;n;x++) n>>=1; ... (demo) The good news is that for n<=1E18, x will never reach the number of bits in an unsigned long long. So the rest of you code is not at...
73,067,913
73,074,249
QStringList creation in place for parameter passing
I have a function that gets a QStringList as a parameter. The QStringList is created in place for parameter passing. Two possibilities come to my mind for this: myFunction(QStringList() << myQString); // possibility 1 myFunction(QStringList { myQString }); // possibility 2 Which possibility is more performant?
Here is the benchmark: #define ct_Benchmark(EXPR, repeat){\ int repeated = repeat;\ qint64 initialTime = QDateTime::currentMSecsSinceEpoch();\ qint64 totalTime = initialTime;\ EXPR;\ initialTime = QDateTime::currentMSecsSinceEpoch() - initialTime;\ for ( int ___i_ = 0; ___i_ < repeated; ___i_+...
73,067,975
73,068,140
What are these C++ Macros doing?
I'm new to C++ and trying to understand what these two macros are doing in this FileMaker Plugin Example. #define FMX_PROC(retType) retType __stdcall #define FMX_PROCPTR(retType, name) typedef retType (__stdcall *name) So far I understand that they are both macros, and that the FMX_PROCPTR is a pointer to a...
These macros are just to provide the calling-convention __stdcall into the function being defined, or a function pointer alias. __stdcall is a non-standard compiler-intrinsic that ensures that functions documented with this attribute will be called with the stdcall calling-convention. This applies to the function itsel...
73,068,316
73,106,142
How to make SCons export compile commands including flags pointing to a conda virtual environment?
I'm working on a C++ project that is built with SCons. I installed SCons using my system's package manager. The project has some dependencies that I installed into a virtual environment using conda. I followed the SCons documentation to export a compile_commands.json. When I activate the project's conda environment, th...
I got SCons to export the correct compile commands by adding the line env.Append(CPPPATH= ['/path/to/my/conda/env/include']) to the SConstruct file. I assume the reason for the compilation working even without this line is that the compiler is installed in the same conda environment.
73,068,731
73,156,555
Xerces 3.2 XMLString::transcode not working on special characters
I have this xml file : <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <cmh> <value atr="éè€ç"></value> </cmh> And this simple C++ program using Xerces 3.2.3: ... //const XMLCh* xmlch_OptionA = currentElement->getAttribute(XMLString::transcode("atr")); --> this one always works char* a = "éèç€"; //char* a = ...
The problem was coming from the Docker image I was using (gcc:10.2). The locale for en_US.UTF-8 was not installed on it. So, I installed it and wrote at the beginning of my program: setlocale(LC_ALL, "en_US.UTF-8"); XMLString::transcode works just fine now.
73,069,395
73,069,421
How can I assign a const unsigned char value to a variable inside a condition in c++?
I am using C++ for programming a microcontroller, and I have this situation. I have several const unsigned char in a .h file. Ex: const unsigned char epd_bitmap_icon1 [] = {... const unsigned char epd_bitmap_icon2 [] = {... I have a function that takes one of this variables: void drawBitmap(int16_t x, int16_t y, uint8...
Declare the variable once outside the if, and assign it in the if. const unsigned char *icon; if (batteryChargePercent > 80) { icon = epd_bitmap_icon1; } else if (batteryChargePercent > 30) { icon = epd_bitmap_icon2; } else { icon = epd_bitmap_icon3; } You need to use const in the pointer declaration to so...
73,069,843
73,078,685
Query information about which data members function accesses
Assume the following example code struct Bar { int x, y, z; }; int foo(const Bar& bar) { return bar.x + bar.z; } Is there a way to automatically tell, that foo accesses x and z from bar, but not y? Maybe the compiler (any of gcc, clang, or msvc) can output something like that?
One tool that can do this sort of thing is clang-query, which is included in the Clang+LLVM distribution. clang-query searches the program's Abstract Syntax Tree (AST) for code that matches the given pattern(s). For example, here is a shell script that invokes clang-query to find member accesses: #!/bin/sh # Run clang...
73,069,864
73,071,419
how to output float to tiff using CImg?
I'm trying to have float values in a .tiff file. The values in display are fine, but once on disk, it is unsigned short. #include<X11/Xlib.h> #include "CImg.h" #define cimg_use_tif using namespace cimg_library; int main() { CImg<float> imgFloat(640, 400); for(int i=0; i<640; i++) for(int j=0; j<400; ...
You need: #define cimg_use_tif before (i.e. above) #include "CImg.h" Or actually, preferably define it on the compilation command-line: g++ -D cimg_use_tif ...
73,069,990
73,070,662
How to update (closure) so that it keeps updating
So in this code, what I have to do is, I want to set my ROIto 8% initially, and changes so on It has to be done with closure concept. I got confused here and tried very much before asking for the help. if (Math.random() > 0.5) { const x = 1; } else { const x = 2; } console.log(x); Believe me, I tried so much befo...
If I understand correctly you want to be able to update the rate of interest while externally to the calculating function. Instead of using global variable we use closure. However, since there are 2 functions involved I return them in an object. const createLoanCalculator = (rateOfInterest, principle, term) => { v...
73,070,072
73,071,309
Move dynamic memory to new array, releasing the old memory and not call destructor
I am implementing a storage class a bit different than std::vector and I ran into a problem when expanding the storage. Current code to double the size: //T is template class //_elements is a T* to current array T* old = _elements; _elements = new T[size * 2]; memcpy(_elements, old, size * sizeof(T)); delete[] old; si...
You need to separate memory (de)allocation and constructor/destructor invocation. memcpy won't work for non-trivial types; you should be using std::uninitialized_move instead. The following code is an example of a container allowing to append only. The relevant member function for resizing the storage is emplace_back: ...
73,070,364
73,113,455
How to execute commands in FarManager running in Windows console
I have a client server application. Using the CreateProcess() function, a new process is created on the server, which is actually like a remote console. The client sends a command, it is executed in the server console and returns the result back to the server. To communicate with the console, I use WriteFile() and Read...
I am attaching my solution based on the advice of @YurkoFlisk. Maybe it can be useful for someone //Execute command in FarManager //nVirtKey - code of virtual key to run in far void RunFar(int nVirtKey){ std::cout << "Key code "<< nVirtKey << std::endl; //Create structure with buttons and their state INPUT...
73,070,739
73,070,919
Vector of pointers saving a pointer to a vector of ints
just wondering if you can point to a pointer that points to a vector of ints. And save the pointer that points to a vector of ints. Here's the code I'm trying to pull off. Probably dosen't make sense but I'm trying to make it work for a while now, bare with me. But I want to pull this way somehow. int n, q; cin >> n >>...
I think this is what you're trying to achieve here: int n, q; cin >> n >> q; vector<vector<int>*> ar; for (int i=0;i<n;i++){ int k; cin >> k; vector<int> *vec = new vector<int>; for(int j = 0;j<k;j++){ vec->push_back(cin.get()); } ar.push_back(vec); } // do not forget to delete the i...
73,070,998
73,071,233
Invoking a member function with variadic template parameters that are not part of the function's arguments
Most of the questions I have found revolve around non-member functions where the variadic template parameters are also found in the function's arguments. In my case, I am in a situation where I would like to filter the types coming into one of the variadic member functions and pass the filtered types to another variadi...
You can use template lambda to expand the filtered types and specify them to DoBar explicitly struct Foo { template <typename First_Tag, typename... T_Tags> void Bar(float arg) { using filtered_args = remove_t<First_Tag, T_Tags...>; [&]<typename... T_FilteredTags>(std::tuple<T_FilteredTags....
73,071,015
73,076,467
Change default class item template provided by AddClass Wizard in vs2017
I want to create a class template that would account for the precompiled header if present (which happens with the default add class wizard), but I'd like to expand the barebone template provided by the wizard with a constructor, (possibly virtual) destructor and a bunch of private and public sections. I have read the ...
What you want to achieve is somewhat difficult: override default c++ class template in visual studio 2010 modify item template may be easier: 1.Add class through class wizard and code #pragma once class Myclass { public: Myclass(); ~Myclass(); protected: int test(); private : }; Tool bar: Project-> Expor...
73,071,103
73,071,548
class template specialization based on literal type using enable_if
I am trying to create a Vector class, templated on a type T and number of elements NUM_VALUES . I want the class to use a std::vector to store its elements when NUM_VALUES > 16384 and a std::array<T, NUM_VALUES> to stores its elements when NUM_VALUES <= 16384. At first I tried doing the following: vector.h: #include <a...
Type SFINAE is not part of the C++ standard, but you could easily accomplish the desired results in a different manner. Define seperate templates for both alternatives. Then define an alias template Vector that uses std::conditional_t to detemine the type to use: constexpr std::size_t SmallVectorMaxSize = 16384; templ...
73,071,556
73,074,329
Why a std::get_time() simple example fails parsing on WSL Ubuntu 20.04?
I am trying to run a very simple example of the std::get_time() function but the parse is failing. #include <iostream> #include <sstream> #include <locale> #include <iomanip> int main() { std::tm t = {}; std::istringstream ss("04-02-2022 3:04:32"); ss >> std::get_time(&t, "%m-%d-%Y ...
I was able to reproduce the failure in gcc 9.4. It works if you change 3 to 03 in the hour field. Even though %H is not supposed to require a leading zero, this appears to be a gcc bug where it does. See Bug 78714. Despite being about %b, this comment in that ticket goes into detail about how it also affects %H and ot...
73,071,644
73,071,651
how to use batch in c++
I have a batch program that I would like to add to one of my c++ programs. The batch program tests if a file exists and exits the script if it doesn't. I do not want to add any more libraries to my code. The problem that I have is that I am not sure how I am able to use batch in c++. I am able to figure everything else...
You can use the system(" ") command to use batch.
73,071,707
73,071,791
C++ template argument-dependent lookup
namespace Test { template<typename T> void foo(T a) { g(a); } struct L { int s; }; void bar(L a) { g(a); } } int main() { foo(Test::L{1}); g(Test::L{5}); } namespace Test { void g(L a) {}; } why in foo, g can be found, but in bar and main, g cannot b...
Even without the call to g in main and bar, the program is still ill-formed, but with no diagnostic required. The argument-dependent lookup in a template specialization is done from the point of instantiation of the specialization, not from the point of the definition of the template. The specialization Test::foo<Test:...
73,073,150
73,073,174
variables declaration in anonymous namespace and definition in other place
Can someone explain why I can't define variable that was declared in anonymous namespace as global variable in another place? #include <iostream> namespace { extern int number; } int number = 123; void g() { std::cout << number; } Compiler says that "Reference to 'number' is ambiguous" but I can't understan...
For the unqualified name-lookup the compiler considers also nested unnamed namespaces in the global namespace, You declared two different objects with the same name in the global namespace and in the nested unnamed namespace. The using directive for unnamed namespace is implicitly inserted in the enclosing namespace. C...
73,073,694
73,073,750
CMake generating .sln files and other VS files
I am new to learning CMake, and as I am going through tutorials, I am running the command Cmake -S -B, but instead of creating a makefile, it is making lots of vcxproj files and a Project.sln. From what i understnand, cmake can make VS files, but I want it to just make Makefiles. How do I get it back?
Set "Unix Makefiles" to variable CMAKE_GENERATOR
73,073,696
73,073,725
Mimicking C calloc array behavior in C++
There is some code that exists in C which uses calloc() to create what effectively is a vector. It looks like this: uint64_t *reverseOrder = (uint64_t *)calloc((size + 1), sizeof(uint64_t)); I want to mimic this behavior with C++ syntax and vectors so that it works the same de-facto. Can I use the following syntax? st...
You can just write #include <vector> #include <cstdint> //... std::vector<uint64_t> reverseOrder( size + 1 ); and all elements of the vector will be zero-initialized.
73,074,052
73,084,414
Returning const reference to temporary
Why does the function foo gives the warning "returning reference to temporary" const bool& foo() { return true; } if declaring bar like this is fine and doesn't generate any kind of warning const bool& bar = true; PS: i'm using GCC
songyuanyao answered with what the standard says about it. But that doesn't really explain why they decided c++ should behave this way. It might be easier to think about the code if you think about what the compiler makes of it: const bool& bar = true; The lifetime of the temporary is extended to the lifetime of bar ...
73,074,150
73,087,141
Calling C++/CLI DLL from IronPython leading to an "not a valid Win32 application. (Exception from HRESULT: 0x800700C1)" error
I've been trying to implement this tutorial: https://www.red-gate.com/simple-talk/development/dotnet-development/creating-ccli-wrapper/ and even though it works. When I try to call the Wrapper.dll from IronPython I get an error. I cannot even load the DLL. This is the IronPython code: import clr clr.AddReferenceToFile...
The answer to my question is: re-build all projects in x64 just because IronPython used is x64 build.
73,074,164
73,074,247
Using a C++ DLL in Flutter The type must be a subtype
dll` to my flutter project In .dll I type function: int testdll(int param) { //... } on flutter I type this: final DynamicLibrary nativePointerTestLib = DynamicLibrary.open("assets/SimpleDllFlutter.dll"); final Int Function(Int arr) testdllflutter = nativePointerTestLib .lookup<NativeFunction<Int Function(Int)>>(...
I try call wrond types, correct types: final int Function(int arr) testdllflutter = nativePointerTestLib .lookup<NativeFunction<Int32 Function(Int32)>>("testdll") .asFunction(); and it works
73,074,294
73,075,830
Singleton creating in c++
Why when we use singleton in c++ we create a method to construct static object of class but don't use static object? I mean why we do this: #include <iostream> struct Singleton { public: static Singleton& instance() { static Singleton s; return s; } void getter() { std::cout << "asd...
The short answer is that people do what you are asking about because they want to avoid bugs resulting from global variables being initialized out of order. In particular, suppose that some other global variable made use of the singleton object in its initialization. You'd run the risk that the second object uses the...
73,074,345
73,074,409
private: static class member initialization with inclass setter called by method in different class returns error - unresolved symbols
The question is a duplicate in concept, but the error is articulated differently. Unresolved symbols should be understood as undefined reference. If you are new to C++, please take the time to read the errors generated by my code. I am taking a course in C++ and OOP, and I need some help understanding what I am doing w...
Class static members need to initialize outside a class, that is the reason of link error. class foo { private: static string goo; static long int doo; public: // .... other code }; string foo::goo = ""; long int foo::doo = 0; Use inline keyword in C++ 17, we can defined static member inside class. http://...
73,074,670
73,074,825
Does it make sense to use a reference in this case?
I wonder if it makes sense to use references when using literal constants. Below i made a few examples: bool funcWithoutReference(const std::string Text) { return Text == "Hello!"; } bool funcWithReference(const std::string& Text) { return Text == "Hello!"; } int main() { // Example 1: Average execution t...
Examples 2, 3, and 4 are identical. In each, you create a single std::string per loop iteration. Example 1 does this too, but also copies it. Let's break it down... Example 1 Total string objects: 2 std::string text = "Hello"; funcWithoutReference(text); Every time around the loop, you create a new string, initialized...
73,074,748
73,074,943
Rearrange array non-negative numbers to the left and into ascending order C++
I already arrange non-negative numbers to the left side of the array, now I want to put the sort function to rearrange numbers in ascending order into my program but it didn't work, I can't have them both, can you all help please? I'm totally new to this. int tg; for(int i = 0; i < n - 1; i++){ for(int j = ...
First,a part of your code is this int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 }; but,the output you want is 1 2 3 6 11 -1 -5 -7 You maybe make some mistakes : there is no -7 in the arr I think the code below will solve your problem #include <cstring> #include <iostream> using namespace std; void segregateElements(i...
73,074,752
73,074,860
How can i call class function with its name in c++
Problem: I have to call functions with its callee names in class. I tried function-pointer with map by return the pointer of functions in class, but it seemed that compiler doesn't allow me to do that with the error '&': illegal operation on bound member function expression I want to create a class with function bind...
There are several issues in your code: You need to use pointer to method for your fun type: typedef bool(MyClass::*fun)(int num); When adding the methods to the map, you need to add the class name qualifier, e.g.: v_map.emplace("A", &MyClass::a); When you invoke the method, you need to use the syntax for derefer...
73,075,197
73,075,269
How to call a function in C++?
so i tried making 2 functions and want to display both outputs and im new to C++ how do i fix this issue? Code: #include <iostream> namespace first{ int x = 1; } namespace second{ int x = 2; } int main() { using namespace first; int x = 0; std::cout << x << '\n'; std::cout << first::x << '\n'; std::cout <...
You need to call lol(). Example: int lol(); // forward declaration int main() { using namespace first; int x = 0; std::cout << x << '\n'; std::cout << first::x << '\n'; std::cout << second::x << '\n'; lol(); // calling lol return 0; }
73,075,308
73,075,400
why is it giving error stackoverflow back?
so i have been learning c++ for the past few days and now i have a task to make a Recursion and recursive function. i tried to solve it but it always gives this error back (Unhandled exception at 0x00535379 in cours.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00392FC4).) or sometimes it gives the value o...
There are few other error in you code from C++ perspective, like invalid syntax for main, missing header, etc. But ignoring them for now to concentrate on factorial thing. You main error order of passing a and b to factorialNumber. Correcting it like below will work. int factorialNumber(int a,int b) { int sum; ...
73,075,419
73,075,955
How to convert CComBSTR to LPCSTR
I have CComBSTR in my code and have to pass it to function with argument type LPCSTR. How to convert CComBSTR to LPCSTR?
There are many ways to do this, but the ATL way would be using Using MFC MBCS/Unicode Conversion Macros: void SomeCode() { USES_CONVERSION; CComBSTR bstr(L"hello world"); LPCSTR lp = W2CA(bstr); // bstr is a LPWSTR }
73,075,753
73,075,937
C++ Creating Dynamic 2D Array With One Statement but Without auto
I've seen that a dynamic 2D array in C++ can be created as follows: auto arr{ new int[nRows][nCols] }; nRows and nCols are compile-time known and the size of the array will not change during runtime. I've tested what is the type of arr is PAx_i (where x is nCols). But I cannot figure out what to put instead of auto (i...
C++ does not support dynamically-sized raw arrays (aka Variable Length Arrays, or VLAs). Whenever you come across the need for such a dynamic array (how ever many dimensions it may have), you should be immediately thinking of using the std::vector container. Once properly created, you can use the [] operator (concatena...
73,076,966
73,582,011
SCIP - SCIPOptSuite - LNK2001 - unresolved external symbol
I am new to SCIP and I encounter this problem when I tried to build the branch-and-price framework I obtained from this link. For your reference, I use MS Visual Studio 2019. I have downloaded and installed the precompiled packages. Then, I conducted the following steps in the property of the project I built in VS 2019...
Obtained from @Richard Critten: "...error saying the libscip.dll is not found ..." the directory containing libscip.dll need to be on the PATH or libscip.dll needs to be in the same directory as the executable.
73,077,061
73,081,039
Can static polymorphism (templates) be used despite type erasure?
Having returned relatively recently to C++ after decades of Java, I am currently struggling with a template-based approach to data conversion for instances where type erasure has been applied. Please bear with me, my nomenclature may still be off for C++-natives. This is what I am trying to achieve: Implement dynamic ...
This is a classical double dispatch problem. The usual solution to this problem is to have some kind of dispatcher class with multiple implementations of the function you want to dispatch (get in your case). This is called the visitor pattern. The well-known drawback of it is the dependency cycle it creates (each class...
73,077,170
73,077,288
Why static upcast with virtual inheritance is always correct for GCC?
After learnt from : Why can't static_cast be used to down-cast when virtual inheritance is involved? I'm expecting following code give me the result that shows the static_cast is wrong and dynamic_cast is right. #include <stdio.h> class A { public: virtual ~A() {} int a; }; class B : public virtual A { int b; }...
Not sure, but it seems like you confuse upcasting with downcasting. In your code there are only upcasts, and those are fine. You get the expected compiler error for example with this: D obj; A* a4 = static_cast<A*>(&obj); D* d = static_cast<D*>(a4); gcc reports: <source>: In function 'int main()': <source>:26:28...
73,077,431
73,078,094
How to customize function parameter errors(c++)
I wrote a function that requires two parameters, but I don't want those two parameters to be 0. I want to make the compiler know that those two parameters cannot be 0 through some ways, otherwise the editor will report an error in the form of "red wavy line". I refer to "custom exception class" to solve this problem, b...
There is no integer type without a 0. However, you can provoke a compiler error by introducing a conversion to a pointer type. Its a bit hacky, but achieves what you want (I think) for a literal 0: #include <iostream> struct from_int { int value; from_int(int value) : value(value) {} }; struct non_zero { ...
73,077,492
73,077,613
Does Python have the C++ equavalent of (var = value, var)
In C++ (and maybe C), you are able to do the following: uint8_t one = 0; if ((one = randomUint8t(), one) == 255){ printf("One has the max uint8_t value"); } So you assign the value of the random uint8 function to one, and you return one to be used in the expression evaluation. This particularly useful if you are try...
This is possible since Python 3.8 with assignment expressions aka the "walrus" operator :=. Example: import random if (one := random.randint(0, 255)) == 255: print("one == 255")
73,077,660
73,078,738
Writing data order using boost::asio::async_write
I have two async write operations using boost::asio::async_write boost::asio::async_write(socket, boost::asio::buffer(data1), function); boost::asio::async_write(socket, boost::asio::buffer(data2), function); Does boost guarantee that data will be written to the socket in the exact order in which the write operations ...
Q. Does boost guarantee that data will be written to the socket in the exact order in which the write operations were called? No, in fact it forbids this use explicitly: This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is known as a composed operation. The p...
73,078,126
73,078,453
Explicitly specify additional template arguments - But I have no arguments left to specify
The following code does not compile under clang (tested with version 10.0), but compiles under gcc (tested with version 10.1); C++ version 14. Which of the compilers is correct? template< typename T > int func(); // (1) template< typename ... Args > int func(); // (2) template<> int func<int>() { return 1; } int main ...
The given program(even without the call) is not valid because you're trying to explicitly specialize function template func with information that is not enough to distinguish/disambiguate which func to specialize. A gcc bug report has been submitted here. There are 2 ways to solve this depending on which func you want...
73,079,238
73,081,086
How to use a QTimer only after a QThread is started
I would like to use a QTimer in my MainWindow application. The timer should start when the thread is started. I have tried: ct_thread.h #include <QtCore> #include <QThread> #include <QTimer> class CT_Thread : public QThread { Q_OBJECT public: explicit CT_Thread(QObject* parent = 0); QTimer* timer; void...
I'm assuming the timer should be handled within the thread. You are missing an event loop in the thread. QThread can be implemented with or without event loop. A timer needs an event loop (it cannot just interrupt the code it currently executes in the thread and call the on_timer() method preemtively instead). Calling ...
73,079,481
73,080,947
How to access a variable from another class using Qt C++?
I've been trying to access another class variable, but I can't build the project. QtCreator doesn't show any error / alert. I'm trying to create a ToDo app as a University project and I need to access the name of the list to link the task to the list. I'm sorry for this very simple question but I'm starting out both wi...
To your ListManager.cpp add a line (usually it is placed before any method implementaton) like the following QStringList ListManager::listName; This will instantiate the static variable. The declaration in the header file is just a declaration, then you have to create it somewhere in the code. If you don't istantiate ...
73,079,603
73,079,913
How to make a custom header available system-wide with clang++?
EDIT I have been educated about this topic and I have decided to close this question P.S In the comments, can someone tell me how to close my question? I have some simple C++ code here that I want to compile. I am currently on a mac with MacOS Big Sur running on my computer and I don't have the <bits/stdc++.h> file as...
First of all - it's greatly discouraged to use headers like stdc++.h. If you anyway want to do that, you need to find the system directories your version of clang looks at. Run the following commands in the terminal: % touch file.cpp % clang++ -c file.cpp -v At the bottom it should give you output like this: #include ...
73,079,900
73,080,083
Is there any other option to decrease this piece of code time complexity?
In this code, I'm iterating over a graph of vertices and comparing the weights of each vertex and its neighbors to find the maximum weight between them. Then store the number of times a vertex is marked by its neighbor vertices in X[i]. map<double, list<double>> adjacency; map<double, double> degree; map<double, double...
You can consider to replace one or more of your std::maps with std::unordered_maps. The complexity for searching an item in std::map, using std::map::find is: Logarithmic in the size of the container. This is for worse case (since not mentioned otherwise). On the other hand the complexity for searching an item in std...
73,080,637
73,090,115
OPENGL flickering on updating model uniform to same value
I have looked up almost all related questions regarding flickering in opengl. They all mostly have something to do with z-buffer or perspective projection. However, I'm rendering a single quad on screen that too without depth testing. I update model uniform every frame to the same value and then I get flickering. Howev...
The problem is not with the OpenGL part of your code, but with the way how you transpose your model matrix. The following code *value = mat4_transpose(*value); will override value with it's transposed representation, which means that every second frame the screen is rendered with a wrong matrix. Stop storing the resul...
73,080,686
73,080,763
Incorrect conversion from Raw RGB Depth image to gray
I am working with a simulation in Python equipped with a depth sensor. The visualization it's done in C++. The sensor gives me the following image that I need to convert to gray. For the conversion, I have the next formula: normalized = (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1) in_meters = 1000 * normalize...
It looks like you are dealing with np.float32 array in Python while CV_8UC3 array in C++. Try converting to CV_32FC3 before calculation. // Convert to float and split into channels cv::Mat raw_image_float; raw_image.convertTo(raw_image_float, CV_32FC3); std::vector<cv::Mat> raw_ch(3); cv::split(raw_...
73,080,945
73,081,004
Provide definition of constructor template outside a class template
Consider the following class template with a constructor template: template <class T> class C{ public: T val_; std::string str_; template <typename S> C(const S& str); // C(const S& str) : str_(str) {}; // Valid definition of constructor within class body void print(){std::cout << ...
The correct syntax is: template <class T> template <class S> C<T>::C(const S& str) { // ... } Regarding your second question: One example of using this pattern (of templating a ctor) is the way to achieve type-erasure in C++ using templates. This article has some examples: https://quuxplusone.github.io/blog/2019/0...
73,080,946
73,081,011
How can I run .exe external application with C++ and VS? And continue execute my C++ code?
I solved it with command System(.. .exe); And .exe application starts. But my VS C++ code stops and will continue only when I'll close started .exe application. How can I continue my C++ code with opened and run .exe application?
You can either fork your process, and start your application in the child process, or you can run a new thread which will block untill your application terminates.
73,081,412
73,081,486
Can't access private constructor from a friend class
In the following code snippet, g++ compiler outputs the following error: error: ‘B::B(const string&)’ is private within this context 857 | { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); } Commenting out the line where smart pointers are used seem to work. However, I'm not sure why it works for t...
The problem is that make_unique which is supposed to construct an instance of B is not a friend of B. Therefore it does not have access to B's private constructor. You can use the following to achieve something similar: std::unique_ptr<B> pB2 = std::unique_ptr<B>(new B("dummy3")); In general it is advised to prefer ma...
73,081,417
73,081,603
Why there is linker error in this code even though the function body exist
I am not able to understand that why this code gives linker error. I have a project with these two files myclass.cpp class MyClass { public: void SomeFun(){ ... } // SomeFun is defined here }; main.cpp class MyClass { public: void SomeFun(); // SomeFun is declared here }; int main() { MyClass obj;...
This in myClass.cpp class MyClass { public: void SomeFun(){ ... } // SomeFun is defined here }; Is a definition for MyClass. This in main.cpp class MyClass { public: void SomeFun(); // SomeFun is declared here }; Is another definition of MyClass. The one-definition-rule (ODR) states: Only one definit...
73,082,491
73,088,991
operator[] - differentiate between get and set?
Are there any advances in recent C++ that allows for differentiating between getting and setting values via the operator[] of a class? (as Python does via __setitem__ and __getitem__) const T& operator[](unsigned int index) const; T& operator[](unsigned int index); I am wrapping an std::unordered_map, and want to let ...
Assume your wrapper class implements set and get methods that perform the appropriate record keeping actions. The wrapper class can then also implement operator[] to return a result object that will delegate to one of those methods depending on how the result is used. This is in line with the first related question you...
73,082,887
73,083,018
std::replace - Compiler deduces a char type from const char* literal converted explicitly to string
I want to replace my buffer string from a value of "eof" to "\0" using std::replace. std::string buffer = "eof"; std::replace(buffer.begin(), buffer.end(), std::string("eof"), std::string("\0")); Compiler error : no match for ‘operator==’ (operand types are ‘char’ and ‘const std::__cxx11::basic_string<char>’)
The problem is that internally std::replace checks == on *first and old_value where first is the first argument passed(iterator here) and old_value is the third argument passed shown in the below possible implementation: template<class ForwardIt, class T> void replace(ForwardIt first, ForwardIt last, const...
73,083,214
73,083,239
what does this line of syntax mean in c++?
this is a quick question, Im translating a program that's in C++ to C, and I saw this line of code, for (int v : adj[u]) { referenced in this article: link and I am not really sure what it does. I tried googling it and got results for range based for loops in C++, but cannot find anything that has this exact syntax ...
It's a very simple for loop that iterates over the elements of adj[u], going 1 by 1.
73,083,485
73,117,968
QTableView, select row and shift+click
I have a QTableview in an app, the selectionMode is set to QAbstractItemView::ExtendedSelection. I have a button from which I select a specific row of the table view, using below call. myTableView->selectRow(rowNumber); The problem is, that if I have a row i selected. then press my button, row j is selected. Then when...
Looks like you are facing similar issue to what you linked: you don't set current index together with selection change. Small example to illustrate: int main(int argc, char* argv[]) { QApplication app(argc, argv); QStringListModel model( { "First", "Second", "Third", "Fouth" }); auto p_view = new QTabl...
73,083,498
73,085,877
Disable prevent windows log event
I'm using WMI (Windows Management Instrumentation) to try to collect some information from a allot of remote computers. The issue is that every time I try to initiate a connection to a remote computer/resource using: //IWbemLocator::ConnectServer method (wbemcli.h) m_pLoc->ConnectServer .... where IWbemLocator *m_pLoc...
Looking at the message logged in EventViewer more closely, I can see that this is a DCOM thing, and it looks like you can turn DCOM error logging off by (as usual) tweaking the registry. The key you want is: HKEY_LOCAL_MACHINE SOFTWARE Microsoft Ole And then create a DWORD value in there called...
73,083,545
73,083,695
About function declarations in functions
We can have function declarations inside of function bodies: void f(double) { cout << "f(double) called"; } void f(int) { cout << "f(int) called"; } void g() { void f(double); //Functions declared in non-namespace scopes do not overload f(1); //Therefore, f(1) will call f(double) ...
This can also be used to limit the visibility of a function declaration to only one specific function. For example: file1.cpp: #include <iostream> void f(double d) { std::cout << d << '\n'; } file2.cpp: int main() { void f(double); f(1); // prints 1 } void g() { f(2); // error: 'f' was not declared in t...
73,083,861
73,083,910
No matching function compile error when passing lambda expression to a templated caller function?
Code: #include <iostream> template <class FunctorType> void caller(const FunctorType& func) { func(); } int main() { double data[5] = {5., 0., 0., 0., 0.}; auto peek_data = [data]() { std::cout << data[0] << std::endl; }; auto change_data = [data]() mutable { data[0] = 4.2; }; caller(peek_data); // This...
A mutable lambda has a non-const operator(). You are trying to call this non-const operator() through a const reference. That doesn't work for the same reason that calling any non-const non-static member function doesn't work through a const reference. If you want to allow caller to modify the passed function object (...
73,084,516
73,115,307
C++ printing unicode characters gives question marks
I want to start by saying I know how to print Unicode characters to console using _setmode(_fileno(stdout), _O_U16TEXT). The problem I have is with printing Unicode characters that are "non-standard". For example, when I try to print ▁ ▂ ▃ ▄ ▅ ▆ ▇ █ ▇ ▆ ▅ ▄ ▃ ▁ using wprintf, it returns this: The project is set to "Un...
From what I have found so far. there is no easy work around except for using another font which does include those characters. What I ended up doing was just editing the font using Fontlab. If anyone else ends up follow my footsteps. once you finish editing: change the font name unless you want to overwrite the existi...
73,085,423
74,020,681
Is there an equivalent of submdspan for mdarray?
The repo of the exciting mdspan, a multi-dimensional analogue of std::span suggested for the C++ standard libraries, now also contains a reference implementation of the closely-related mdarray, which unlike mdspan owns its data. But whereas the submdspan function can produce a subset of an mdspan, I can't find an analo...
Just randomly ran across this: since I am the primary author/maintainer on all involved things (mdspan, mdarray, submdspan and the reference implementation) yeah we can add that. And the way I would do that is actually calling the "to_mdspan" function of the mdarray, and call submdspan on that: auto sub = submdspan(mda...
73,085,590
73,112,962
Shuffle a 2D string array
I'm doing a C++ program, in which I want to shuffle an array (or part of an array). Here is the array: string colorTheme[8][8] = { {"blue", "blue", "green", "green", "violet", "violet", "teal", "teal"}, {"beige", "beige", "red", "red", "indigo", "indigo", "pink", "pink"}, {"c...
The best way to tackle this problem is to convert the 2D array into 1D, as shuffling a 1D array is a lot simpler. Under the covers, create an int array shuffler; fill an int array with values from 0 - n^2 and shuffle them using something like rand. From there, use the values in the int array as new positions for your s...
73,086,234
73,086,624
malloc.cpp not found, header IS included
I am aware of this question and its solution. Its solution (to include two header files listed below) is already in the code, so the post was unhelpful relative to my program. I am working on an MFC program, using an old version of ZLib, specifically its 2005 version. To practice with the zipping library, I attempted ...
Turns out there is no issue at all. C++ console programs are different from MFC here. Stepping through that line in a console program is the same as stepping OVER that line in MFC. In MFC, you are actually given the option of seeing the assembly or rather, disassembly, code, by clicking a Disassembly option in the bott...
73,086,801
73,087,143
Why explicit-ness of std::pair's heterogeneous "move"-constructor changed in C++17?
Pardon the convoluted title, and consider this code: #include <memory> #include <utility> using X = std::unique_ptr<int>; using A = std::pair<int, const X>; using B = std::pair<int, X>; static_assert(std::is_constructible<A, B>::value, "(1)"); // Ok. static_assert(std::is_convertible<B, A>::value, "(2)"); // R...
The relevant constructors have not been explicit before C++17 either. GCC and Clang in pre-C++17 mode are actually considering std::is_convertible<B, A>::value false because A's move constructor is implicitly deleted. The move constructor is implicitly deleted, because a const std::unique_ptr cannot be moved or copied....
73,086,879
73,086,913
const char* pointer handling (C++)
Hi everyone I have a simple task in C++: -> writing a program that takes a string from user input and loops over the characters in the string via a pointer. If I understand correctly, then a previously declared string name; variable can also be accessed via const char*, implying that I can declare a pointer in the foll...
The operator << overloaded for a pointer of the type char * such a way that it outputs the string pointed to by the pointer. So according to the assignment instead of these statements const char *pName = &(name[0]); cout << pName << endl; you need to use a loop like for ( const char *pName = &name[0]; *pName != '\0'...
73,087,181
73,108,824
Boost SML: respond to determination made in action
I am trying to use a Boost SML state machine to implement a "receiver". As an example, lets say the SM receives ints and is "done" when it gets to a certain number: An "idle" state moves to a "reading" state on a "receive" event, accumulate the received data If the limit is reached, terminate, or else keep reading I ...
I think that your state machine can described as follows: sml doesn't support choice puseudo state (rhombus shape in the diagram) but we can use "normal" state instead. The diagram use if/else branch from the choice pseudo state. But it doesn't supported in sml. So I define gDone and gNotDone. It is the similar as def...
73,087,452
73,093,141
Why can't Clang get __m128's data by index in constexpr function
#include <cstddef> #include <immintrin.h> constexpr float get_data(__m128 a, std::size_t pos) { return a[pos]; } It works on GCC. I wonder is there any workaround to make it possible
Regardless of constexpr, a[pos] is only valid as a GNU C extension, not portable to MSVC. Storing to an array, or C++20 std::bit_cast to a struct might work. bit_cast is constexpr-compatible, unlike other type-punning methods. Although I'd be worried about how efficiently that would compile across compilers for runtim...
73,087,819
73,088,136
For loop not incrementing only when qInfo looks for array value
#include <QCoreApplication> int ages[4] = {23,7,75,1000}; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qInfo() << ages; for (int i = 0; i < 5; i++){ qInfo() << i; } a.exec(); return 0; } returns: 0x7ff7d01f3010 ...
You have undefined behaviour in your code because you are indexing the array out of its size. Your array has four elements, but you seem to try to access 5 elements in its. So, the last iteration is undefined behaviour. You could write this instead: #include <QCoreApplication> int ages[4] = {23,7,75,1000}; int main(i...
73,088,437
73,088,736
The next prime number
Among the given input of two numbers, check if the second number is exactly the next prime number of the first number. If so return "YES" else "NO". #include <iostream> #include <bits/stdc++.h> using namespace std; int nextPrime(int x){ int y =x; for(int i=2; i <=sqrt(y); i++){ if(y%i == 0){ ...
I can tell you two things you are doing wrong: Enter 2 4 and you will check 4, 6, 8, 10, 12, 14, 16, 18, ... for primality forever. The other thing is y = y+2; nextPrime(y); return (y); should just be return nextPrime(y + 2); Beyond that your loop is highly inefficient: for(int i=2; i <=sq...
73,088,690
73,088,967
How to use QGeoCoordinate in Qt C++ , especially the azimuthTo() and distanceTo() objects?
This is my code: After specifying two different coordinates (geo and geo2), how can I know the distance between them using distanceTo() //enter code here QGeoCoordinate geo; geo.setLatitude(90); geo.setLongitude(90); QGeoCoordinate geo2; geo2.setLatitude(53.213456); geo2.setLongitude(-9.182547); edit: I have read the ...
As per the documentation, it is a simple call of taking one of the two QGeoCoordinate objects and pass the other object to its member function. So your code becomes: QGeoCoordinate geo; geo.setLatitude(90); geo.setLongitude(90); QGeoCoordinate geo2; geo2.setLatitude(53.213456); geo2.setLongitude(-9.182547); qreal dista...
73,088,871
73,088,958
Are 'volatile' and 'side effect' related?
Just a beginner question. In the code from cppreference.com, there is a comment saying, "make sure it's a side effect" on the line using std::accumulate. What is the author's intention in saying this? Is it related to the volatile int sink? (Maybe it means something like "make sure the sink is not optimized by the com...
Not necessarily. C++ has the 'as if' rule. The compiler must generate code that works 'as if' the source code was executed, but it doesn't have to do everything that the source code does, in exactly the same order. Now look at the sink variable. After the line you mention it's never used again. So it's value has no vis...
73,089,019
73,089,144
Cannot infer template argument 'T' when a second parameter includes 'T'
Given this template function: template < typename T, typename U, typename = std::enable_if< std::is_same_v<U, std::unique_ptr<T>> || std::is_same_v<U, std::shared_ptr<T>>>> T foo(U val) { if constexpr (std::is_same_v<U, std::unique_ptr<T>>) { return *val; } return *val; } I want t...
SFINAE constraints don't affect template argument deduction. Your compiler has to deduce T and U first, without even looking at your enable_if_t<...>. I'd do something like this: #include <memory> #include <type_traits> namespace impl { template <typename A, template <typename...> typename B> struct specializa...
73,089,421
73,089,442
Why can't we assign the value to a non-initialized string within a for loop in c++?
I'am learning c++ and I've a question like why can't we initalize a given string in a for loop. string s, result; cin >> s; for(int i=0; i<s.length(); i++){ result[i] = s[i]; } cout << result; There simply won't be cout ofcourse. Because result string never got initialized in a for loop? Please explain why? The...
result has the length 0 so using the subscript operator to dereference and assign any element (except assigning \0 to the terminating \0) has undefined behavior. If you want to append a char to the string: result += s[i];
73,089,542
73,089,589
C++: Finding average for each salesperson from a text file
I need to calculate the average sales for each salesperson from a text file. My code will produce the correct output as the sample, but will not work if I add more information to the file without manually modifying the code. I'm completely stuck on this, tried many different methods that I know but they doesn't complet...
This is caused by the static person count in your code, please try to replace the 4 with a larger constant. const int PERSON_COUNT = 100; void read() { int i = 0; Sales sale[PERSON_COUNT]; fstream read, read2; read.open("Sales.txt"); while(!read.eof()) { read.ignore(); getline(r...
73,089,920
73,091,007
game of stacks in which number is removed from top until it amounts to greater that given max sum
I'm trying to solve this hacker rank problem, which gives us two integer stacks and a maxSum variable assigned to a particular value and asks us to find total number of elements removed from top from both the stacks until sum of all number removed from stacks does not become greater than the given maxSum. example; stac...
Your code assumes that there is a "greedy" approach to ensure you find the maximum possible number of removals. But this is not true. It is not always best to take the minimum value among the two stack tops. For example, stack B could start with a rather great value, but have many small values after it, which would mak...
73,090,139
73,090,489
static member std::function of template class gets empty despite initalization
Consider the following class: template <class T> struct Test { Test() { if (!f) { f = []() { std::cout << "it works\n"; }; initialized = true; } } static void check() { if (f) f(); else std::cout << "f is empty\n"; } T x{}; inline static st...
The problem is related to the order of initialization of static variables which I guess is solved differently for the templated instantiated static variables compared to Test<double> on different compilers. inline static Holder f; is a static variable, so somewhere before entering main it will be default initialized (...
73,090,157
73,090,806
How to use library fmt with clang
My code is like #include "fmt/compile.h" int main() { using namespace fmt::literals; auto result = fmt::format("{}"_cf, FMT_VERSION); printf("%s", result.data()); } It cannot compile with clang. The compilation result can be seen here How can I make it work with clang. thx
Build of fmt depends on a bunch of macros. Here, build fails because operator () ""_cf is not defined in the clang version. If you look at the code you'll see it depends on macro FMT_USE_NONTYPE_TEMPLATE_ARGS for whatever reason. Probably godbolt at inclusion of fmt doesn't declare the macro to be true for clang. Regar...
73,090,519
73,090,679
what does vector<int> dist(n, INT_MAX); mean in C++?
i am new to C++ and I was wondering what the below code does. I tried googling but could not find the answer. Thanks vector<int> dist(n, INT_MAX);
The line of code serves to declare a variable called dist, and to initialise it is a std::vector object. The <int> part of the vector initialisation is called a template argument. The std::vector class is templated, which means it can store any arbitrary data-type, which is why the type has to be declared within angled...