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,635,160
| 73,635,667
|
How to solve Boost Error: terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
|
I am trying to use Boost for creating a shared memory. This is my code:
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#define BUF_SIZE 1*1024*1024
int main()
{
shared_memory_object tx_data_buffer(create_only ,"tx_data_memory", read_write);
tx_data_buffer.truncate(BUF_SIZE);
mapped_region tx_region(tx_data_buffer, read_write);
//Get the address of the region
cout << "\n\nTX Data Buffer Virtual Address = " << tx_region.get_address() << endl;
//Get the size of the region
cout << "\n\nTX Data Buffer Size = " << tx1_region.get_size() << endl;
}
I ran the above code succesfully a few times before (not sure whether it was one time or more than one times). But when I am trying to run the same code again, it is giving me the following error:
terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
what(): File exists
I am running the code on Eclipse in Linux. Any idea as to what is causing this?
|
You're specifically asking the shared_memory_object to open in create_only mode. Of course, when it exists, it cannot be created, so it fails. The error message is very clear: "File exists".
One way to resolve your problem is to use open_or_create instead:
namespace bip = boost::interprocess;
bip::shared_memory_object tx_data_buffer(bip::open_or_create ,"tx_data_memory", bip::read_write);
Or, alternatively, explicitly delete the shared memory object:
bip::shared_memory_object::remove("tx_data_buffer");
bip::shared_memory_object tx_data_buffer(bip::create_only, "tx_data_memory",
bip::read_write);
Keep in mind that you have synchronize access to shared memory from different threads.
|
73,635,173
| 73,635,476
|
C++ template runtime choices
|
I would like to improve the following runtime template selection code:
We have 4 functors for p-norm calculation (1 general case, 3 specialized cases). During runtime, we can select the best one.
template <typename T>
struct p_norm { // contains functors to calculate p-norm
struct general { ... }; // general case
struct one { ... }; // specialize for p=1
struct two { ... }; // specialize for p=2
struct inf { ... }; // specialize for p=inf
};
For example, we can get the distance based on p,
auto impl_fptr = distance_fn<T, p_norm<T>::general>;
if (p == 1.0) {
impl_fptr = distance_fn<T, p_norm<T>::one>;
} else if (p == 2.0) {
impl_fptr = distance_fn<T, p_norm<T>::two>;
} else if (std::isinf(p)) {
impl_fptr = distance_fn<T, p_norm<T>::inf>;
}
impl_fptr(vec1, vec2);
or maybe get the angle based on p,
auto impl_fptr = angle_fn<T, p_norm<T>::general>;
if (p == 1.0) {
impl_fptr = angle_fn<T, p_norm<T>::one>;
} else if (p == 2.0) {
impl_fptr = angle_fn<T, p_norm<T>::two>;
} else if (std::isinf(p)) {
impl_fptr = angle_fn<T, p_norm<T>::inf>;
}
impl_fptr(vec1, vec2);
The problem is that there are a lot of code duplications in selecting a suitable template case. I have no clue on how to improve the type selection.
OTOH, the minor problem is that I would like to implement p_norm<double> for the general case and implement p_norm<1.>, p_norm<2.>, ... for template specialization. I know it's not how the template works, but is there any way to make the specialization more obvious? Probably via tag dispatching?
|
std::variant with tag (std::type_identity here) might help:
template <typename T>
std::variant<std::type_identity<p_norm <T>::general>,
std::type_identity<p_norm <T>::one>,
std::type_identity<p_norm <T>::two>,
std::type_identity<p_norm <T>::inf>>
get_method_var(double d)
{
if (d == 1.0) { return std::type_identity<p_norm <T>::one>{}; }
else if (d == 2.0) { return std::type_identity<p_norm <T>::two>{}; }
else if (std::isinf(d)) { return std::type_identity<p_norm <T>::inf>{}; }
else { return std::type_identity<p_norm <T>::general>{}; }
}
and then
template <typename T>
auto distance(const auto& vec1, const auto& vec2, double p)
{
return std::visit([&](auto tag){
return distance_fn<T, typename decltype(tag)::type>(vec1, vec2);
}, get_method_var<T>(p));
}
template <typename T>
auto angle(const auto& vec1, const auto& vec2, double p)
{
return std::visit([&](auto tag){
return angle_fn<T, typename decltype(tag)::type>(vec1, vec2);
}, get_method_var<T>(p));
}
|
73,635,636
| 73,644,207
|
No .lib file generated after building tiny C++ static library project
|
I decided on adding a tiny extra project to my visual studio solution which includes only a single header file(for now) with a mutex which allows only 1 thread to output to the console at a time. Since this is a functionality which all of my projects in my solution will need so I thought it will be best to add a separate project for it and add references to it on the other projects.
So I created an empty project named Commons, then added an header file logger_mutex.h and wrote the following code inside it.
#pragma once
#ifdef _DEBUG
#include <mutex>
std::mutex loggerMutex;
#endif
I changed the project type in properties from Application(.exe) to Static Library (.lib). Then I added the include path to this file in the other project properties. Also I added this Commons project as a reference to all my other projects. But now when I try to build the solution it gave the error LINK1104 cannot open file ../path/to/my/output/directory/Commons.lib
I investigated on the output directory and there was no file in there named Commons.lib. I tried rebuilding the Commons project separately, and even though visual studio said it built successfully I did not see the Commons.lib file appear on the output directory.
I tried it even without the other projects, in a completely different solution. It still did not generate any .lib file in the output directory. I think this should be verifiable as well.
So what am I missing here, is there some kind of minimum requirement needed to have to get a .lib output file generated? Is my code too small to generate a .lib output? I am using Visual Studio 2022.
|
Add one empty .cpp file in your lib project and a lib will be generated.
But as far as I am concerned, it will be better to #include the logger_mutex.h to other project's pch.h instead of as a library.
|
73,638,117
| 73,638,246
|
What precision is used by std::chrono::system_clock?
|
Here's some code that I found:
std::cout << std::chrono::system_clock::now().time_since_epoch().count() << std::endl;
This prints 1662563612364838407 for me; so it looks like this prints the number of nanoseconds since the UNIX epoch (1970-01-01).
But is this precision guaranteed? I didn't find any indication at https://en.cppreference.com/w/cpp/chrono/system_clock that this value will always be in nanoseconds. Is it possible that this will return e.g. microseconds with another compiler, operating system or hardware?
|
No it is not guaranteed. You can use the clocks period member alias to get tick period in seconds:
#include <chrono>
#include <iostream>
int main() {
std::cout << std::chrono::system_clock::period::num << " / " << std::chrono::system_clock::period::den;
}
Possible output:
1 / 1000000000
|
73,638,202
| 73,639,359
|
How to implement copyable and movable wrapper around reference counted type?
|
Suppose a C API provides an opaque struct with internal reference counting:
struct Opaque {
int data;
int refcount;
};
struct Opaque* opaque_new(int data) {
return new Opaque {
.data = data,
.refcount = 1
};
}
int opaque_data(struct Opaque* opaque) {
return opaque->data;
}
struct Opaque* opaque_ref(struct Opaque* opaque) {
opaque->refcount++;
return opaque;
}
void opaque_unref(struct Opaque* opaque) {
opaque->refcount--;
if (!opaque->refcount) {
delete opaque;
}
}
How to create a wrapper type that is copyable, movable, copy assignable and move assignable?
So far I have:
#include <algorithm>
class Wrapper {
public:
Wrapper() : m_opaque(nullptr) {}
explicit Wrapper(int data) : m_opaque(opaque_new(data)) {}
Wrapper(const Wrapper&) = delete; // TODO
Wrapper(Wrapper&& wrapper) : m_opaque(wrapper.m_opaque) {
wrapper.m_opaque = nullptr;
}
Wrapper& operator=(const Wrapper&) = delete; // TODO
Wrapper& operator=(Wrapper&& other) {
swap(other);
return *this;
}
~Wrapper() {
if (m_opaque) {
opaque_unref(m_opaque);
}
}
void swap(Wrapper& other) {
std::swap(m_opaque, other.m_opaque);
}
int getData() const {
if (m_opaque) {
return opaque_data(m_opaque);
} else {
return 0;
}
}
private:
struct Opaque* m_opaque;
};
I specifically don't want reference counting on top of reference counting, using std::shared_ptr with a custom deleter.
What's a concise way to implement the remaining methods, in particular copy assignment? Is there a better way to implement the ones I got so far?
|
Boost's intrusive_ptr was made for "internal reference counts":
#include <boost/intrusive_ptr.hpp>
// intrusive_ptr API functions
inline void intrusive_ptr_add_ref(Opaque* opaque) noexcept {
::opaque_ref(opaque);
}
inline void intrusive_ptr_release(Opaque* opaque) noexcept {
::opaque_unref(opaque);
}
struct Wrapper {
public:
// Boost.intrusive_ptr operators are fine
Wrapper() noexcept = default;
Wrapper(const Wrapper&) noexcept = default;
Wrapper(Wrapper&&) noexcept = default;
Wrapper& operator=(const Wrapper&) noexcept = default;
Wrapper& operator=(Wrapper&&) noexcept = default;
// (false means don't add a refcount, since opaque_new does that)
explicit Wrapper(int data) : m_opaque(opaque_new(data), false) {
// if (!m_opaque) throw std::bad_alloc();
}
void swap(Wrapper& other) noexcept {
m_opaque.swap(other.m_opaque);
}
friend void swap(Wrapper& l, Wrapper& r) noexcept {
l.swap(r);
}
int getData() const {
if (m_opaque) {
return ::opaque_data(m_opaque.get());
} else {
return 0;
}
}
private:
boost::intrusive_ptr<Opaque> m_opaque;
};
https://godbolt.org/z/oGEdd66Yo
You could also implement this with the "Copy-and-swap" idiom:
Wrapper(Wrapper&& other) noexcept : m_opaque(std::exchange(other.m_opaque, nullptr)) {}
Wrapper(const Wrapper& other) : m_opaque(other.m_opaque) {
if (m_opaque) opaque_ref(m_opaque);
}
// Also works for move assign
Wrapper& operator=(Wrapper copy) noexcept {
this->swap(copy);
return *this;
}
Unrelated, but your C function opaque_new should not throw C++ exceptions (when new fails). You can use new (std::nothrow) Wrapper { ... } so that it returns nullptr instead of throwing an exception. Or you could have it abort instead of throwing.
And would it really hurt to have a nullptr check inside the functions?
|
73,638,331
| 73,640,445
|
boost::asio SerialPort unable to receive data
|
I am unable to receive data over serial port in boost::asio while using asynchronous. When I use synchronous routines I am able to receive data.
Code :
SerialPort.cpp
bool SerialPort::read_async(std::uint32_t read_timeout)
{
try
{
if (read_timeout not_eq SerialPort::ignore_timeout)
this->read_timeout = read_timeout;//If read_timeout is not set to ignore_timeout, update the read_timeout else use old read_timeout
this->port.async_read_some(boost::asio::buffer(this->read_buffer.data(), this->read_buffer.size()),
boost::bind(&SerialPort::read_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
return true;
}
catch (const std::exception& ex)
{
PLOG_ERROR << ex.what();
return false;
}
}
void SerialPort::read_handler(const boost::system::error_code& error, std::size_t bytes_transferred)
{
std::string received_data_buffer;
std::transform(this->read_buffer.begin(), this->read_buffer.begin() + bytes_transferred,
std::back_inserter(received_data_buffer), [](std::byte character) {
return static_cast<char>(character);
});
PLOG_INFO << "In Read Buffer : " << received_data_buffer;
}
bool SerialPort::open_port(void)
{
try
{
this->port.open(this->port_name);
return true;
}
catch (const std::exception& ex)
{
PLOG_FATAL << ex.what();
}
return false;
}
SerialPort.hpp
class SerialPort
{
private:
boost::asio::io_context io;
boost::asio::serial_port port;
boost::asio::serial_port::native_handle_type native_port;
std::string port_name;
const static std::uint32_t READ_BUFFER_MAX_LENGTH{ 8096 };
std::array<std::byte, SerialPort::READ_BUFFER_MAX_LENGTH> read_buffer;//Used in synchronous read
void read_handler(
const boost::system::error_code& error, // Result of operation.
std::size_t bytes_transferred // Number of bytes read.
);
//boost::asio::deadline_timer timer;
public:
SerialPort() : io(), port(io), thread_sync_read()
{
}
~SerialPort();
bool open_port(void);
bool read_async(std::uint32_t read_timeout = SerialPort::ignore_timeout);
};
main.cpp
SerialPort sp;
int main()
{
sp.open_port("COM11");
sp.write_sync("Testing123");
sp.read_async();
while (true)
{
}
return 0;
}
|
You're supposedly trying to do some operations asynchronously.
Firstly, mixing synchronous and asynchronous operations is not always advisable. Some services/IO objects might hold inner state that assumes one or the other.
Secondly, the asynchronous operation requires the io_service to be run. That doesn't happen. You could make it explicit instead of the current while() loop.
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
#include <iostream>
namespace asio = boost::asio;
using boost::system::error_code;
std::ostream PLOG_INFO(std::clog.rdbuf());
std::ostream PLOG_ERROR(std::clog.rdbuf());
std::ostream PLOG_FATAL(std::clog.rdbuf());
class SerialPort
{
public:
SerialPort()
: io_()
, port_(io_) /*, thread_sync_read()*/
{}
~SerialPort() = default;
bool open_port(std::string name);
static constexpr uint32_t ignore_timeout = -1;
bool read_async(std::uint32_t read_timeout = SerialPort::ignore_timeout);
void run() { io_.run(); }
private:
static constexpr uint32_t READ_BUFFER_MAX_LENGTH{8096};
asio::io_context io_;
asio::serial_port port_;
std::string port_name_;
uint32_t read_timeout_ = ignore_timeout;
// asio::deadline_timer timer;
std::array<std::byte, READ_BUFFER_MAX_LENGTH> read_buffer_;
void read_handler(error_code error, size_t bytes_transferred);
};
bool SerialPort::read_async(std::uint32_t read_timeout) {
try {
if (read_timeout != SerialPort::ignore_timeout)
read_timeout_ =
read_timeout; // If read_timeout is not set to ignore_timeout,
// update the read_timeout else use old
// read_timeout
port_.async_read_some(
asio::buffer(read_buffer_.data(), read_buffer_.size()),
boost::bind(&SerialPort::read_handler, this,
asio::placeholders::error,
asio::placeholders::bytes_transferred));
return true;
} catch (const std::exception& ex) {
PLOG_ERROR << ex.what() << std::endl;
return false;
}
}
void SerialPort::read_handler(error_code error, size_t bytes_transferred) {
std::string s;
std::transform(
read_buffer_.begin(), read_buffer_.begin() + bytes_transferred,
std::back_inserter(s),
[](std::byte character) { return static_cast<char>(character); });
PLOG_INFO << "In Read Buffer : " << s << " (" << error.message() << ")" << std::endl;
}
bool SerialPort::open_port(std::string name) {
try {
port_name_ = std::move(name);
port_.open(port_name_);
return true;
} catch (std::exception const& ex) {
PLOG_FATAL << ex.what() << std::endl;
return false;
}
}
SerialPort sp;
int main(int argc, char** argv) {
sp.open_port(argc > 1 ? argv[1] : "COM11");
// sp.write_sync("Testing123");
sp.read_async();
sp.run();
}
|
73,639,728
| 73,641,444
|
How to use `--start-group` and `--end-group` in CMake
|
Is it possible to use CMake to enclose a target's libraries in --start-group/--end-group without manually writing the argument string into target_link_options?
Background: I'm having library ordering issues when linking a C++ executable to a list of libraries (using g++ 7.5.0). I recently learned about the --start-group and --end-group options in gcc/g++ that allow for repeated searching of archives. I would like to enable these options when using CMake to generate my build files.
Given a list of target library names (e.g. target_link_libraries(myTarget mylibrary1 mylibrary2 ${MY_VARIABLE_LIST_OF_LIBRARIES} ...)), is it possible to enclose all those libraries within --start-group/--end-group without having to manually type out the arguments as in target_link_options(myTarget PUBLIC "--start-group -lmylibrary1 -lmylibrary2 ... --end-group")? (I'd especially like to avoid having to track down the contents of ${MY_VARIABLE_LIST_OF_LIBRARIES}" to manually add -l to all libraries included in that variable.)
|
CMake 3.24 introduces LINK_GROUP generator expression, which allows to group libraries in target_link_libraries command for adding some feature on that group. One of the group features is RESCAN, which effectively adds --start-group/--end-group for a GNU compiler:
target_link_libraries(myTarget
PRIVATE # or any other keyword
mylibrary1 mylibrary2 # These libraries will be linked normally
"$<LINK_GROUP:RESCAN,${MY_VARIABLE_LIST_OF_LIBRARIES}>" # These libraries will be grouped
)
|
73,640,094
| 73,640,733
|
Why are two destructors created for googletest test fixture when not placed in unnamed namespace?
|
When I analyze gcov results for the following code (after using c++filt to demangle), I see two FooTest::~FooTest() in the coverage information file, both mapped to the same line number. One is marked as called and the other is not. Note: No compiler optimizations are used (i.e. -O0).
#include "gtest/gtest.h"
struct FooTest : ::testing::Test {
~FooTest() = default;
};
TEST_F(FooTest, run) {}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
If I put the declaration of FooTest in the unnamed namespace, I only see 1 destructor (anonymous namespace)::FooTest::~FooTest() in the coverage info.
#include "gtest/gtest.h"
namespace {
struct FooTest : ::testing::Test {
~FooTest() = default;
};
}
TEST_F(FooTest, run) {}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
I realize that the visibility of FooTest is different when placed in the unnamed namespace. But, I wouldn't have expected that to cause the difference since the translation unit is compiled without optimizations.
What precisely is happening to cause gcov to report two destructors with the same signature to exist when the test fixture is not placed in the unnamed namespace?
|
The link posted by Eljay, https://stackoverflow.com/a/6614369/4641116, contains an explanation as to why multiple dtors are created.
In the code snippit above, the base object destructor (D2) is called by the derived test class defined via the TEST_F macro. The deleting destructor (D0) is not called by the program and hence not reported as covered by GCOV.
When the class has default visibility, the compiler cannot prove that no one outside the translation unit might require the deleting destructor, which is why it is created.
|
73,640,182
| 73,640,837
|
Return an array from a function in c++
|
I'm trying to implement a function that returns an array, I came to this solution, but I don't know if it is a good practice, that's how I did it:
#include <iostream>
using namespace std;
int* returnNewArray(int n) {
int* arr = new int[n];
for (int i=0;i<n;i++)
arr[i] = i;
return arr;
}
int main() {
int n = 5;
int* arr = returnNewArray(n);
for (int i=0;i<n;i++)
cout << arr[i] << "\t";
delete[] arr;
arr = NULL;
cout << endl;
}
I wonder if it is necessary to deallocate the memory that I allocated in the function to create the dynamic array (arr).
|
I don't know if it is a good practice
It's not. Nowadays, cases where using new/new[] and delete/delete[] are necessary are very few.
I wonder if it is necessary to deallocate the memory that I allocated in the function
It is necessary if you want to avoid memory leaks and since you used a raw owning pointer, you need to do it manually, just like you do in your code. Your code is cleaning up correctly.
Good practice would however be to use a std::vector<int> or at least use a smart pointer like std::unique_ptr<int[]> instead since these will clean up memory automatically when they go out of scope.
vector<int> version:
#include <numeric> // std::iota
#include <vector> // std::vector
std::vector<int> returnNewArray(size_t n) {
std::vector<int> arr(n);
std::iota(arr.begin(), arr.end(), 0); // [0, n)
return arr;
}
unique_ptr<int[]> version:
#include <memory> // std::unique_ptr / std::make_unique_for_overwrite
#include <numeric> // std::iota
std::unique_ptr<int[]> returnNewArray(size_t n) {
auto arr = std::make_unique_for_overwrite<int[]>(n);
std::iota(arr.get(), arr.get() + n, 0); // [0, n)
return arr;
}
Both versions will let you iterate over the result just like you do in your code - and you don't have to delete[] anything when you're done:
auto arr = returnNewArray(n);
for(int i = 0; i < n; ++i)
std::cout << arr[i] << '\t'; // 0 1 2 3 4
But the std::vector<int> has the benefit of knowing its own size and can be used in range based for-loops, which also helps to not accidentally access the array out-of-bounds:
for (int value : arr) // range based for-loop
std::cout << value << '\t'; // 0 1 2 3 4
|
73,640,419
| 73,640,576
|
Template argument deduction, Qualified-Id and performance
|
Suppose I have a lambda function:
std::function<void (int&& y)> lambda = [](int&& y) { std::cout << std::forward<int>(y) << std::endl; };
Having another function named gate which takes the lambda function as arg:
template<typename T> void gate(T&& x, std::function<void (T&&)> f) { f(std::move(x)); };
as the template argument deduction cannot make equal the types lambda(0) and std::function<void (T&&)>, Indeed, I specifically need to pass the std::function<void (T&&)> directly to through gate function, a commonly used solution is to make the lambda function parameter as non-deduced context. The scope is achieved using some struct which takes in some arbitrary type and spit it right back out. Hence, template argument deduction fails and the type of 'T&&' is deducted elsewhere, in this case from the first argument passed which type was correctly deducted.
template typename<T> struct Identity { typedef T type };
template<typename T> void gate(T&& x, typename Identity<std::function<void (T&&)>>::type f) { f(std::move(x)); };
int main() { gate(1234, [](int&& y) { std::cout << std::forward<int>(y) << std::endl; }); }
What I am wondering is, are there some lost in performance given the usage of the 'identity' struct? Could this be made better? Is creating firstly lambda and then pass it as argument the better way?
|
What I am wondering is, are there some lost in performance given the usage of the 'identity' struct?
Certainly no runtime performance because the structure is never instantiated or used.
Compilation speed could be affected since the compiler has to instantiate that type but it "amortizes" together with the instantiation of the function template itself since there is 1:1 correspondence. It will highly depend on the compiler how quickly it can throw those instantiations away.
FYI there is std::type_identity in C++20 for exactly this purpose which might allow the compiler to improve its performance. Maybe it will get similar treatment how Clang 15 now treats std::forward and others as builtins instead of instantiating them.
|
73,640,973
| 73,641,200
|
Question about Nt and Zw functions API from User Mode
|
Im not working for any specific project, i just would like to know more about Nt and Zw functions, so here are my questions:
NOTE: Im always referring to User-Mode space, and not Kernel-Mode.
Whats the difference between Nt and Zw functions ? (so like, for example NtTerminateProcess and ZwTerminateProcess)
Is the same thing calling NtTerminateProcess and ZwTerminateProcess from user mode?
From researching on the internet is saw that Zw function are mostly used by Kernel Drivers, but i tested few and all seems to be working perfectly in usermode too, so why should they be called in kernel mode only/mostly (?) if they works perfectly like Nt ones in usermode?
I saw just by disassembly ntdll.dll that Nt functions are just a proxy for Zw ones, so actually why Nt ones exists?
|
Whats the difference between Nt and Zw functions ?
in user mode both 2 names point to the same address (function). so no difference which name use. and in user mode this functions is stub, which call to kernel. the ntdll.dll export all names - all Nt and all Zw. however if use definitions from ntifs/ntddk/wdm - not all functions declared. for instance in case registry functions - ZwCreateKey, ZwOpenKey, ZwQueryValueKey,.. only with Zw prefix api declared. no declaration of Nt. so you need add it by self if want use NtOpenKey for instance (possible include ntifs.h with windows.h)
in kernel mode - exist big difference between Zw and Nt. at first here it always point to different functions. the Nt - this is real implementation of function. when Zw - stub, which reenter kernel and call Nt.
so (in kernel!) call Nt always faster that Zw.
call Nt use less stack space (this is important for kernel)
from another side -if call Zw - previous mode always will be kernel at Nt point. if direct call Nt - previous mode will be the same as at call point (this is base on context from where call, usually will be user mode as previous mode)
and finally ntoskrnl.exe export far not all Zw and Nt functions. for some api only Zw exported. for some only Nt. so we have no choise which variant call. for some both or not export at all. for select which variant call in kernel - need have knowledge (what is previous mode), from where we call api, etc.
Is the same thing calling NtTerminateProcess and ZwTerminateProcess
from user mode?
yes. absolute the same. because, both names (Zw and Nt) point to the same address and both is exported
From researching on the internet is saw that Zw function are mostly used by Kernel Drivers...
this is mistake. for call it in kernel need have deep knowledge, what we doing. and for call it from user mode - no difference, which prefix is use
I saw just by disassembly ntdll.dll that Nt functions are just a proxy for Zw ones, so actually why Nt ones exists?
you mistake. in user mode, how i already say, the Nt==Zw. and it point to proxy (stub ?) which call kernel. in native process. in wow64 process - this is also proxy (or stub) but not to kernel, instead to 64bit gate. here we go not direct to kernel, but to 64 bit code first, which fix parameters and call kernel.
in kernel mode Zw always proxy (stub) to Nt. but not visa versa
|
73,640,974
| 73,640,984
|
What is the difference between "using std::string" and "#include <string>"
|
I am newly learning C++, I do not really understand the difference between putting using std::string vs #include <string> at the top of my main file.
I seem to be able to define strings without having #include <string> here:
#include <iostream>
using std::cout; using std::cin;
using std::endl;
using std::string;
int main()
{
string s = "hi";
cout << s;
return 0;
}
This seems to run without issue, so why would I have #include <string>?
|
You need to include the <string> header to use std::string.
Adding using std::string; allows you to use it without the std:: namespace qualifier.
If you include a header that includes <string> you may not have to do so explicitly. However, it is bad practice to count on this, and well-written headers include guards against multiple inclusion, so assuming you're using well-written header files, there is no harm in including a header that was included via a previous include.
|
73,641,004
| 73,641,435
|
Defining declared member function inside struct
|
struct a_t {
struct not_yet_known_t;
struct b_t {
void f(not_yet_known_t* m);
};
struct c_t {
b_t b;
//...
};
struct not_yet_known_t {
c_t c;
//...
};
// ERROR HERE
void b_t::f(not_yet_known_t* m) {
// code comes here
}
};
int main() {
a_t::not_yet_known_t m;
a_t::b_t b;
b.f(&m);
}
Is it possible to define a_t::b_t::f inside a_t:: scope some way? Or if we could access global scope inside a_t:: but not actually pasting the code outside a_t:: scope?
Error I get:
main.cpp:16:13: error: non-friend class member 'f' cannot have a qualified name
void b_t::f(not_yet_known_t* m) {
~~~~~^
|
struct a_t {
struct not_yet_known_t;
struct b_t {
void f(not_yet_known_t* m){ _b_t_f(this, m); }
};
struct c_t {
b_t b;
//...
};
struct not_yet_known_t {
c_t c;
//...
};
static void _b_t_f(b_t* b, not_yet_known_t* m) {
// code comes here
}
};
Instead of declaring a_t::b_t::f you can define it to call another function then define that function in outside of a_t::b_t.
You can use this way if you don't want to go outside of struct a_t. I suggest naming that function _b_t_f something like struct name + function name to be sure it will never collide with other things.
|
73,641,174
| 73,666,658
|
using std::filesystem::recursive_directory_iterator; (Console App works, VCL App Doesn't)
|
I'm wanting to use std::filesystem::recursive_directory_iterator to list files in a folder and subfolder.
This code works fine in a Console Application:
#include <iostream>
#include <vector>
#include <string>
#include <filesystem>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::filesystem::recursive_directory_iterator;
int main() {
string path = "./";
for (const auto & file : recursive_directory_iterator(path))
cout << file.path() << endl;
return EXIT_SUCCESS;
}
However, in the VCL App with the following code:
#include <vcl.h>
#pragma hdrstop
#include <fstream.h>
#include <stdio.h>
#include <dir.h>
#include <iostream>
#include <vector>
#include <string>
#include <filesystem>
using std::cout; using std::cin;
using std::endl; using std::string;
using std::filesystem::recursive_directory_iterator;
#include "OSSEncryptByList.h"
#include "OSSMain.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TEncryptByListForm *EncryptByListForm;
//---------------------------------------------------------------------------
__fastcall TEncryptByListForm::TEncryptByListForm(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void TEncryptByListForm::ShowListForm()
{
// blah...
The error message is:
[bcc32 Error] OSSEncryptByList.cpp(11): E2209 Unable to open include file 'filesystem'
For some reason, #include <filesystem> is failing in the VCL Application but not in the Console Application.
|
Your Console project is configured to use a Clang-based C++ compiler, but your GUI project is configured to use the "classic" Borland C++ compiler instead. The classic compiler does not support C++11, and thus cannot use the <filesystem> library. You will have to go into your Project Options and disable the "Use 'classic' Borland compiler" option in the C++ Compiler settings.
|
73,641,731
| 73,641,802
|
Unique pointer to a pointer memory management
|
Function f allocates a few bytes that are returned in the form of a unique_ptr<char*>. How "smart" is this smart pointer ?
When the returned unique_ptr goes out of scope, are those allocated bytes returned to the system ?
The managed object here is a pointer (char*), not the bytes it points to ! (hence the specialization for arrays)
Answer @Miles Budnek
No. Consider a unique_ptr<char[]>.
|
std::unique_ptr is a very simple class template. All it does is store a pointer and delete (or delete[], in the case of an array) the object pointed to by that pointer in its destructor.
That is, it looks something like this (slightly simplified):
template <typename T>
class unique_ptr
{
private:
T* ptr_;
public:
unique_ptr(T* ptr)
: ptr_{ptr}
{}
~unique_ptr()
{
delete ptr_;
}
// Other constructors and member functions omitted for brevity
};
As you can see, all it does is delete the the object directly pointed to by the pointer it holds. If that object is itself a pointer then any data pointed to by that pointer does not get deleted.
If you want to return a smart pointer to an allocated array of char, then you should create a std::unique_ptr<char[]> pointing directly to the first char in the array. If you really want an extra level of indirection, you would need something like a std::unique_ptr<std::unique_ptr<char[]>> if you wanted the underlying array to get delete[]ed when the unique_ptr goes out of scope.
|
73,641,893
| 73,642,837
|
Operator overload taking void
|
I have a case in my code where I want to call a class-defined binary operator overload through a template, but the second argument might be type void. Is it possible to write that specialisation?
The why:
So I have a piece of existing macroisation/template wrapping which helps me log return values from functions.
It goes a bit like this:
#define Return return DebugPlacement({__FILE__,__LINE__}) <<=
Where DebugPlacement is a little spot-class that has a templated overload for operator <<=
struct DebugPlacement
{
const char* path; int line;
template <class Arg>
const Arg& operator <<= (const Arg& arg)const
{
std::cerr << "DIAG: " << path << ":" << line << " returns " << arg << std::endl;
return arg;
}
};
We chose operator <<= because it is pretty obscure and behaves somewhat like the existing streaming operator, but in reverse. Also its low precedence means that almost any sensible expression can be written on the RHS.
Another compromise: All the types are generally simple so use of rvals was not a big issue. I'm sure we will eventually see a need for perfect forwarding here, but not yet.
It prints the value, and returns it. And I can plug in various general specialisations as I find I need them, - char*, etc. No extra brackets are required. It works very nicely, thanks for asking!
In a lot of cases it is used in API stubs:
extern int MyFunction(int (arg1), int (arg2));
int MyFunctionStub(int (arg1), int (arg2))
{
Return MyFunction(int (arg1), int (arg2));
}
And that stub behaviour, in turn, has ended up macroised. I know - it is a curse and a blessing. Needless to say, our usecases are not quite this trivial. The stub does also have work to do, so can't be eliminated or templated away. The names of the stubs are also historically fixed as the public "C" API.
But it all falls apart if the return type is void!
It appears the nice c++ gods think the following is acceptable, probably because of template wrappers needing to blindly forward return types:
extern void MyVFunction(int (arg1), int (arg2));
void MyVFunctionStub(int (arg1), int (arg2))
{
return MyVFunction(int (arg1), int (arg2));
}
But with the macro substitution I can't add my tracing. They don't like:
extern void MyVFunction(int (arg1), int (arg2));
void MyVFunctionStub(int (arg1), int (arg2))
{
return DebugPlacement({__FILE__,__LINE__}) <<= MyVFunction(int (arg1), int (arg2));
}
Errors (at the call-site):
error: no viable overloaded '<<='
note: candidate template ignored: substitution failure [with T = void]: cannot form a reference to 'void'
So is there some form of words to declare a specialisation of a binary operator that does require a right hand side, but of type void? Currently we are still living in a c++11 land. Am I going to have to wait for a later c++ standard, or are the standardisation gods not looking kindly upon me this time?
Of course, I have tried a few things:
template <>
auto DebugPlacement::operator <<=(void& t)const -> void&
error: cannot form a reference to 'void'
Also
void operator <<=(void t)const
error: argument may not have 'void' type
|
I have a case in my code where I want to call a class-defined binary operator overload through a template, but the second argument might be type void. Is it possible to write that specialisation?
You can handle void return type using built-in binary comma operator:
In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing) (until C++17).
When its right-hand operand is void comma operator evaluates to void. Comma operator can be overloaded only for non-void operands. When any operand is void only the built-in comma operator is invoked, the user-defined operator, is not considered.
Comma operator precedence is the lowest which is ideal for your task.
Note that comma symbol (,) has different meanings in different contexts:
The comma in various comma-separated lists, such as function argument lists (f(a, b, c)) and initializer lists int a[] = {1, 2, 3}, is not the comma operator. If the comma operator needs to be used in such contexts, it has to be parenthesized: f(a, (n++, n + b), c).
C++11 example:
#include <iostream>
#include <utility>
struct ReturnValueLogger {
char const* file_;
int const line_;
std::ostream& log_file_line() const {
return std::clog << file_ << ":" << line_ << ' ';
}
ReturnValueLogger(ReturnValueLogger const&) = delete;
~ReturnValueLogger() {
if(file_) // operator, overload is not called for void rhs.
log_file_line() << "Return value is void\n";
}
template<class T>
auto operator,(T&& rhs) -> decltype(std::forward<T>(rhs)) { // Not called for void rhs.
log_file_line() << "Return value is " << rhs << '\n';
file_ = 0;
return std::forward<T>(rhs);
}
};
#define Return return ReturnValueLogger{__FILE__,__LINE__},
int f() { return 1; }
void g() {}
int f2() { Return f(); } // Outputs "Return value is 1".
void g2() { Return g(); } // Outputs "Return value is void".
int main() {
f2();
g2();
}
Overloading comma operator is also useful for a similar macro Throw to instrument exceptions with stacktrace, file and line information at throw sites.
|
73,642,159
| 73,642,429
|
How to find the smiley symbols( :) and :-] ) starting positions in a text using c++
|
Trying to find the starting positions of the smiley in c++.
But once it found the first smiley, it stops finding the next smiley.
Code I was trying with regex (":\)|:\-\]")
#include <iostream>
#include <string>
#include <regex>
int main ()
{
std::string s ("Best :) bookseller :) today. :-]");
std::smatch m;
std::regex e (":\\)|:\\-\\]");
if (std::regex_search(s, m, e))
{
std::cout << "matched" << std::endl;
std::cout << m[0] << " -> " << m.position(0) << std::endl;
std::cout << m[1] << " -> " << m.position(1) << std::endl;
std::cout << m[2] << " -> " << m.position(2) << std::endl;
}
else
std::cout << "not matched" << std::endl;
return 0;
}
Expected output is:
matched
:) -> 5
:) -> 19
:-] -> 29
But getting output as:
matched
:) -> 5
-> 32
-> 32
It would be great if someone suggest how to find the smiley symbols position in multiple places in a test using c++ (or) suggest a right regex to use.
|
A regex_search only returns a single match. As the documentation notes:
In order to examine all matches within the target sequence, std::regex_search may be called in a loop, restarting each time from m[0].second of the previous call. std::regex_iterator offers an easy interface to this iteration.
Simple loop construction:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string s ("Best :) bookseller :) today. :-]");
std::smatch m;
std::regex e (":\\)|:-\\]");
for (auto it = s.cbegin();
std::regex_search(it, s.cend(), m, e);
it = m[0].second)
{
std::cout << "matched" << std::endl;
std::cout << m[0] << " -> " << m.position(0) << std::endl;
}
}
Using regex_iterator:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string s ("Best :) bookseller :) today. :-]");
std::regex e (":\\)|:-\\]");
for (auto it = std::sregex_iterator(s.begin(), s.end(), e);
it != std::sregex_iterator();
++it)
{
const auto& m = *it;
std::cout << "matched" << std::endl;
std::cout << m.str() << " -> " << m.position(0) << std::endl;
}
}
Note that you do not need to escape the - character in a regular expression. I have corrected that in my examples.
|
73,642,889
| 73,642,919
|
C++ union of derived classes with pure virtual base - what happens?
|
I stumbled across this pattern today. It compiles fine but does not work correctly at runtime. ("Der1" is printed twice)
I can sort of see why, given that the address dereferenced is always the same, but I don't fully understand.
I am not looking for a solution or workaround, I have already restructured this code. Just interested to understand what happens under the hood in this scenario.
#include <iostream>
struct Base
{
virtual void Func() = 0;
};
struct Der1 : public Base
{
virtual void Func() override
{
std::cout << "Der1" <<std::endl;
}
};
struct Der2 : public Base
{
virtual void Func() override
{
std::cout << "Der2" <<std::endl;
}
};
static union Ders
{
Der1 D1;
Der2 D2;
Ders() : D1() {}
} theDers;
static Base * b = &theDers.D1;
int main()
{
b->Func();
b = &theDers.D2;
b->Func();
return 0;
}
|
What's happening is undefined behavior. What happens "under the hood" is immaterial. A different C++ compiler might produce completely different results (called a "crash").
You can observe undefined behavior in action by adding a constructor to both classes:
struct Der1 : public Base
{
Der1()
{
std::cout << "Der1 construct\n";
}
// ...
struct Der2 : public Base
{
Der2()
{
std::cout << "Der2 construct\n";
}
You will observe that only Der1 gets constructed. This is your big honking clue.
In a union, the first object in the union gets initially constructed for you. It becomes your onus to make a different member union "active" by manually invoking the existing active object's destructor and invoking the new active object's constructor, directly (typically using placement new). It's your onus to keep track of which union member is active.
The shown code invokes a method of an object that was never constructed, resulting in undefined behavior.
This is why in C++ it's much easier to use std::variant, which does all this work for you.
|
73,642,903
| 73,647,684
|
Sending an array of ints with boost::asio
|
I want to send raw ints with boost.asio compatibly with any CPU architecture. Usually, I would convert ints to strings, but I may be able to get better performance by skipping the int/ascii conversion. I don't know what boost.asio already does under the hood such as using htonl. The documentation doesn't say and there is no way to test this code on my own PC.
Here are several methods I have to send an array of ints over the network:
Store the ints in an array of int32_t. Use htonl and ntohl to get correct endian-ness. If int32_t is not supported on the target machine, handle that with int_fast32_t and extra work.
Use boost.serialization. The only example I can find is from pre-C++11 times (see section on serialization), so I don't know if boost.serialization and boost.asio should still be used in this way. Also, as boost.serialization is a black box, it isn't clear what the performance overhead of using this library is.
Convert each int to the ascii representation.
I think (1) is the "correct" alternative to non-ascii conversion. Can boost.asio or boost.serialization perform any of the steps of (1) for me? If not, what is the current recommended way to send ints with boost.asio?
|
The other answer by @bazza has good professional advice. I won't repeat that. I get the impression you're more focusing on understanding the implementation specifics here, so I'll dive into the details of that for you here:
Yeah, option 1 seems okay for the simple use case you describe.
I don't know what boost.asio already does under the hood such as using htonl
It doesn't except perhaps in the protocol layers - but those are implementation details.
The documentation doesn't say
That's because it doesn't have an opinion on your application layer. The fact that it isn't mentioned is a good sign that no magic happens.
Can boost.asio or boost.serialization perform any of the steps of (1) for me?
Actually, no. The Boost binary archive is not portable (see also EOS Portable Archive).
Ironically, it can portably use one of the text archive formats https://www.boost.org/doc/libs/1_46_1/libs/serialization/doc/archives.html#archive_models (XML and plain text are provided), but as you surmised they can have considerable overhead: Boost C++ Serialization overhead. Besides, there will be copying into and out of the stream format.
If not, what is the current recommended way to send ints with boost.asio?
I'd consider using the raw array/vector:
std::array<int32_t, 45> data;
boost::asio::async_write(socket_,
boost::asio::buffer(data),
...);
Of course you have to cater for endianness. Boost Endian has you covered in several ways. Compare the performance trade-offs here: https://www.boost.org/doc/libs/1_80_0/libs/endian/doc/html/endian.html#overview_performance
The simplest idea here is to use the drop-in (un)aligned arithmetic types:
std::array<boost::endian::big_int32_t, 45> data;
boost::asio::async_write(socket_,
boost::asio::buffer(data),
...);
To make the example a bit more life-like:
struct Message {
boost::endian::big_uint32_t magic = 0xCAFEBABE;
boost::endian::big_uint32_t length = 0;
std::vector<boost::endian::big_uint32_t> data;
std::array<boost::asio::const_buffer, 3> as_buffers() const {
length = data.length(); // update leading length header field
return {
boost::asio::buffer(&magic, sizeof(magic)),
boost::asio::buffer(&length, sizeof(length)),
boost::asio::buffer(data),
};
}
};
Now you can still:
Message message;
message.data = {1,2,3,4,5,6,7,8};
boost::asio::async_write(socket_,
message.as_buffers(),
...);
|
73,643,874
| 73,675,695
|
C++ Simple Window Creation is executing java code for some reason?
|
I'm following the walkthrough of how to create a simple c++ application window here, and as far as I can tell my code is exactly the same as on the website. However whenever I try to execute the code it throws up this console where it seems to execute some java code and infinitely try to connect to a server. The problem is I have no earthly idea why this could be happening or what could be causing it. On cursory google searches it seems like it might be related to tesseract or some other package but I don't know why some outside package would ever be doing something in my code when I haven't included it. My project is a standard console app from Visual Studio but with my code replacing the default. I imagine this has nothing to do with the actual code but I have included it just in case.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
static TCHAR szWindowClass[] = _T("DesktopApp");
static TCHAR szTitle[] = _T("Windows Desktop Guided Tour Application");
HINSTANCE hInst;
LRESULT CALLBACK WndProc(_In_ HWND hWnd,_In_ UINT message,_In_ WPARAM wParam,_In_ LPARAM lParam) {
PAINTSTRUCT ps;
HDC hdc;
TCHAR greeting[] = _T("Hello, Windows desktop!");
switch (message){
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// Here your application is laid out.
// For this introduction, we just print out "Hello, Windows desktop!"
// in the top left corner.
TextOut(hdc,
5, 5,
greeting, _tcslen(greeting));
// End application specific layout section.
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return 0;
}
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(wcex.hInstance, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);
if (!RegisterClassEx(&wcex))
{
MessageBox(NULL,_T("Call to RegisterClassEx failed!"),_T("Windows Desktop Guided Tour"),NULL);
return 1;
}
// Store instance handle in our global variable
hInst = hInstance;
HWND hWnd = CreateWindowEx(
WS_EX_OVERLAPPEDWINDOW,
szWindowClass,
szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 100,
NULL,
NULL,
hInstance,
NULL
);
if (!hWnd)
{
MessageBox(NULL,
_T("Call to CreateWindow failed!"),
_T("Windows Desktop Guided Tour"),
NULL);
return 1;
}
// The parameters to ShowWindow explained:
// hWnd: the value returned from CreateWindow
// nCmdShow: the fourth parameter from WinMain
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// Main message loop:
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
|
The cause of this was from a library by the name of Tesseract, I'm unsure why it was compiling with the code at all, but I can be sure that it was causing this, and a quick uninstall of the library fixed everything.
|
73,644,157
| 73,724,541
|
Get raw buffer for in-memory dataset in GDAL C++ API
|
I have generated a GeoTiff dataset in-memory using GDALTranslate() with a /vsimem/ filepath. I need access to the buffer for the actual GeoTiff file to put it in a stream for an external API. My understanding is that this should be possible with VSIGetMemFileBuffer(), however I can't seem to get this to return anything other than nullptr.
My code is essentially as follows:
//^^ GDALDataset* srcDataset created somewhere up here ^^
//psOptions struct has "-b 4" and "-of GTiff" settings.
const char* filep = "/vsimem/foo.tif";
GDALDataset* gtiffData = GDALTranslate(filep, srcDataset, psOptions, nullptr);
vsi_l_offset size = 0;
GByte* buf = VSIGetMemFileBuffer(filep, &size, true); //<-- returns nullptr
gtiffData seems to be a real dataset on inspection, it has all the appropriate properties (number of bands, raster size, etc). When I provide a real filesystem location to GDALTranslate() rather than the /vsimem/ path and load it up in QGIS it renders correctly too.
Looking a the source for VSIGetMemFileBuffer(), this should really only be returning nullptr if the file can't be found. This suggests i'm using it incorrectly. Does anyone know what the correct usage is?
Bonus points: Is there a better way to do this (stream the file out)?
Thanks!
|
I came back to this after putting in a workaround, and upon swapping things back over it seems to work fine. @mmomtchev suggested looking at the CPL_DEBUG output, which showed nothing unusual (and was silent during the actual VSIGetMemFileBuffer call).
In particular, for other reasons I had to put a GDALWarp call in between calling GDALTranslate and accessing the buffer, and it seems that this is what makes the difference. My guess is that GDALWarp is calling VSIFOpenL internally - although I can't find this in the source - and this does some kind of initialisation for VSIGetMemFileBuffer. Something to try for anyone else who encounters this.
|
73,644,823
| 73,644,993
|
What does `template<>` mean in front of a variable definition in C++98
|
I'm recently working on some legacy codes written in C++98.
I am trying to get them compiled by C++17 compiler. A whole lot of warnings popped out as I was doing that. However, almost all the warnings were easily resolved. Except for this one:
struct Counter {
Counter(int v) : m_val(v) {}
int m_val;
};
struct AClass {
static Counter SEQ;
};
template<> Counter AClass::SEQ = 0;
The C++17 compiler gave a warning "too many template headers for...(should be 0)" for the line template<> Counter AClass::SEQ = 0;. (https://godbolt.org/z/G845K3cvv)
But for C++98 compiler it was totally OK. (https://godbolt.org/z/xErje7T8o)
Now, in order to resolve the warning, I need a complete understanding as to what does the statement mean in the C++98 world.
My gut feeling is that it is a full template specialization. And the template argument is empty. So it is equivalent to Counter AClass::SEQ = 0; and template<> means nothing. (https://stackoverflow.com/a/4872816/1085251)
Can anyone tell me exactly what it means?
|
It seems like gcc 4.7.4 is unable to give a diagnostic. Note that from gcc 5.1 onwards, we get a diagnostic from gcc. Demo.
The given program is ill-formed in both C++17 as well as C++98 as you're trying to provide an explicit specialization when there is nothing to specialize(as there is no templated entity anywhere in the program and AClass is also not a class template).
|
73,645,060
| 73,645,467
|
Created a program for binary tree traversal, inorder and postorder print wrong sequences
|
I made a program that takes user input to create a binary tree, with options to traverse said tree based on user input. Inserting and Preorder traversal work fine, but for some reason Inorder traversal prints the same output as Preorder, and Postorder traversal prints the input backwards. I've checked my insert and traversal functions a million times and I can't see where I'm going wrong... help would be greatly appreciated!
#include <iostream>
using namespace std;
struct Node {
int data;
Node *right;
Node *left;
};
Node *createNode(int data) {
Node *temp = new Node();
temp->data = data;
temp->right = temp->left = NULL;
return temp;
}
void insertNode(Node* &root, int data) {
if(root == NULL)
root = createNode(data);
else if(root->data > data)
insertNode(root->left, data);
else
insertNode(root->right, data);
}
void printInorder(Node *root) {
if(root != NULL){
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
}
void printPreorder(Node *root) {
if(root != NULL){
cout << root->data << " ";
printPreorder(root->left);
printPreorder(root->right);
}
}
void printPostorder(Node *root) {
if(root != NULL){
printPostorder(root->left);
printPostorder(root->right);
cout << root->data << " ";
}
}
int main()
{
Node *root = NULL;
int n, val;
int treeOp;
do {
cout << "\nBINARY TREE OPTIONS";
cout << "\n------------------------------\n";
cout << "(1) Insert element(s)";
cout << "\n(2) Inorder traversal";
cout << "\n(3) Preorder traversal";
cout << "\n(4) Postorder traversal";
cout << "\n(5) Return to main menu\n\n";
cout << "Enter the number of your choice: ";
cin >> treeOp;
cout << endl;
switch(treeOp) {
case 1:
cout << "How many elements will you insert: ";
cin >> n;
cout << "\nInsert " << n <<" elements, hit enter after each:\n";
for(int i=0; i < n; i++) {
cin >> val, insertNode(root, val);
}
cout << "\nElement(s) inserted!" << endl;
break;
case 2:
if(root == NULL) {
cout << "\nNo elements found!\n";
} else {
cout << "INORDER TRAVERSAL OF YOUR BINARY TREE: " << endl;
printInorder(root);
cout << endl;
}
break;
case 3:
if(root == NULL) {
cout << "\nNo elements found!\n";
} else {
cout << "PREORDER TRAVERSAL OF YOUR BINARY TREE: " << endl;
printPreorder(root);
cout << endl;
}
break;
case 4:
if(root == NULL) {
cout << "\nNo elements found!\n";
} else {
cout << "POSTORDER TRAVERSAL OF YOUR BINARY TREE: " << endl;
printPostorder(root);
cout << endl;
}
break;
default:
if(treeOp!=5){
cout << "\nInput invalid, please try again\n";
}
}
} while (treeOp != 5);
return 0;
}
Not sure if I was clear in my explanation above, but basically when I insert 1 2 3 4 5, I'd get:
Inorder: 1 2 3 4 5 (wrong)
Preorder: 1 2 3 4 5 (right)
Postorder: 5 4 3 2 1 (wrong)
|
You did not make a mistake at all. But you have now first-hand encountered the raison d'être for tree balancing. (eg red-black trees or AVL trees)
Inserting "1 2 3 4 5" in that order, with your code, gives the following tree (also known as a linked list):
1
2
3
4
5
If you change your input to "3 1 2 4 5" you get a far more balanced tree:
3
1 4
2 5
|
73,645,987
| 73,646,492
|
Execute lambda with CreateThread
|
Is there a better way to use CreateThread than creating a free function each time for the sole purpose of casting lpParameter?
Are there any modern alternatives to CreateThread for creating persistent threads?
Edit: Perhaps you should just use std::async(lambda). I imagine that it's just implemented with CreateThread. Maybe the answer to this question is looking up how std::async is implemented (assuming it's a library feature).
DWORD WINAPI MyThreadFunction(
_In_ LPVOID lpParameter
)
{
((MyClass*)lpParameter)->RunLoop();
}
void MyClass::LaunchThread()
{
CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
this, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier
}
|
There are several mechanisms for achieving parallelism (std::async etc. as mentioned above).
But the modern one which is most similar to your original code with CreateThread is std::thread. It can be constructed with a global function, a lambda, or a class method (which seems the best fit for you):
m_thread = std::thread([this](){ RunLoop(); }); // pass a lambda
or
m_thread = std::thread(&MyClass::RunLoop, this); // pass a method
Note that a std::thread starts to run (potentially) when constructed. Also note that, std::async does not guarantee that it will run on a separate thread and even if it does run on a thread, it could be a thread from a pool. The behaviour might not be the same as with your original CreateThread.
Here's a complete example of using std::thread (including cancellation):
#include <thread>
#include <chrono>
#include <atomic>
#include <iostream>
class MyClass
{
public:
MyClass() {}
~MyClass() { EndThread(); }
void LaunchThread()
{
EndThread(); // in case it was already running
m_bThreadShouldExit = false;
// Start the thread with a class method:
m_thread = std::thread(&MyClass::RunLoop, this);
}
void EndThread()
{
// Singal the thread to exit, and wait for it:
m_bThreadShouldExit = true;
if (m_thread.joinable())
{
m_thread.join();
}
}
void RunLoop()
{
std::cout << "RunLoop started" << std::endl;
while (!m_bThreadShouldExit)
{
std::cout << "RunLoop doing something ..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
std::cout << "RunLoop ended" << std::endl;
}
private:
std::thread m_thread;
std::atomic_bool m_bThreadShouldExit{ false };
};
int main()
{
MyClass m;
m.LaunchThread();
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
m.EndThread();
}
Possible output:
RunLoop started
RunLoop doing something ...
RunLoop doing something ...
RunLoop doing something ...
RunLoop doing something ...
RunLoop doing something ...
RunLoop ended
|
73,646,519
| 73,646,587
|
while(decision1 != 1 || decision1 != 2) why does this keep repeating even though decision is already 1 or 2
|
This is the code. Why does it keep repeating even though decision is already 1 or 2?
std::cout << "How many toppings do you want? (1/2): ";
std::cin >> decision1;
while(decision1 != 1 || decision1 != 2)
{
std::cout << "Please enter either 1 or 2\n";
std::cout << "How many toppings do you want? (1/2): ";
std::cin >> decision1;
}
|
When decision1 == 1, the condition decision1 != 2 is true, and vice-versa.
Since decision1 cannot be both 1 and 2, decision1 != 1 || decision1 != 2 is always true.
|
73,646,581
| 73,647,040
|
How to get a user's input into a class's member variable and dereference it
|
class cookie{
public:
cookie() = default;
int*p_member{};
int case{};
private:
};
#include <iostream>
using namespace std;
int main(){
cookie cold;
cout << "Type what you want into the cookie p_member variable " << endl;
std::cin >> cold.*p_member; // this doesn't work
}
I wanna know how to get access to the classes pointer variable put data inside it and then derefrence it.
|
First things first, make sure that you're not dereferencing a null or uninitialized pointer. Otherwise you'll have undefined behavior.
it's about a member that is a pointer.I would like to assign a value to the member, and then dereference the member so i could print it out.
You can use a pointer to member syntax for this task as shown below:
class cookie{
public:
int var;
int cookie::*p_member=&cookie::var; //p_member can point to an int data member of an cookie object
};
int main(){
cookie cold{};
cout << "Type what you want into the cookie p_member variable " << endl;
std::cin >> cold.*cold.p_member; //take input from user directly into var using member pointer syntax
std::cout << "var: " << cold.var << std::endl; //print var to confirm that it is correctly set
}
Working demo
|
73,646,712
| 73,647,244
|
I am trying to solve this question. But condition is dont touch listPrime function. Is it possible
|
**Dont touch listPrime function just modify the main function.Also Must use listPrime to get return value ; Question from one of my senior classmate **
#include <iostream>
const int nmax = 100001;
bool isPrime[nmax];
int listPrime(int num){
for(int i = 2; i<=num;i++){
isPrime[i] = true;
}
for(int i = 2; i<=num/2;i++){
if(isPrime[i]==true){
for(int j =i*2;j<=num;j+=i){
isPrime[j] = false;
}
}
}
for(int i=2;i<=num;i++){
if(isPrime[i] == true){
return i;
}
}
}
int main (){
//Qn: Call the above function and get return all prime number lists from 1-100
// but dont touch listPrime Function untill you think you can not do it
return 0;
}
|
You don't need to use the function's return value at all. I'm sure that final loop and return in the function is there to throw you off. It's completely pointless.
The function computes a prime sieve. If you just call it once, it'll generate the entire table for values up to whatever value you passed. So you may as well pass nmax to generate the entire table. Computing a sieve is very fast, especially for values as small as 100000.
Once the table is built, all you need to do is read the value at any valid index to know if that index is a prime number. It's unclear whether you want to show A) all primes up to 100; or B) the first 100 primes. I'll show both.
int main()
{
listPrime(nmax);
// Option A: Output primes up to 100
for (int n = 0; n < 100; n++)
{
if (isPrime[n]) {
std::cout << n << '\n';
}
}
// Option B: Output first 100 primes
for (int count = 0, n = 0; count < 100 && n < nmax; n++)
{
if (isPrime[n]) {
count++;
std::cout << "Prime " << count << " is " << n << '\n';
}
}
}
|
73,647,216
| 73,648,873
|
Compiling opencv on ubuntu with C++ version 17
|
I'm trying to add a pnp solver to opencv
I'm working on ubuntu OS.
first I followed a tutorial on how to install opencv from source by cloning the repositories, then I tested the example and it worked so it compiled and installed succesfully.
I began adding my files and I made sure that no names are duplicated and all the files have been added so there were no issues with dependancies.
then I ran the cmake again, and ran the make command, but it is giving me the following error:-
opencv/modules/calib3d/src/RansacOptimalNPnP/../NPnP/DualVar.h:71:8: error: ‘optional’ in namespace ‘std’ does not name a template type
71 | std::optional<std::tuple<Eigen::Matrix3d, Eigen::Vector3d, double>>
I looked it up online and there is a possibility that I need to use C++ version 17 but the standard version in opencv is set to 11.
what can I change in the opencv cmake list to change that?
|
You can install OpenCV from ubuntu's opencv package via the following:
for python:
sudo apt-get install python3-opencv
for libopencv-dev:
sudo apt-get install libopencv-dev
If you want to compile it and not use ubuntu's OpenCV package, do the following:
# dependencies
sudo apt-get install cmake
sudo apt-get install gcc g++
# for python2 support
sudo apt-get install python-dev python-numpy
# for python3 support
sudo apt-get install python3-dev python3-numpy
# GTK support
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev
sudo apt-get install libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev
# GTK 2 support
sudo apt-get install libgtk2.0-dev
# GTK 3 support
sudo apt-get install libgtk-3-dev
# Optional Dependencies
sudo apt-get install libpng-dev
sudo apt-get install libjpeg-dev
sudo apt-get install libopenexr-dev
sudo apt-get install libtiff-dev
sudo apt-get install libwebp-dev
now that you are done with dependencies continue to the actual installation
sudo apt-get install git
git clone https://github.com/opencv/opencv.git
mkdir build
cd build/
cmake ../
if properly configured this is the output
-- Python 2:
-- Interpreter: /usr/bin/python2.7 (ver 2.7.6)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.6)
-- numpy: /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.8.2)
-- packages path: lib/python2.7/dist-packages
--
-- Python 3:
-- Interpreter: /usr/bin/python3.4 (ver 3.4.3)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython3.4m.so (ver 3.4.3)
-- numpy: /usr/lib/python3/dist-packages/numpy/core/include (ver 1.8.2)
-- packages path: lib/python3.4/dist-packages
make
sudo make install
This was shamelessly copied from opencv docs py setup in ubunutu
|
73,647,249
| 73,647,425
|
class initalizer list using a templated constructor of baseclass
|
I like to create a registry of templated classes adressed through their polymorphic anonymous base-class. In order to construct these classes I need to store the type of the used template class in the base-class. I woulod like to make the design slim and pass the template class in the constructor of the baseclass through a custom templated constructor.
However my code fails, and i cannot figure out what the correct formulation would be. Any help appriciated:
#include <vector>
#include <string>
#include <typeinfo>
#include <memory>
class Store_Base {
const std::string stored_type_name_;
protected: //ctor
template<class Tstored>
Store_Base() : stored_type_name_(typeid(Tstored).name()) {};
protected: // dtor
virtual ~Store_Base() = default;
public:
std::string get_type_name() const {return stored_type_name_;}
};
template <class Tstored>
class Store : public Store_Base {
const Tstored stored_;
public: //ctor
Store(const Tstored stored)
: Store_Base<Tstored>(), stored_(stored) {}; // !!! compile-error
public:
Tstored get_stored() const {return stored_;}
};
int main() {
std::vector<std::unique_ptr<Store_Base>> my_vec;
my_vec.emplace_back(std::make_unique< Store<int> >(42));
my_vec.at(0)->get_type_name(); // >>> i
((Store<int>*)(my_vec.at(0).get()))->get_stored(); // >>> 42
return 0;
}
|
This
Store(const Tstored stored)
: Store_Base<Tstored>()
is wrong, because it attempts to initialize the base class Store_Base<Tstored>, but Store_Base is not a template. The base class to be initialized is Store_Base not Store_Base<Tstored>.
The way to call a templated constructor is to have the template argument deduced. See here C++ template constructor.
You can use a tag to enable deduction:
#include <vector>
#include <string>
#include <typeinfo>
#include <memory>
template <typename T>
class Tag{};
class Store_Base {
const std::string stored_type_name_;
protected: //ctor
template<class Tstored>
Store_Base(Tag<Tstored>) : stored_type_name_(typeid(Tstored).name()) {};
protected: // dtor
virtual ~Store_Base() = default;
public:
std::string get_type_name() const {return stored_type_name_;}
};
template <class Tstored>
class Store : public Store_Base {
const Tstored stored_;
public: //ctor
Store(const Tstored stored)
: Store_Base(Tag<Tstored>{}), stored_(stored) {}; // !!! compile-error
public:
Tstored get_stored() const {return stored_;}
};
int main() {
std::vector<std::unique_ptr<Store_Base>> my_vec;
my_vec.emplace_back(std::make_unique< Store<int> >(42));
my_vec.at(0)->get_type_name(); // >>> i
((Store<int>*)(my_vec.at(0).get()))->get_stored(); // >>> 42
return 0;
}
Note that I didn't change more than necessary and that this code still fails to compile due to the destructor of Store_Base being protected, ie std::unique_ptr cannot access it.
|
73,648,806
| 73,648,843
|
How to read data from a binary file and write to a shared memory region?
|
I have created a shared memory region using boost. My next step is to read data from a binary file and write it to the shared memory region. I am using the following code to do this:
#include <fstream>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
using namespace std;
using namespace boost::interprocess;
int main(int argc, char **argv)
{
ifstream file;
file.open("sigData.bin", ios::binary | ios::in); // file is of 1mb
shared_memory_object shm(open_or_create, "shared_memory", read_write);
shm.truncate(1024 * 1024);
mapped_region region(shm, read_write);
unsigned char * mem = static_cast<unsigned char*> (region.get_address());
file.read(mem, region.get_size());
}
The above code gives me an error on the file.read() function. The error is as follows:
error: invalid conversion from ‘unsigned char*’ to ‘std::basic_istream<char>::char_type* {aka char*}’ [-fpermissive]
How do I solve this issue?
|
This can be solved by casting the pointer from unsigned char* to char*; this is one of the rare cases where just changing the type of a pointer is OK.
So, use
file.read(reinterpret_cast<char*>(mem), region.get_size());
|
73,649,066
| 73,650,407
|
Adjacency List in graph
|
Hi I am try to implement a graph using adjacency list using following code.
#include<iostream>
#include<list>
#include<vector>
#include<unordered_map>
using namespace std;
class graph{
public:
vector<int> adj[10000];
void insert(int u,int v, bool direction) {
adj[u].push_back(v);
if(direction==1) {
adj[v].push_back(u);
}
}
void print(int n) {
for(int i=0;i<n+1;i++) {
cout<<i<<"->";
for(auto j : adj[i]) {
cout<<j<<",";
}
cout<<endl;
}
}
};
int main( ) {
int n;
cout<<"Enter no of node"<<endl;
cin>>n;
cout<<"enter edges "<<endl;
int m;
cin>>m;
graph g;
for(int i=0;i<m;i++) {
int u, v;
cin>>u>>v;
g.insert(u,v,1);
}
g.print(n);
return 0;
}
But the problem with this code is that it will give correct answer only in the case when my node start from 0 in a continuous manner(0,1,2,3). But when I try to print adjacency list of this graph:
Then it is giving this output:
Can somebody tell me where am I wrong?
|
The edges you are adding aren't the same as the graph i picture, you are inputting edge 1, 3 instead of edge 1, 5.
|
73,649,475
| 73,681,699
|
Serving static files in uWebSockets HTTP server (C++)
|
I am setting up an HTTP server in C++ using the uWebSockets library and I would like to add a middleware to serve static files, similar to what app.use(express.static(path.join(__dirname, 'public'))); does in Express.js.
The static files reside in the public folder. The middleware should make the server load files under the path http://localhost:8087/css/bootstrap.min.css, not http://localhost:8087/public/css/bootstrap.min.css, thus re-routing root to public.
How could one do this in C++ using the uWebSockets library? I already inspected the uWS::App struct, however I find there nothing related to the path or to serving static files.
Here is an example an HTTP server:
#include <uWebSockets/App.h>
#include <rapidjson/rapidjson.h>
#include "util/AsyncFileReader.h"
#include "util/AsyncFileStreamer.h"
#include <iostream>
#include <string>
void get_home(uWS::HttpResponse<false> *res, uWS::HttpRequest *req) {
res->writeHeader("Content-Type", "text/html; charset=utf8");
// res->writeStatus(uWS::HTTP_200_OK);
// res->end("Hello! This is <b>Sergei's C++ web server</b>.");
AsyncFileReader page_contents("./public/home.html");
res->end(page_contents.peek(0));
}
int main() {
int port{8087};
// HTTP
uWS::App app = uWS::App();
app.get("/", get_home);
app.listen(port, [&port](auto *token) {
if (token) {
std::cout << "Listening on port " << port << std::endl;
}
})
.run();
return 0;
}
|
There is an example with this exactly
I eventually ended up adding a directory watch and updating the html files if saved (a few changes in codebase) but i guess thats a different thing
#include "helpers/AsyncFileReader.h"
#include "helpers/AsyncFileStreamer.h"
#include "helpers/Middleware.h"
AsyncFileStreamer asyncFileStreamer("htmls"); // htmls is a relative folder path to static files
app.get("/*", gethome); // note the *
void get_home(auto *res, auto *req) {
//void get_home(uWS::HttpResponse<false> *res, uWS::HttpRequest *req) {
serveFile(res, req); // essentially res->writeStatus(uWS::HTTP_200_OK);
asyncFileStreamer.streamFile(res, req->getUrl());
}
Please note serveFile() function also needs to take care of different Content-Type header setting for images
example mentioned:
https://github.com/uNetworking/uWebSockets/blob/master/examples/HttpServer.cpp
|
73,649,751
| 73,662,809
|
Nested lambda capture of variable gives incorrect warning
|
I'm using a nested lambda to walk through some data.
The outer lambda does some processing and then calls the inner lambda.
I get the following warning:
x86-64 clang 13.0.1 - 2629ms (104630B) ~1800 lines filtered
Output of x86-64 clang 13.0.1 (Compiler #1)
<source>:9:34: warning: class '' does not declare any constructor to initialize its non-modifiable members
const auto PickVarAtRandom = [&]<bool SATvar> {
^
<source>:9:34: note: in instantiation of member class '' requested here
<source>:18:41: note: in instantiation of function template specialization 'main()::(anonymous class)::operator()<true>' requested here
const auto result = doPick.template operator()<true>();
^
<source>:10:13: note: reference member '' will never be initialized
if (Length > 50) { printf("hallo"); return false; }
The code uses a nested lambda call. The following code will reproduce the issue in Godbolt.
#include <stdlib.h>
#include <stdio.h>
int main() {
const auto Length = rand() % 2;
//warning: class '' does not declare a constructor ...
// V
const auto PickVarAtRandom = [&]<bool SATvar> {
if (Length > 0) { printf("one %i", Length); return false; }
else { printf("zero %i", Length); }
return true;
};
const auto doPick = [&]<bool SATvar>() {
return PickVarAtRandom.template operator()<SATvar>();
};
const auto result = doPick.template operator()<true>();
}
The error goes away if just use a single lambda:
//no warning
#include <stdlib.h>
#include <stdio.h>
int main() {
const auto Length = rand() % 100;
const auto PickVarAtRandom = [&]<bool SATvar> {
if (Length > 50) { printf("hallo"); return false; }
return true;
};
const auto result = PickVarAtRandom.template operator()<true>();
}
I'm using clang 14 on MacOS, but in order to reproduce the warning in godbolt I need to select clang 13.
clang++ --version
Apple clang version 14.0.0 (clang-1400.0.29.102)
Target: arm64-apple-darwin21.6.0
Thread model: posix
Why do I get this warning with nested lambdas?
Can I suppress the warning?
Or is there a way to get rid of the warning whilst still using nested lambdas?
|
It's a compiler bug that was fixed in this commit:
https://github.com/llvm/llvm-project/commit/f7007c570a216c0fa87b863733a1011bdb2ff9ca.
As you can see, the commit is in clang 14, specifically between the tags llvmorg-14.0.0-rc2 and llvmorg-14.0.0-rc3. So it makes sense that the warning does not appear on godbolt with clang 14 but does with clang 13, and I guess the version on your machine is not the most recent clang 14.
Unfortunately, there does not seem to be any flag attached to this warning. If you cannot upgrade, I think the only way to suppress it in code is with a pragma for -Weverything:
#include <stdlib.h>
#include <stdio.h>
int main() {
const auto Length = rand() % 2;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weverything"
const auto PickVarAtRandom = [&]<bool SATvar> {
#pragma GCC diagnostic pop
if (Length > 0) { printf("one %i", Length); return false; }
else { printf("zero %i", Length); }
return true;
};
const auto doPick = [&]<bool SATvar>() {
return PickVarAtRandom.template operator()<SATvar>();
};
const auto result = doPick.template operator()<true>();
}
godbolt
You can of course compile with -Wno-everything or -w, but that's a bad idea in general.
As for why you get this warning... my guess from looking at the commit is that the additional condition cast<CXXRecordDecl>(D)->getTemplateDepth() > TemplateArgs.getNumRetainedOuterLevels() makes some part of clang correctly treat PickVarAtRandom as local, which somehow solves the warning. Perhaps you can find more info in here.
|
73,649,793
| 73,649,903
|
How make a vector2 relative to other vector2 properly?
|
Im making a 2D game with box2D physics, and i want to implement a parent-child system between the objects. The child's position will be relative to it parent. For example, father object position is (10, 0), the relative child's position is (0, 1) and the result child's position is (10, 1).
I was thinking about how to implement something like that, and I came to the conclusion that adding to each component of the child's position vector the parent's current position minus parent's previous frame position, this effect was achieved.
That worked fine in a normal game, but with box2d physics, there is some "delay" and children position seems to update slower than the father.
There is a proper way to achieve this effect more accurately?
|
What you're describing is known in the physics simulation world as a constraint. It simply means that the constrained object isn't free to move like it wants to, but instead there are some restrictions. A special case of a constraint is a joint that links two bodies together - and Box2D supports them. In your specific case, if you want the child to always be exactly in the same spot as the parent, you probably want a "weld" joint.
That being said, if you want a 100% interlock between parent and child, you might want to create one compound shape by either composing Fixtures or using ChainShape; that will guarantee that the system will never consider a possibility of them moving relative to one another, at least not with regards to dynamic forces.
|
73,649,917
| 73,650,474
|
construction with an allocator must be possible if uses_allocator is true
|
I'm trying to create a pmr-allocated datastructure (compare code below). This however fails with an awful long error message and I can't quite track the root of it. At the end is a static_assert which says construction with an allocator must be possible if uses_allocator is true.
As far as I can tell, std::pmr::vector is trying to call the copy constructor of profile with an allocator which fails because 1) I didn't define a copy constructor and 2) the default copy constructor doesn't take into account allocator construction. However: Why is the copy constructor being selected in the first place? How did I urge std::pmr::vector to select the copy constructor over the default one?
Demo
#include <memory_resource>
#include <cstdio>
struct profile
{
using allocator_type = std::pmr::polymorphic_allocator<std::byte>;
profile(allocator_type allocator = {})
: allocator_{ allocator }
{}
allocator_type get_allocator() {
return allocator_;
}
allocator_type allocator_;
};
struct update
{
using allocator_type = std::pmr::polymorphic_allocator<std::byte>;
update(allocator_type allocator = {})
: profiles_{ allocator }
{
}
allocator_type get_allocator() {
return profiles_.get_allocator();
}
std::pmr::vector<profile> profiles_;
};
struct service
{
update pending_;
};
int main()
{
}
Partial error (check above link to see whole traceback):
In file included from /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/memory_resource:36:
In file included from /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/bits/memory_resource.h:41:
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/bits/uses_allocator_args.h:72:8: error: static assertion failed due to requirement 'is_constructible_v<profile, const profile &, const std::pmr::polymorphic_allocator<profile> &>': construction with an allocator must be possible if uses_allocator is true
static_assert(is_constructible_v<_Tp, _Args..., const _Alloc&>,
|
update(allocator_type allocator = {})
: profiles_{ allocator }
Converts allocator to profile and initializes profiles_ with an initializer_list containing single element, which is getting copied.
Either change {} to () or make profile constructor explicit (you might want to provide separate non-explicit default constructor in this case)
|
73,650,604
| 73,650,875
|
Is there a way to create a new tuple from an already exisiting tuple?
|
I need a way to generate a new tuple from another tuple.
std::string f1(int a)
{
std::string b = "hello";
return b;
}
float f2(std::string a)
{
float b = 2.5f;
return b;
}
int f3(float a)
{
int b = 4;
return b;
}
int main()
{
auto t1 = std::make_tuple(1, "a", 1.5f);
//New tuple ---> std::tuple<std::string, float, int>(f1(1), f2("a"), f3(1.5));
return 0;
}
This is just a minimal example of what I want to do. Is there a way of doing this in C++20, maybe using std::tuple_cat?
|
You can use std::apply to do this:
template<class Tuple, class... Fns>
auto tuple_transform(const Tuple& t, Fns... fns) {
return std::apply([&](const auto&... args) {
return std::tuple(fns(args)...);
}, t);
}
auto t1 = std::make_tuple(1, "a", 1.5f);
auto t2 = tuple_transform(t1, f1, f2, f3);
Demo
|
73,650,921
| 73,651,642
|
Why do 'for' and 'for_each' result in different functions being generated by iterating through array elements using lambdas?
|
I'm trying to better understand the interactions of lambda expressions and iterators.
What is the difference between these three snippets of code? onSelect is an std::function that is called when a component is selected.
Example 1 and 3 seem to work quite nicely. Example 2 returns the same index value, regardless of the component clicked.
My intuition is that Example 2 only results in one symbol being generated, and therefore the function only points to the first value. My question is, why would for_each result in multiple function definitions being generated, and not the normal for loop?
components[0].onSelect = [&]{ cout<<0; };
components[1].onSelect = [&]{ cout<<1; };
components[2].onSelect = [&]{ cout<<2; };
components[3].onSelect = [&]{ cout<<3; };
//And so on
vs
for (int i = 0; i < numComponents; ++i)
{
components[i].onSelect = [&]
{
cout<<components[i];
};
}
vs
int i = 0;
std::for_each (std::begin (components), std::end (components), [&](auto& component)
{
component.onSelect = [&]{
cout<<i;
});
|
What is the difference between these three snippets of code?
Well, only the first one is legal.
My intuition is that Example 2 only results in one symbol being generated
Each lambda expression generates a unique unnamed class type in the smallest enclosing scope. You have one block scope (inside the for loop) and one lambda expression so yes, there's only one type.
Each instance of that type (one per iteration) could differ in state, because they could all capture different values of i. They don't, though, they all capture exactly the same lexical scope by reference.
and therefore the function only points to the first value
A lambda expression is always a class type, not a function. A lambda expression with an empty capture is convertible to a free function pointer - but you don't have an empty capture. Finally, the lambda didn't capture only the first value - or any value - but an unusable reference to the variable i. Because you explicitly asked to capture by reference ([&]) instead of value.
That is, they all get the same reference to i whatever its particular value at the time they're instantiated, and i will have been set to numComponents and then gone out of scope before any of them can be invoked. So, even if it hadn't gone out of scope, referring to components[i] would almost certainly be Undefined Behaviour. But as it has gone out of scope, it is a dangling reference. This is an impressive density of bugs in a small amount of code.
Compare the minimal change:
for (int i = 0; i < numComponents; ++i) {
components[i].onSelect = [i, &components]
{
cout<<components[i];
};
}
which captures i by value, which is presumably what you really wanted, and only takes components by reference. This works correctly with no UB.
My question is, why would for_each result in multiple function definitions being generated, and not the normal for loop?
You have two nested lambda expressions in example 3, but we're only concerned with the inner one. That's still a single lambda expression in a single scope, so it's only generating one class type. The main difference is that the i to which it has (again) captured a reference, has presumably not gone out of scope by the time you try calling the lambda.
For example, if you actually wrote (and a minimal reproducible example would have shown this explicitly)
int i = 0;
std::for_each (std::begin (components), std::end (components), [&](auto& component)
{
component.onSelect = [&]{
cout<<i;
});
for (i = 0; i < numComponents; ++i)
components[i].onSelect();
then the reason it would appear to work is that i happens to hold the expected value whenever you call the lambda. Each copy of it still has a reference to the same local variable i though. You can demonstrate this by simply writing something like:
int i = 0;
std::for_each (std::begin (components), std::end (components), [&](auto& component)
{
component.onSelect = [&]{
cout<<i;
});
components[0].onSelect();
components[1].onSelect();
i = 2;
components[1].onSelect();
|
73,651,580
| 73,651,858
|
c++ vector with two parameters
|
I don't quite understand what the following does:
std::vector<const char*> getRequiredExtensions()
{
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
if (enableValidationLayers) {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
return extensions;
}
I don't understand this line:
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
What exactly does it do? And what does glfwExtensions resolve to, I only get that it's a double pointer (Which is also a new concept for me).
And what does the glfwExtensions + glfwExtensionCount mean?
thanks for any help!
|
Let's concentrate on the following line of code:
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
This declares extensions as a variable of the templated std::vector<typename T> type, where the T type resolves to const char* (that is, it declares a vector whose elements are each pointers to constant character data). This vector object is initialized using the constructor that takes two iterator arguments – the form (5) on this cppreference page.
A point of confusion here may be how the arguments are iterators: well, pointers are also iterators (in many ways). In this case, the const char** glfwExtensions; line declares a variable that points to a const char* (which is the type of the vector's elements), and the call to glfwGetRequiredInstanceExtensions makes this point to the beginning of an array of such (const char*) pointers and sets the glfwExtensionCount variable to the number of elements in that array. Further, adding the size of an array to a pointer to its first elements yields a pointer to "one past the end" of the array – which is equivalent to an STL "end" iterator.
Thus, the two arguments to the constructor are, effectively, acting as std::begin(glfwExtensions) and std::end(glfwExtensions) – but those functions can't be used directly, because glfwExtensions is not an array of known size in this context.
|
73,651,991
| 73,652,598
|
Is there anything from the standard library or boost that facilitates conditionally executing a function?
|
I am refactoring a function with too many if-else's, something like the following but more complicated. Some major characteristics of this function are:
It bails out early for many pre-conditions (e.g., condition1() and condition2()).
It only does some meaningful stuff on very specific scenarios (e.g., doA() and doB()). (Oh yeah, the beauty of temporary bug fixing!)
Some pre-conditions may or may not be independent of additional conditions (e.g., condition3/4/5/6()).
retT foo() { // total complexity count = 6
if (!condition1()) { // complexity +1
return retT{};
}
if (!condition2()) { // complexity +1
return retT{};
}
if (condition3()) { // complexity +1
if (condition4() || condition5()) { // complexity +2
return doA();
}
else if (condition6()) { // complexity +1
return doB();
}
}
return retT{};
}
The goal is to call out those actual works on their precise conditions rather than leaving them vulnerable to the change of the if-else structure in foo(). More specifically, I would like to turn foo() into something like this:
retT foo() { // total complexity count = 4
ConditionalCommand<retT> conditionalDoA{doA};
conditionalDoA.addCondition(condition1());
conditionalDoA.addCondition(condition2());
conditionalDoA.addCondition(condition3());
conditionalDoA.addCondition(condition4() || condition5()); // complexity +1
ConditionalCommand<retT> conditionalDoB{doB};
conditionalDoB.addCondition(condition1());
conditionalDoB.addCondition(condition2());
conditionalDoB.addCondition(condition3());
conditionalDoB.addCondition(!(condition4() || condition5())); // complexity +2
conditionalDoB.addCondition(condition6());
for (auto& do : {conditionalDoA, conditionalDoB}) {
if (do()) { // complexity +1
return do.result();
}
}
return retT{};
}
This makes the implementation more linear and the conditions for performing a particular work more explicit. I understand that it would be equivalent to just creating a first-level if-clause for each work with all the added conditions listed, but the above code would:
reduce our internal complexity measurement (if-else, logical operators, and ternary based, as illustrated in the code comments),
prevent future intrusion into the first-level if-clauses by a new developer, for example, who wants to doC() instead of doA() if condition7() is true, and
allow me to refine each work's conditions independently of those of the other works (recall that some conditions might be depending on each other).
So the question is, is there any existing std or boost utility that does what ConditionalCommand does so I don't need to reinvent the wheel?
|
Edit: conclusion at the top, frame challenge below.
Back to the original question, is there anything existing in std or boost to do what ConditionalCommand does?
OK, if you're really not worried about the fact that this design violates your own stated requirements, the answer is: NO. Nothing does exactly this.
However, you could just write something like
std::array condA { condition1(), condition2(), condition3(),
(condition4() || condition5()) };
if (std::ranges::all_of(condA, std::identity{})) doA();
if (std::ranges::all_of(
std::initializer_list<bool>{
condition1(), condition2(), condition3(),
(condition4() || condition5()),
condition6()
},
std::identity{})
)
doB();
or whatever takes your fancy. You're only suggesting a very thin convenience layer over this logic.
This makes the implementation more linear
Between perfectly linear control flow and a perfectly linear data structure, I don't really see any advantage either way on this criterion.
the conditions for performing a particular work more explicit
If by "more explicit" you mean "more declarative", then I guess so. You've hidden everything that is actually going on inside some mystery templates though, so it had better be very clear, intuitive and well documented.
reduce our internal complexity measurement (if-else, logical operators, and ternary based, as illustrated in the code comments),
Your "internal complexity measurement" is, frankly, stupid. If you optimize for a bad objective, you'll get a bad result.
Here you have very obviously increased overall complexity, increasing the learning curve for new developers, making the relationship between conditions and their consequences less clear and control flow much harder to debug.
But you've done it in a way that your "internal complexity measurement" chooses to ignore, so it looks like an improvement.
Although I dislike cyclomatic complexity as a broad measure, if yours is genuinely so much higher than shown in the question that refactoring is required - I'd still try just refactoring the procedural code before I considered your proposal.
prevent future intrusion into the first-level if-clauses by a new developer, for example, who wants to doC() instead of doA() if condition7() is true
Just write unit tests for every combination of your 7 conditions (or a single test that runs every permutation) and let your junior developer find out for themselves when the CI server complains about their branch.
You're not helping them get less junior by obfuscating your code like this, you're trying to insulate yourself from their mistakes in a way that doesn't actually help them improve.
Also, the original control flow may even have bugs in them
In that case you should definitely be writing test cases first! You're talking about refactoring code you don't trust in a way that violates your own stated requirements with no way to validate the result.
allow me to refine each work's conditions independently of those of the other works (recall that some conditions might be depending on each other).
If you really want a less error-prone way of organizing this, these condition inter-dependencies should be encoded explicitly. At the moment you can still break everything by adding conditions in the wrong order.
Further, you're currently executing all conditions unconditionally except for the short-circuit evaluation of conditions 4 & 5. Is this even well-defined? Is it guaranteed to remain well-defined?
Still further, you're now evaluating each condition multiple times, once for each possible action.
If you really must encode this in data rather than code, it could be something like an explicit dependency graph (so condition2 depends-on condition1 and is never executed unless that dependency evaluates to true). Then you can have multiple leaf actions attached to the same graph, and don't need any redundant re-evaluations.
To be fair, implementing this is a pain, but at least it satisfies your dependency requirement.
|
73,652,195
| 73,652,327
|
in C++, is std::move still preferred when calling a function that takes in a const reference?
|
Of the two versions of function calls below, is the one with std::move still preferred?
void myFunc(const std::string& myStr){
//
}
std::string MyStr = "my string";
//For these 2 versions, should I still prefer std::move here to save a value copy, even when the function itself takes in a reference?
myFunc(std::move(MyStr));
myFunc(MyStr);
|
When passing a value by reference std::move doesn't make any sense, because no instantiation is happening here, and there would be no side effects (provided you don't want to alter overload function candidate)
Thus for this particular case there is no any difference and you don't need std::move
|
73,652,567
| 73,652,755
|
How to match callable objects out of parameter pack to corresponding element in an array as argument?
|
For example, say I have the following:
template<typename ...FunctionTypes>
static void MainFunction(FunctionTypes... functions)
{
constexpr Uint32_t NumFunctions= sizeof...(FunctionTypes);
std::array<double, NumFunctions> myArray;
double arg1 = 4.2;
int arg2= 9;
for_each_tuple(myArray, FigureOutThisPart(myFunctions, arg1, arg2)...);
}
Where for_each_tuple takes a tuple or array of size N as well as N functions to apply to each tuple entry. This part was tricky to implement, but works! It is defined as such:
namespace detail {
template <typename Tuple, std::size_t ...Indices, typename ...FunctionTypes>
constexpr void for_each_tuple_impl(Tuple&& tuple, std::index_sequence<Indices...>, FunctionTypes&&... functionsIn) {
std::tuple<FunctionTypes...> functions = std::tie(functionsIn...);
using swallow = int[];
(void)swallow{
1, // Make sure array has at least one element
(std::get<Indices>(functions)(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...
};
}
}
template <typename Tuple, typename ...Functions>
void for_each_tuple(Tuple&& tuple, Functions&&... f) {
constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
static_assert(N == sizeof...(Functions), "Need one function per tuple entry");
detail::for_each_tuple_impl(
std::forward<Tuple>(tuple),
std::make_index_sequence<N>{},
std::forward<Functions>(f)...);
}
The idea is that I have set of myFunctions, each of which is operating on a different entry of myArray. Each function in myFunctions would take arg1, arg2, and the current array entry as arguments.
My goal is to be able to pass arg1 and arg2 into each of myFunctions so that those values can be used in the operation on the current array entry. Is there a sane way in which this can be done? Ideally, I would like the solution to be a constexpr so everything can get resolved at compile time.
|
I think something like this could work:
#include <array>
#include <functional>
template<typename ...FunctionTypes>
constexpr void MainFunction(FunctionTypes... functions)
{
constexpr auto NumFunctions= sizeof...(FunctionTypes);
std::array<double, NumFunctions> myArray{};//Zero-init for now.
double arg1 = 4.2;
int arg2= 9;
std::size_t i=0;
(std::invoke(functions, arg1,arg2, myArray[i++]),...);
}
#include <iostream>
void foo(double a1, int a2, int a){
std::cout<<"Called foo("<<a1<<','<<a2<<','<<a<<")\n";
}
int main()
{
MainFunction(foo,foo);
return 0;
}
It requires C++17 for the fold expression and the sequence points for the comma.
It can be evaluated at compile-time:
constexpr void bar(double a1, int a2, int a){
}
int main()
{
constexpr auto x = (MainFunction(bar,bar),1); // Force compile-time evaluation.
return 0;
}
|
73,653,604
| 73,653,802
|
How to use unique_ptr fo automatic memory management?
|
I want a memory block that I can resize, so using the C library functions:
{
char *buf = reinterpret_cast<char*>(std::malloc(n));
⋮
std::realloc(buf,N);
⋮
std::free(buf);
}
How can I go about using smart pointer protection (against leaking buf) in the above snippet?
If I replace the first instruction with this:
uBuf = std::make_unique<char[]>(n); char *buf = uBuf.get();
Would that "free" me from worrying about the final free()?
Would the std::unique_ptr tolerate resizing its *raw protégé (no longer n bytes) and do the delete[] expected from it when leaving the scope ?
If not, how to do it?
|
would "free" me from worrying about the final free() ?
Yes, it will correctly call delete[] for you.
Would the unique_ptr tolerate resizing its *raw protégé (no longer n bytes) and do the delete[] expected from it when leaving the scope ?
Calling realloc on the raw pointer causes undefined behavior, because it was not allocated with malloc/calloc/realloc, but with new[].
To make this work correctly, you need to use a custom deleter which calls free instead of delete[]. Then you need to allocate the pointer manually instead of using std::make_unique, so that the allocation comes from malloc. Then to handle ownership during the realloc call you need to release the owned pointer, call realloc, check its return value for failure, and then conditionally hand ownership back to the smart pointer, e.g.:
struct FreeDeleter {
void operator()(void* p) const noexcept { std::free(p); }
};
template<typename T>
// C++20 constraint to assure free is appropriate for the type
requires std::is_trivial_v<std::remove_all_extents_t<T>>
using free_unique_ptr = std::unique_ptr<T, FreeDeleter>;
//...
auto buf = free_unique_ptr<char[]>(static_cast<char*>(std::malloc(n)));
//...
auto buf_raw = buf.release(); // after this `buf` does not own the buffer anymore
if(auto buf_new = std::realloc(buf_raw, N)) {
buf.reset(static_cast<char*>(buf_new));
} else {
// realloc failed, return ownership of the old pointer
buf.reset(buf_raw);
// handle failure here as appropriate
}
You would probably want to wrap the whole sequence in a function (and the allocation line maybe as well) to avoid mistakes in there. This would be an "unsafe" block where temporarily the smart pointer does not guarantee the deletion (because the pointer is released).
As already mentioned in the comments, this is worth it only if a simple std::vector or std::string doesn't do it. Implementations for these two do not typically use realloc, even for trivial types, as far as I know, but how worth realloc instead of copying to a new allocation immediately is will depend on the allocator used.
|
73,653,615
| 73,653,857
|
Reference to child class lost after assigning to a base instance
|
I'm trying to implement a Runner class that handles different types of objects dynamically, this Runner should be agnostic of what type of object is handling and use abstract class methods to execute functions which the child classes will be in charge of executing their own implementation.
All properties in the Runner class are treated as generic objects, but whenever a child implementation is executed, that implementation is not visible to the Runner because assigning child objects into base type makes the child reference to be lost.
What would be the best implementation for this architecture?
This is my code:
#include <vector>
#include <iostream>
class GenericItem{
public:
virtual void f() {};
};
class GenericList {
public:
virtual void f() {};
std::vector<GenericItem*> list;
};
class Apple: public GenericItem{
public:
Apple(int color){
this->color = color;
}
int color;
};
class House: public GenericItem{
public:
int size;
};
class AppleList: public GenericList{
public:
std::vector<Apple*> list;
};
class HouseList: public GenericList{
public:
std::vector<House*> list;
};
class GenericManager{
public:
virtual GenericList* getList() = 0;
};
class AppleManager: public GenericManager{
public:
AppleManager(){}
AppleList* getList() {
AppleList* list = new AppleList();
list->list.push_back(new Apple(5));
list->list.push_back(new Apple(7));
list->list.push_back(new Apple(9));
return list;
}
};
class Runner{
public:
Runner(GenericManager* manager){
this->manager = manager;
}
GenericItem* chooseItem(){
GenericList* list = this->manager->getList();
std::cout << "Vector size: " << list->list.size() << std::endl;
return list->list.front();
}
GenericManager* manager;
};
int main (){
Runner runner(new AppleManager());
Apple* apple = dynamic_cast<Apple*>(runner.chooseItem());
std::cout << "Apple color: " << apple->color << std::endl;
};
This is the output I got:
Vector size: 0
Segmentation fault (core dumped)
Expected output:
Vector size: 3
Apple color: 5
In this case the function getList() always returns an object with a vector of 3 elements, but when is called by the Runner the object has an empty list.
|
The problem comes from the generic list.
Here you declare a vector of generic items:
// Inside GenericList
std::vector<GenericItem*> list;
But then, you also declare another vector in its child class:
// inside AppleList
std::vector<Apple*> list;
This will shadow the parent's list.
You can't override members like functions, as they have distinct instances and distinct types. Also note that std::vector<Apple*> is completely unrelated to std::vector<GenericItem*>, they don't have any relationship, and cannot be converted from one to another.
You can verify that you have indeed two distinct vector by doing this:
AppleList* getList() {
AppleList* list = new AppleList();
list->list.push_back(new Apple(5));
list->list.push_back(new Apple(7));
list->list.push_back(new Apple(9));
std::cout << list->list.size() << list->GenericList::list.size();
return list;
}
You will see 30 in the output.
An easy solution would be to simply remove the child's vector, and only use the parent's one:
class GenericList {
public:
virtual void f() {};
std::vector<GenericItem*> list;
};
class AppleList: public GenericList{
};
class HouseList: public GenericList{
};
Fundamentally, you cannot reinterpret an array of a type to be an array of a different type. This is not a std::vector limitation, but a limitation of (any) OO langages that allow multiple inheritance since the Apple part of each GenericItem might be at different places and each of the items need to be casted one by one.
|
73,653,939
| 73,653,960
|
sizeof instance of std::vector returns wrong number of elements in the vector
|
I have a cycle, that defines a vector of GLfloat vertices coordinates. (three 1.0f floats describe the color, it doesn't matter)
std::vector<GLfloat> verticesUnitPoints;
float xCurrent = -1.0f;
for (int i = 0; i <= 8; i++)
{
float yOffset = 0.01f;
//first vertex
verticesUnitPoints.push_back(xCurrent);
verticesUnitPoints.push_back(yOffset);
verticesUnitPoints.push_back(0.0f);
verticesUnitPoints.push_back(1.0f);
verticesUnitPoints.push_back(1.0f);
verticesUnitPoints.push_back(1.0f);
//second vertex
verticesUnitPoints.push_back(xCurrent);
verticesUnitPoints.push_back(-yOffset);
verticesUnitPoints.push_back(0.0f);
verticesUnitPoints.push_back(1.0f);
verticesUnitPoints.push_back(1.0f);
verticesUnitPoints.push_back(1.0f);
xCurrent += 0.25f;
}
I also have a glBufferData function, that must create a buffer with enough place for all vector elements.
glBufferData(GL_ARRAY_BUFFER, sizeof(verticesUnitPoints) * sizeof(GLfloat), &verticesUnitPoints[0], GL_STATIC_DRAW);
But as I can see in output window, only small part of all vertices is rendered.
I can easily fix it by just increasing the multiplier of sizeof(verticesUnitPoints) but I find this solution horrible.
|
sizeof(verticesUnitPoints) returns size of std::vector class (not instance), which is fixed for any number of elements.
In order to obtain this number use member function std::vector::size (verticesUnitPoints.size())
|
73,654,812
| 73,655,310
|
How to represent a floating point number in binary from 32-bit hex value in C++ without using bitset or float variable?
|
Given a 32-bit hex like 0x7f000002, how do I get the full value of this number printed in binary without using bitset or defining any float variables to use union?
I know that it is supposed to display
+10000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.0 for this particular 32-bit hex number.
But I don't know how to get there without using those 2 aforementioned function/variable.
|
You can appeal directly to what the bits in a floating point number mean: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
The last 23 bits store the mantissa, and the eight bits before store the biased exponent (with the one bit before that being the signbit). The number is essentially "1.<mantissa> * 2**(<exponent> + bias)", and multiplying by a power of two is essentially shifting the binary radix point, or adding zeros to the left or right in the binary string.
Taking all that into account (+ edge cases for subnormal numbers and inf and NaN), you can make this function:
std::string floatbits_to_binaryfloatstring(std::uint32_t floatbits) {
bool signbit = floatbits >> 31;
int exponent = (floatbits >> 23) & 0xff;
std::uint32_t fraction = floatbits & 0x7fffffu;
std::string result;
result += signbit ? '-' : '+';
if (exponent == 0xff) {
if (fraction == 0) {
result += "inf";
} else {
result += "NaN";
}
} else if (exponent == 0) {
if (fraction == 0) {
result += "0.0";
} else {
// Subnormal
result += "0.";
result.append(125, '0');
for (int i = 23; i-- > 0;) {
result += (fraction >> i) & 1 ? '1' : '0';
}
// Remove trailing zeroes
result.erase(result.find_last_of('1') + 1u, result.npos);
}
} else {
fraction |= 0x800000u; // Make implicit bit explicit
exponent -= 127 + 23;
// The number is "fraction * 2**(exponent)" in binary
if (exponent <= -24) {
result += "0.";
result.append(-exponent - 24, '0');
for (int i = 24; i-- > 0;) {
result += (fraction >> i) & 1 ? '1' : '0';
}
} else if (exponent >= 0) {
for (int i = 24; i-- > 0;) {
result += (fraction >> i) & 1 ? '1' : '0';
}
result.append(exponent, '0');
result += '.';
} else {
int point = 24 + exponent;
for (int i = 24; i-- > 0;) {
result += (fraction >> i) & 1 ? '1' : '0';
if (--point == 0) result += '.';
}
}
// Remove trailing zeroes
result.erase(result.find_last_not_of('0') + 1u, result.npos);
if (result.back() == '.') result += '0';
}
return result;
}
Example: https://wandbox.org/permlink/9jtWfFJeEmTl6i1i
I haven't tested this thoroughly, there might be some mistake somewhere.
Since this is a weird format in the first place, there probably isn't a prebuilt solution for this. hexfloat is close, but in hex and with binary p notation instead
|
73,654,820
| 73,655,088
|
Convert int to an int array C++
|
Given an input from the user (ex. 123456) you must convert the input int to an int array (ex. {1, 2, 3, 4, 5, 6}.
I was wondering, how can this be done? I have started out with a function that counts the digits the were inputted, and initializes an array with the amount of digits.
Is there another way to go about doing this that is simpler?
This is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int n, counter = 0;
cin >> n;
while (n != 1)
{
n = n / 10;
counter++;
}
counter += 1;
int arr[counter];
return 0;
}
|
Let me solve this in what is a bit overkill for the problem, but will actually teach you various C++ constructs instead of the "C plus a bit syntactic sugar" you are doing right now.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main( int argc, char * argv[] )
{
if ( argc != 2 )
{
std::cout << "Enter *one* number.\n";
return 1;
}
// Don't work with C arrays any more than you absolutely must.
// Initializing a variable with those curly braces is the
// modern C++ way of initialization. The older way using ()
// had some issues (like the "most vexing parse" problem).
std::string input { argv[1] };
// Initialize a vector of int with the elements of input.
// If you need the elements in reverse order, just use
// std::rbegin and std::rend.
std::vector<int> output { std::begin( input ), std::end( input ) };
// The elements of output right now have a value depending on
// the character encoding, i.e. they refer to the *character
// value* of the digit, not the *integer* value. You could
// call `std::stoi` on each, or you can substract the encoded
// value for the letter '0', because the standard guarantees
// that '0' through '9' are encoded with consecutive values.
// This is NOT true for letters!
// The part starting at [] is called a "lambda", and it is a
// very nifty feature in conjunction with <algorithm> that you
// should study at some point (right after you learned what a
// 'functor' is, which is probably a bit down the road yet).
// Think of it as a way to define a local function without
// giving it a name.
std::for_each( output.begin(), output.end(), [](int & i){ i -= '0'; } );
// Prefer range-for over indexed for.
for ( auto & i : output )
{
std::cout << i << "\n";
}
return 0;
}
That solution is a bit heavy on the advanced C++ features, though.
This second one is simpler (no <algorithm> or lambdas), but shows proper input error handling and still avoids manual arithmetics on the number:
#include <iostream>
#include <string>
#include <vector>
int main()
{
int input;
while ( ! ( std::cin >> input ) )
{
// Input can fail, e.g. when the user enters
// letters.
std::cout << "Enter a number.\n";
// Clear the error flag on the input stream.
std::cin.clear();
// Clear input buffer of what the user entered.
std::cin.ignore();
}
std::string number { std::to_string( input ) };
// You *can* reserve space in the vector beforehand,
// but unless you know you will be pushing a LOT of
// values, I would not bother. (Also, there are a
// couple of mistakes you could make if you try.)
std::vector<int> output;
for ( auto & c : number )
{
output.push_back( c - '0' );
}
for ( auto & i : output )
{
std::cout << i << "\n";
}
}
|
73,655,413
| 73,657,241
|
How to get Linux based system in QT5?
|
I am developing an application on qt5 using C++ which will support all popular distros, for this currently I am using QSysInfo
qDebug() << "currentCpuArchitecture():" << QSysInfo::currentCpuArchitecture();
qDebug() << "productType():" << QSysInfo::productType();
qDebug() << "productVersion():" << QSysInfo::productVersion();
qDebug() << "prettyProductName():" << QSysInfo::prettyProductName();
It returns ubuntu, manjaro... in prettyProductName, I actually need a base system like Debian, arch...
|
All Linux distros are just Linux so you need to read distro-specific values:
$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=22.04
DISTRIB_CODENAME=jammy
DISTRIB_DESCRIPTION="Ubuntu 22.04.1 LTS"
PRETTY_NAME="Ubuntu 22.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy
The files are distro-specific and the information in those files are also distro-specific so the files and fields may differ from one distro to another. Some distro may not even have them
Similarly there's a common tool named lsb_release in most common distros and you can check its output if it exists
$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 20.04.5 LTS
Release: 20.04
Codename: focal
If a rare distro doesn't have any of those then probably you're out of luck
|
73,656,117
| 73,656,566
|
Is equivalent destruction undefined behavior?
|
Will running a 'equivalent' procedure to an objects destructor result in undefined behavior under the standard?
Example:
Assume we wish to represent a directed acyclic tree, with homogeneous nodes, with root ownership. A problem with deep-structures is recursive operations. Almost all operations can be implemented, of course, with an allocated stack. However, can the nodes remain homogeneous, and automatically destroyed, without undefined behavior?
Namely by bypassing recursive destruction by doing a logically equivalent stack based destruction operation from the root node. (Ignoring possible exceptions from allocation)
class Node {
// ...
// Assuming unique ownership
Node *left;
Node *right;
~Node() { destroy_deep(); }
void destroy()
{
// Assert: left == nullptr && right == nullptr
// ...
}
void destroy_deep()
{
std::vector<Node *> nodes{ this };
while (nodes.size()) {
Node &next = *nodes.back();
if (!next.left && !next.right) {
next.destroy();
if (next != this) {
// Assume such a deallocate function
deallocate(next);
}
nodes.pop_back();
} else {
if (next.left) {
nodes.push_back(next.right);
}
if (next.right) {
nodes.push_back(next.left);
}
}
}
}
};
|
However, can the nodes remain homogeneous, and automatically destroyed, without undefined behavior?
Sure. First of all let's use proper data type for pointers, as you assume unique ownership we should use std::unique_ptr:
class Node {
using NodePtr = std::unique_ptr<Node>;
// ...
// Assuming unique ownership
NodePtr left;
NodePtr right;
};
Ok now this class will properly manage it's data, but it will destroy the tree recursively. Now to avoid recursion we just create our own custom destructor:
Node::~Node()
{
if( ! (left || right) ) // optimization
return;
std::vector<NodePtr> nodes;
auto populate = [&nodes] ( Node *n ) {
if( n->left ) nodes.push_back( std::move( n->left ) );
if( n->right ) nodes.push_back( std::move( n->right ) );
};
populate( this );
while( !nodes.empty() ) {
auto n = std::move( nodes.back() );
nodes.pop_back();
populate( n.get() );
}
}
Live example
That's it, it will destroy children using std::vector as stack.
|
73,656,671
| 73,656,986
|
std::filesystem::path obtain relative path given a base path without temporary std::string conversion?
|
I am trying to find the relative path of something not from root but from a given path instead, like find the difference of 2 paths using std::filesystem::path objects, for example:
std::filesystem::path path = "/var/log", file = "/var/log/folder1/folder2/log.log";
I was expecting that operator- was implemented for this kind of things so I was expecting something like:
std::filesystem::path rel = file - path; //With a expected result of "folder1/folder2/log.log"
EDIT: After some research and attempts, I finally managed to use std::mismatch like this:
#include <filesystem>
#include <iostream>
#include <algorithm>
int main() {
std::filesystem::path path, file;
path = "/var/log";
file = "/var/log/folder1/folder2/log.log";
// Temporary string conversion
std::string path_str = path.string(), file_str = file.string();
std::filesystem::path str = std::string(std::mismatch(file_str.begin(), file_str.end(), path_str.begin()).first, file_str.end());
std::cout << "Relative path is " << str.relative_path() << std::endl;
return 0;
}
It will output: Relative path is "folder1/folder2/log.log"
My question is: Can the same be done without that temporary std::string conversion?
|
std::filesystem::relative has an overload that accepts a base path and returns the first argument relative to the second, so all you need is:
auto relative_path = std::filesystem::relative(file, path);
Demo
|
73,657,141
| 73,657,175
|
Incompatible pointer types assigning to 'int (*)(int, int, int, int, int)' from 'int *'
|
I have this pointer to an orgFunction takes 5 int as input and returns int, and orgfunctionhook takes the same args and return:
int (*orgFunction)(int a1, int a2 , int a3 , int a4, int a5);
int orgFunctionHook(int a1, int a2 , int a3 , int a4, int a5)
{
// do something..
return orgFunction(a1,a2,a3,a4,a5);
}
void Load(){
orgFunction = (int*)HookFunction((char*)"something", 0x50000, (void*)orgFunctionHook);
}
And the HookFunction takes 3 args, const char, an address for my original function, and some hook
for ease this is the definition for it:
void* HookFunction(char* path, uint64_t vaddr, void* replace);
it returns a void*, my function i want to use it return int, once i use it in the Load()
I get this error:
" Incompatible pointer types assigning to 'int (*)(int, int, int, int, int)' from 'int *' "
My attempt to solve it was to declare it like this:
void Load(){
void * orgFunction = (int*)HookFunction((char*)"something", 0x50000, (void*)orgFunctionHook);
}
but this makes a problem in the run time it when it runs the orgFunctionHook, the pointer address to the function orgFunction will be assinged as 0x0 ( EMPTY )
Is there could be another solution to pass this without losing the pointer to the origin function?
EDIT: Forgot to mention, that I can't change anything related to the HookFunction, its return or paramters remain the same.
|
You're casting to the wrong type. As mentioned in the error message, the function pointer has type int (*)(int,int,int,int,int) but you're attempting to assign an expression of type int * to it. These types are incompatible.
The proper way to do this would be to create a typedef for the function pointer type:
typedef int (*ftype)(int, int, int, int, int);
Then you declare your function pointer with this type:
ftype orgFunction;
And similarly with HookFunction:
ftype HookFunction(char* path, uint64_t vaddr, ftype replace);
Then your Load function would look like this:
void Load(){
orgFunction = HookFunction((char*)"something", 0x50000, orgFunctionHook);
}
If you can't modify HookFunction, then just use the typedef in the call:
void Load(){
orgFunction = (ftype)HookFunction((char*)"something", 0x50000, (void *)orgFunctionHook);
}
|
73,657,183
| 73,657,527
|
Passing the template variable to the Observers from the Subject - Observe design pattern
|
I am utilizing an observer design pattern for this simple use case whereupon a change in a Subject concrete class, the template value _x is passed to the observers via notify() however that will require Subject to be a template class which I don't want.
Instead of making Subject a template class, I made notify a template function and made Observer a template to allow the passing of a template value in update() but that will cause problems inside Subject which doesn't need to be a template class.
Any ideas on getting around this problem without making Subject template?
class Subject;
template<typename T>
class Observer
{
public:
virtual void update(T value, Subject *) = 0;
};
class Subject
{
std::vector<Observer<T>*> _obs;
public:
void attach(Observer<T>* obs)
{
_obs.push_back(obs);
}
template<typename T>
void notify(T value)
{
for (auto& o: _obs)
{
o->update(value, this);
}
}
};
template<typename T>
class B : public Observer<T>
{
public:
void update(T value, Subject* sub)
{
std::cout << "Value set = " << value << std::endl;
}
};
template<typename T>
class A : public Subject
{
T _x;
public:
void set(T value)
{
_x = value;
notify(_x); // want to pass T without making Subject template
}
};
int main()
{
A<int> a1;
B <int> b1;
a1.attach(&b1);
a1.set(10);
}
|
If you really promise that for notify<T>, there are only Observer<T>, then you could use a dynamic_cast safely:
class Subject;
class ObsBase{
virtual ~ObsBase()=default;
};
template<typename T>
class Observer:public ObsBase
{
public:
virtual void update(T value, Subject *) = 0;
};
class Subject
{
//If this is the owner, use std::unique_ptr<ObsBase>
std::vector<ObsBase*> _obs;
public:
void attach(ObsBase* obs)
{
_obs.push_back(obs);
}
template<typename T>
void notify(T value)
{
for (ObsBase* o: _obs)
{
auto* d = dynamic_cast<Observer<T>*>(o);
if(d!=nullptr)
d->update(value, this);
}
}
};
|
73,658,473
| 73,665,788
|
How to customize a QScopedPointerDeleter to avoid calling destructor of parent class
|
I have 2 classes A and B, which looks like this
class A{
public:
~A(){/* do something */};
};
class B : public A{
public:
~B(){/* do something */};
};
I want to avoid calling ~A() when ~B() is called. I found this post said that std::shared_ptr can customize deleter to control destructor. But I'm working on a Qt project which uses QScopedPointer to declare B.
Now my question is:
How to customize the QScopedPointerDeleter to avoid calling destructor of parent A?
|
The good guy
Don't do it. Solve the actual problem in a clean way.
The bad guy - I really want to do it
WARNING Keep in mind that you may get in trouble using this approach, f.ex. by creating memory leaks or undefined behavior.
Note that calling the child destructor ~B, without executing the parent/base destructor ~A isn't possible:
Even when the destructor is called directly (e.g. obj.~Foo();), the
return statement in ~Foo() does not return control to the caller
immediately: it calls all those member and base destructors first. [1]
However, you can move the logic of ~B to another member function and call that one instead:
class B : public A{
public:
~B(){/* do something */};
void DestructWithoutParent () {
/* do something */
/* call destructor of members*/
}
};
Note that you should now call the destructor of your members (if any) explicitly.
Now you can release the memory of your B object manually and call your custom destructor function (see this answer for more information and why you shouldn't use this approach):
B *b = new B();
b->DestructWithoutParent (); // calls the 'destructor' of B without calling ~A
operator delete(b); // free memory of b
Note that the heap memory owned by A (f.ex. by smart pointer members of A), isn't released in this way. It may also violate the assumptions made by the programmer of class A, possibly resulting in undefined behavior.
Integrating this with QScopedPointer[2]:
struct BDeleter {
static inline void cleanup(B *b)
{
b->DestructWithoutParent (); // calls the 'destructor' of B without calling ~A
operator delete(b); // free memory of b
}
};
QScopedPointer<B, BDeleter> b(new B);
|
73,659,169
| 73,659,233
|
Why is this C++ program outputting this with a input of 5?
|
this is the code:
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
const double PERC19 = 0.2;
const double PERC49 = 0.3;
const double PERC99 = 0.4;
const double PERC100 = 0.5;
const double Price = 99.00;
double totalCost, originalAmount, discountAmount, dRate;
int numberofSold;
cout << "Enter the number of units sold\n";
cin >> numberofSold;
// Input Validation
if (numberofSold < 0) {
cout << "Input should be a positive number\n";
exit(0);
}
originalAmount = numberofSold * Price;
if(numberofSold >= 10 && numberofSold <= 19){
cout << "test";
discountAmount = originalAmount * PERC19;
totalCost = originalAmount - discountAmount;
}
if(numberofSold >= 20 && numberofSold <= 49){
cout << "test";
discountAmount = originalAmount * PERC49;
totalCost = originalAmount - discountAmount;
}
if(numberofSold >= 50 && numberofSold <= 99){
cout << "test";
discountAmount = originalAmount * PERC99;
totalCost = originalAmount - discountAmount;
}
if(numberofSold >= 100){
cout << "test";
discountAmount = originalAmount * PERC100;
totalCost = originalAmount - discountAmount;
}
cout << totalCost;
}
this is it's output:
PS C:\C_programs\first assing> .\asign.exe
Enter the number of units sold
5
3.95253e-323
PS C:\C_programs\first assing>
when given an input of 5, why would this be outputted? 5 does not qualify for any of the if statements. totalCost should be null, but instead it does 3.95253e-323 instead when run on my computer.
on replit.com, it outputs 395 instead, which is the calculation for the first if statement (not the input val one), dispite not actually running the statement.
|
You have not initialized the variable totalCost to anything. Reading an uninitialized variable is undefined behavior (anything can happen). In your case it so happens to return the value 3.95253e-323 which you then output in the last line. The fix is to initialize it with:
double totalCost = 0;
You can also ensure you set it by ensuring one of your if statements apply.
|
73,660,023
| 73,660,905
|
How condition_variable comes to deadlock
|
I write a demo about condition_variable. I need the correct order to be first-second-third, but there comes to the deadlock.Program infinite loop and there is no output.
class Foo
{
public:
void printfirst() { printf("first"); }
void printsecond() { printf("second"); }
void printthird() { printf("third"); }
Foo()
{
}
mutex mtx;
condition_variable cv1, cv2;
void first()
{
lock_guard<mutex> l(mtx);
printfirst();
cv1.notify_one();
}
void second()
{
unique_lock<mutex> ul(mtx);
cv1.wait(ul);
printsecond();
cv2.notify_one();
}
void third()
{
unique_lock<mutex> ul(mtx);
cv2.wait(ul);
printthird();
}
};
when i add two var (firstready and secondready) and invoke the condition_variable.wait(lock,function()), there is no error. whats the difference of these two function?
class Foo
{
public:
void printfirst() { printf("first"); }
void printsecond() { printf("second"); }
void printthird() { printf("third"); }
Foo()
{
firstready=false;
secondready=false;
}
mutex mtx;
bool firstready,secondready;
condition_variable cv1, cv2;
void first()
{
lock_guard<mutex> l(mtx);
printfirst();
firstready=true;
cv1.notify_one();
}
void second()
{
unique_lock<mutex> ul(mtx);
cv1.wait(ul,[&]{return firstready;});
printsecond();
secondready=true;
cv2.notify_one();
}
void third()
{
unique_lock<mutex> ul(mtx);
cv2.wait(ul,[&]{return secondready;});
printthird();
}
};
|
The first code may deadlock because, for example, cv2 might be notified before third starts running. The condition variable doesn't remember that you notified it. If nobody is waiting when you notify it, nothing happens.
The second code remembers that the notification was sent. It only waits if secondready is false, otherwise it doesn't wait. The variable secondready remembers that the condition variable was notified.
The second code is the proper way to use a condition variable. A condition variable is designed so you can wait for almost any condition, e.g. !queue.is_empty() && pi > 3. That's why the condition variable doesn't remember whether the condition is true - it doesn't know what the condition is - that's your job.
|
73,660,415
| 73,660,742
|
How to print 12 12 12..... using two threads in C++11
|
How can I print 12 12 12....continuously using two threads in C++11.
can someone please suggest.
I have used two functions. One function will print "1" and the second function will print "2" with a condition variable. I don't know whether this is a correct approach or not
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <chrono>
using namespace std;
mutex m;
condition_variable cv;
bool flag = false;
void func1(int i)
{
while(1)
{
unique_lock<mutex> lg(m);
cout << i;
if(flag)
flag = false;
else
flag = true;
lg.unlock();
cv.notify_one();
}
}
void func2(int i)
{
while(1)
{
unique_lock<mutex> ul(m);
cv.wait(ul, [](){return (flag == true) ? true : false;});
cout << i;
ul.unlock();
//this_thread::sleep_for(chrono::milliseconds(2000));
}
}
int main()
{
thread th1(func1, 1);
thread th2(func2, 2);
th1.join();
th2.join();
return 0;
}
|
You have to make the flag to be toggled by each thread, then each one should wait for the flag to have the correct value. The code below should make the job
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <chrono>
using namespace std;
mutex m;
condition_variable cv;
bool flag = false;
void func1(int i)
{
while (1)
{
unique_lock<mutex> lg(m);
cv.wait(lg, []() {return (flag == false) ? true : false; });
cout << i;
flag = true;
this_thread::sleep_for(chrono::milliseconds(200));
lg.unlock();
cv.notify_one();
}
}
void func2(int i)
{
while (1)
{
unique_lock<mutex> ul(m);
cv.wait(ul, []() {return (flag == true) ? true : false; });
cout << i;
flag = false;
this_thread::sleep_for(chrono::milliseconds(200));
ul.unlock();
cv.notify_one();
}
}
int main()
{
thread th1(func1, 1);
thread th2(func2, 2);
th1.join();
th2.join();
return 0;
}
|
73,660,529
| 73,660,920
|
How to get the index of function argument in C/C++ with or without a macro?
|
We are trying to find a way to get the index of a function argument in C. More specifically, we have a function prototype we want to follow, for example, void f(int a, int b, int *c). Unfortunately, this prototype cannot change for compatibility issues. What we want is to allow the user of the function to explicitly state some arguments to be ignored, but because the arguments can be of any kind (if we had only pointer arguments for example, checking the pointers for null values could solve the issue) we are thinking of recording the argument position with some macro and then accessing it from inside the function. We are thinking of something like the following :
f(a, IGNORE(b) or maybe IGNORE, &c)
where IGNORE somehow records the position of the argument and stores it somewhere (we are going to use some static variables for this) and then we can access the index of the argument to be ignored from inside the function and make choice about ignoring the argument. We know that this can probably be solved by replacing f with a macro but we are not really sure we are allowed to do this. We are probably allowed to use C++ for this but again without altering the function prototype. Thanks in advance for your time.
UPDATE : The prototype provided is just an example we also have function with prototype similar to void f(int a, int b), so to our knowledge function overloading will not work.
|
If I understand correctly, you have functions that you cannot change and you want to enable calling the function with "missing" parameters in any position.
You can use overloading by a wrapper with std::optional arguments. The caller can then either pass parameters or std::nullopt where the wrapper then uses the default for that argument:
#include <optional>
#include <iostream>
void f(int a,int b){
std::cout << a << " " << b;
}
constexpr int f_a_default = 42;
constexpr int f_b_default = 42;
void f(std::optional<int> a,std::optional<int> b){
f(a.value_or(f_a_default), b.value_or(f_b_default));
}
int main() {
f(1,std::nullopt);
f(2,3);
f(std::nullopt,3);
}
The original f must not be modified. If the caller does provide parameters for all arguments the original f is called.
For more complex types you might want to facilitate perfect forwarding.
PS: I assumed you do not want to modify the calls too much, ie f(2, no parameter) can be f(2,std::nullopt) but it should not be g(2,std::nullopt) or g<f>(2,std::nullopt). If thats not the case, the whole thing could be made more generic by writing a template wrapper than can be called like this generic_wrapper<f>(2,std::nullopt);. This would save a lot of boilerplate, because you could use a single wrapper rather than one wrapper for each function.
|
73,660,847
| 73,661,431
|
What does time complexity actually mean?
|
I got the task of showing the time taken by the merge sort algorithm theoretically ( n log(n) ) and practically (by program) on a graph by using different values of n and time taken.
In the program, I'm printing the time difference between before calling the function and after the end of the function in microseconds I want to know what dose n log(n) means.
I tryed with this values:
Number of values:
10000 20000 30000 40000 50000 60000 70000 80000 90000 100000
program time in micro second:
12964 24961 35905 47870 88764 67848 81782 97739 111702 119682
time using n log n formula:
132877 285754 446180 611508 780482 952360 1.12665e+006 1.30302e+006 1.48119e+006 1.66096e+006
code:
auto start = std::chrono::high_resolution_clock::now();
mergeSort(arr, 0, n - 1);
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
cout << microseconds << " ";
Graph i got:
|
What time complexity actually means?
I interpret your question in the following way:
Why is the actual time needed by the program not K*n*log(n) microseconds?
The answer is: Because on modern computers, the same step (such as comparing two numbers) does not need the same time if it is executed multiple times.
If you look at the time needed for 50.000 and 60.000 numbers, you can see, that the 50.000 numbers even needed more time than the 60.000 numbers.
The reason might be some interrupt that occurred while the 50.000 numbers were sorted; I assume that you'll get a time between the 40.000 numbers and the 60.000 numbers if you run your program a second time.
In other words: External influences (like interrupts) have more impact on the time needed by your program than the program itself.
I got the task of showing the time taken by the merge sort algorithm theoretically (n log(n)) and practically (by program) on a graph by using different values of n and time taken.
I'd take a number of elements to be sorted that takes about one second. Let's say sorting 3 Million numbers takes one second; then I would sort 3, 6, 9, 12 ... and 30 Million numbers and measure the time.
This reduces the influence of interrupts etc. on the measurement. However, you'll still have some effect of the memory cache in this case.
You can use your existing measurements (especially the 50.000 and the 60.000) to show that for a small number of elements to be sorted, there are other factors that influence the run time.
|
73,661,722
| 73,668,899
|
What is an std::uniform_real_distribution<>::param_type?
|
When calling an std::uniform_read_distribution<>, there is an option to specify the range by passing a param_type. dist(generator, decltype(dist)::param_type{1, 2}) seems to work, but I can't find where param_type is defined. Can someone explain what it is or provide a link to its definition in cppreference or the standard?
|
I looked through the docs more carefully and it turns out I missed it earlier.
cppreference
P, the type named by D::param_type, which
satisfies CopyConstructible
satisfies CopyAssignable
satisfies EqualityComparable
has a constructor taking identical arguments as each of the constructors of D that - take arguments corresponding to the distribution parameters.
has a member function with the identical name, type, and semantics, as every member function of D that returns a parameter of the distribution
declares a member typedef using distribution_type = D;
C++17 Standard
P shall satisfy the requirements of CopyConstructible, CopyAssignable, and EqualityComparable types.
For each of the constructors of D taking arguments corresponding to parameters of the distribution, P shall have a corresponding constructor subject to the same requirements and taking arguments identical in number, type, and default values. Moreover, for each of the member functions of D that return values corresponding to parameters of the distribution, P shall have a corresponding member function with the identical name, type, and semantics.
P shall have a declaration of the form using distribution_type = D;
|
73,661,732
| 73,661,889
|
Can't access the file(Internal File Buffer NULL)
|
I have this strange bug. I have a program which writes text to the file using the fstream, but the file is not being created and therefore no text is appended. When I debug my code, it shows me this:
create_new_file = {_Filebuffer={_Pcvt=0x0000000000000000 <NULL> _Mychar=0 '\0' _Wrotesome=false ...} }.
But whenever I use ofstream everything works.
Here is the code:
std::fstream create_new_file{ fileName.str()};
std::unique_ptr<std::string> changes = std::make_unique<std::string>("");
std::cin >> *changes;
create_new_file << *changes << "\n";
Here is the code which works:
std::ofstream create_new_file{ fileName.str()};
I have seen a similar post on Stack Overflow but the answer did not resolve my issue. I have tried adding the std::ios::trunc to the fstream but that did not help. But whenever I use ofstream everything works just as expected.
|
The problem is that for bidirectional file streams the trunc flag must always be explicitly specified, i.e., if you want the file content to be discarded then you must write in | out | trunc as the second argument as shown below.
Thus, to solve the problem change std::fstream create_new_file{ fileName.str()}; to :
//-------------------------------------------------------------------------vvvvvvvvvvvvvvv---->explicitly use trunc
std::fstream create_new_file{ "output.txt", ios_base::in | ios_base::out | ios_base::trunc};
Working demo
|
73,661,830
| 73,662,182
|
How get google.com web page using C socket
|
I wrote code that should query the google.com web page and display its contents, but it doesn't work as intended.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int sockfd;
struct sockaddr_in destAddr;
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
fprintf(stderr, "Error opening client socket\n");
close(sockfd);
return;
}
destAddr.sin_family = PF_INET;
destAddr.sin_port = htons(80);
destAddr.sin_addr.s_addr = inet_addr("64.233.164.94");
memset(&(destAddr.sin_zero), 0, 8);
if(connect(sockfd, (struct sockaddr *)&destAddr, sizeof(struct sockaddr)) == -1){
fprintf(stderr, "Error with client connecting to server\n");
close(sockfd);
return;
}
char *httprequest1 = "GET / HTTP/1.1\r\n"
"Host: google.com\r\n"
"\r\n";
char *httprequest2 = "GET / HTTP/1.1\r\n"
"Host: http://www.google.com/\r\n"
"\r\n";
char *httprequest3 = "GET / HTTP/1.1\r\n"
"Host: http://www.google.com/\r\n"
"Upgrade-Insecure-Requests: 1\r\n"
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\r\n"
"User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36\r\n"
"\r\n";
char *httprequest = httprequest2;
printf("start send\n");
int send_result = send(sockfd, httprequest, strlen(httprequest), 0);
printf("send_result: %d\n", send_result);
#define bufsize 1000
char buf[bufsize + 1] = {0};
printf("start recv\n");
int bytes_readed = recv(sockfd, buf, bufsize, 0);
printf("end recv: readed %d bytes\n", bytes_readed);
buf[bufsize] = '\0';
printf("-- buf:\n");
puts(buf);
printf("--\n");
return 0;
}
If I send httprequest1, I get this output:
gcc -w -o get-google get-google.c
./get-google
start send
send_result: 36
start recv
end recv: readed 528 bytes
-- buf:
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Fri, 09 Sep 2022 11:52:16 GMT
Expires: Sun, 09 Oct 2022 11:52:16 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
--
In httprequest2, I specified the parameter Host: and I got the following this output:
gcc -w -o get-google get-google.c
./get-google
start send
send_result: 48
start recv
end recv: readed 198 bytes
-- buf:
HTTP/1.1 400 Bad Request
Content-Length: 54
Content-Type: text/html; charset=UTF-8
Date: Fri, 09 Sep 2022 11:53:19 GMT
Connection: close
<html><title>Error 400 (Bad Request)!!1</title></html>
--
Then I try copy headers from browser and after httprequest3 I got same result as for httprequest2.
How can I get the full page?
|
It should be Host: www.google.com and not Host: http://www.google.com/
However, it might not give you the home page. Google wants you to use HTTPS, so it'll probably redirect you to https://www.google.com/ and you won't be able to implement HTTPS fully yourself (you'll have to use a library like OpenSSL)
|
73,661,933
| 73,662,002
|
C++, conflicting between library function and inhertited class function
|
#include <iostream>
#include <unistd.h>
using namespace std;
class A{
public:
bool close(){ return true; }
};
class B: public A{
public:
void fun(){
(void) close(1);
}
};
int main() {
B b;
b.fun();
return 0;
}
In class B I want to call the function close(1) which is in library unistd.h. FYI: close(int fileDes) used to close the file descriptors in process.
So how to overcome the issue. I got the below error:
source.cpp: In member function 'void B::fun()':
source.cpp:11:27: error: no matching function for call to 'B::close(int)'
11 | (void) close(1);
| ^
source.cpp:6:14: note: candidate: 'bool A::close()'
6 | bool close(){ return true; }
| ^~~~~
source.cpp:6:14: note: candidate expects 0 arguments, 1 provided
So how to overcome the issue, so that It will call the function in unistd.h file.
|
In the scope of the member function fun the name close as an unqualified name is searched in the scope of the class
void fun(){
(void) close(1);
}
And indeed there is another member function close in the base class with such a name.
So the compiler selects this function.
If you want to use a function from a namespace then use a qualified name as for example
void fun(){
(void) ::close(1);
}
|
73,662,472
| 73,662,672
|
Can const-default-constructible objects be of non-class types?
|
Per my understanding, for class type T to be const-default-constructible type, the default-initialization of T shall invoke a user-provided constructor, or T shall provide a default member initializer for each non-variant non-static data member: ([dcl.init]/7)
A class type T is const-default-constructible if
default-initialization of T would invoke a user-provided constructor
of T (not inherited from a base class) or if
(7.4) each direct
non-variant non-static data member M of T has a default member
initializer [..]
Noting the bold part, it seems to me that const-default-constructible types can only be class types (including unions and structs). Therefore I can't say that const int, for example, is const-default-constructible type since int is not a class type.
You might ask, from where this confusion comes. Basically, [class.default.ctor]/2 says:
A defaulted default constructor for class X is defined as deleted
if:
[..]
(2.4) any non-variant non-static data member of const-qualified type (or array thereof) with no brace-or-equal-initializer is not
const-default-constructible ([dcl.init]),
[..]
Notice the word "any". This bullet considers cases where X has data member M, and M is of class types as well as non-class types. But per [dcl.init]/7, the const-default-constructible types are limited to only be class types.
Consider the following example,
struct S
{
const int I;
// Is the type of S::I said to be non-const-default-constructible?
S() = default;
};
Is there missing wording? Am I misreading the quotes?
PS: Thanks to @463035818_is_not_a_number for clarifying this. Consider this case:
struct X
{
const int M = 0;
// Is the type of X::M said to be const-default-constructible?
X() = default;
};
|
Is the type of S::I said to be non-const-default-constructible?
Yes. Like you've quoted in [dcl.init]/7 only class types can be const-default-constructible. The reason for this is non-class types do not have a default constructor, meaning they have no default value that can be used if they are declared like
const T foo;
When you read
any non-variant non-static data member of const-qualified type (or array thereof) with no brace-or-equal-initializer is not const-default-constructible ([dcl.init])
It is saying that if you have a member in the form of const T name; in your class then the default constructor is deleted if T is not const-default-constructible. In your case that means your constructor is deleted because const int is not const-default-constructible.
In the case of X, M is still not const-default-constructible because it is not a class type. X though is const-default-constructible because M has a brace-or-equal-initializer so [class.default.ctor]/2.4 does not apply.
This can be boiled down into a simple rule: All const objects must have an initializer
Since built in types do not get default initialized they must have a value provided by the programmer.
|
73,662,903
| 73,663,350
|
Is move elision guaranteed in this case?
|
Consider the following C++20 code; assume T to be non-movable and non-copyable:
struct Cell
{
Cell(T&& instance) : obj(std::move(instance)) {}
private:
T obj;
};
Cell cell(T{/* arguments */});
Is move elision guaranteed in the constructor of Cell?
If T were movable, would it be guaranteed that only the regular (non-move) constructor would be invoked?
|
Is move elision guaranteed in the constructor of Cell?
No, the parameter instance of Cell::Cell(T&& instance) is of rvalue reference type T&&, so there can be no move elision here. The parameter instance must bind to the materialized temporary T{/* arguments */}. Then, std::move(instance) will be used to direct initialize obj.
But note that obj(std::move(instance) won't work because you're trying to initialize obj with std::move(instance) when T is neither movable neither copyable. Demo
|
73,664,004
| 73,709,422
|
How to import classes from C++ to Cython that uses function overloading
|
I have classes nested in classes and inside of a namespace in c++ in the following format:
namespace my_Namespace{
class MyFirstClass{
class NestedClass{
public:
NestedClass(int arg){};
NestedClass(double arg{};
NestedClass(std::string arg){};
};
};
};
And from the documentation you import the classes in cython like so:
cdef extern from "myfile.hpp" namespace "my_Namespace":
cdef cppclass MyFirstClass "my_Namespace::MyFirstClass"
cdef cppclass NestedClass "my_Namespace::MyFirstClass::NestedClass`
Side note, do we need any imports for the cython script to use cppclass? Im not seeing it as a keyword.
Anyway, since NestedClass has constructor overload how would I implement each in cython? I am trying to do this so that it can be normally imported in python, am I better off just making the whole c++ namespace and functions and putting them in a DLL and just use ctypes to import and use the functions?
And one last question I am seeing the documents create classes from the cython code above like so:
cdef class NestedClass:
cdef NestedClass* obj_
def __cinit__(self):
self.obj_=new NestedClass()
def __dealloc__(self): del self.obj_
Is this correct and can I just use the NestClass that I got from the C++ file to derive classes like so:
`cdef class NestedClassInt:
cdef NestedClass* obj_
def __cinit__(self,arg:int): self.obj_=new NestedClass(arg)
#Now define the define the string one
def class NestedClassString:
cdef NestedClass* obj_
def __cinit__(self,arg:str): self.obj_=new NestedClass(arg)
I have been reading multiple forums and I know that python does not support constructor overloading so I don't see if Cython does or if there is a way to convert from it.
|
The upshot as I explained in the comments is that you can declare the overloads for your C++ methods and Cython understands them. You can't declare overloads for methods of cdef classes, and therefore need to pick some other way of switching based on type.
I suggested either using different factory functions (classmethods/staticmethods) or using isinstance in __init__.
# distutils: language = c++
from libcpp.string cimport string as std_string
cdef extern from * namespace "my_Namespace":
"""
namespace my_Namespace{
class MyFirstClass{
public:
class NestedClass{
public:
NestedClass(int arg){};
NestedClass(double arg){};
NestedClass(std::string arg){};
};
};
};
"""
cdef cppclass MyFirstClass:
cppclass NestedClass:
NestedClass(int arg)
NestedClass(double arg)
NestedClass(std_string arg)
cdef class NestedClassWrapper:
cdef MyFirstClass.NestedClass* nc
def __dealloc__(self):
del self.nc
@classmethod # use staticmethod to make this cdef
def make_from_int(cls, int arg):
cdef NestedClassWrapper o = cls.__new__(cls)
o.nc = new MyFirstClass.NestedClass(arg)
return o
# and the same pattern for the int and string versions
cdef class NestedClassWrapper2:
cdef MyFirstClass.NestedClass* nc
def __dealloc__(self):
del self.nc
def __cinit__(self, arg):
if isinstance(arg, int):
# cast to a C int
self.nc = new MyFirstClass.NestedClass(<int>arg)
elif isinstance(arg, float):
self.nc = new MyFirstClass.NestedClass(<double>arg)
elif isinstance(arg, bytes):
self.nc = new MyFirstClass.NestedClass(<std_string>arg)
else:
raise TypeError
Other variations on the theme might also exist. For example a fused type as an argument to __cinit__, or using try: ... except to test the type conversions rather than isinstance. But most solutions will look something like one of these two approaches.
cppclass should be recognised providing you name the file .pyx. It may not be highlighted by your editor though.
|
73,665,940
| 73,666,029
|
How do I convert this C++ 2D array code into Python?
|
I am currently trying to improve my Python coding skills, but am stuck on something. I am attempting to convert some C++ 2D array code that ignores spaces into Python.
What I am trying to do is allow a user to input a number for a 2D array size of their liking and input what they want inside it. For example, 3 would create a 3x3 square. Then, they are to type "D" or "R" depending on the "people's" political affiliation in the 2D array. The input, for example, would be:
R R D *enter D R D *enter D D R *enter
int size = 0;
int input = 0;
int houseAmt = 0;
int R = 0;
int D = 0;
int noChange = 0;
int day = 1;
string check = "";
string cont = "continue";
int quit = 0;
//get n for rows and columns
cin >> size;
//create two dimensional array
char nHood [size][size];
//second array for changed votes
char nHood2 [size][size];
//take user input for grid
for (int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
nHood[i][j] = getchar();
//ignore spaces
if (nHood[i][j] == ' ' || nHood[i][j] == '\n') {
j--;
}
}
}
My conversion is currently this in Python (left out unrelated code):
from msilib.schema import Condition
import sys
import string
D = 0
R = 0
noChange = 0
houseAmt = 0
size = int(input("Please enter the grid size: "))
print("Please enter either 'D' or 'R' using spaces to separate each
one:")
nHood = [[] for _ in range(size)]
#second array for changed votes
nHood2 = [[] for _ in range(size)]
#take input for grid
for i in range(0, size):
for j in range(0, size):
nHood[i][j] = input().split(' ')[0]
#ignore spaces
if nHood[i][j] == ' ' or nHood[i][j] == '\n':
j -= 1
I keep receiving this error when I run the Python program:
line 73, in
nHood[i][j] = input().split(' ')[0]
IndexError: list assignment index out of range
Does anyone have any thoughts on how to fix this? Perhaps using .append somewhere? Thanks!
|
nHood[i] is an empty list, so you should append new element to it.
D = 0
R = 0
noChange = 0
houseAmt = 0
size = int(input("Please enter the grid size: "))
print("Please enter either 'D' or 'R' using spaces to separate each one:")
nHood = [[] for _ in range(size)]
#second array for changed votes
nHood2 = [[] for _ in range(size)]
#take input for grid
for i in range(0, size):
for j in range(0, size):
nHood[i].append(input().split(' ')[0]) # Pay attention to this line
#ignore spaces
if nHood[i][j] == ' ' or nHood[i][j] == '\n':
j -= 1
|
73,665,963
| 73,670,349
|
Non uniform pixel painting in low Frame rate
|
I am making an image editing program and when making the brush tool I have encountered a problem. The problem is when the frame rate is very low, since the program reads the mouse at that moment and paints the pixel below it. What solution could I use to fix this? I am using IMGUI and OpenGL.
Comparision.
Also Im using this code to update the image on the screen.
UpdateImage() {
glBindTexture(GL_TEXTURE_2D,this->CurrentImage->texture);
if (this->CurrentImage->channels == 4) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->CurrentImage->width, this->CurrentImage->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, this->CurrentImage->data);
}
else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->CurrentImage->width, this->CurrentImage->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->CurrentImage->data);
}
}
And the code for the pencil/brush
toolPencil(int _MouseImagePositionX, int _MouseImagePositionY) {
int index = ((_MouseImagePositionY - 1) * this->CurrentImage.width * this->CurrentImage.channels) + ((_MouseImagePositionX - 1) * this->CurrentImage.channels);
//Paint the pixel black
CurrentImage.data[index] = 0;
CurrentImage.data[index + 1] = 0;
CurrentImage.data[index + 2] = 0;
if (CurrentImage.channels == 4) {
CurrentImage.data[index + 3] = 255;
}
}
|
sample your mouse without redrawing in its event ...
redraw on mouse change when you can (depends on fps or architecture of your app)
instead of using mouse points directly use them as piecewise cubic curve control points
see:
How can i produce multi point linear interpolation?
Catmull-Rom interpolation on SVG Paths
So you simply use the sampled points as cubic curve control points and interpolate/rasterize the missing pixels. Either sample each segment by 10 lines (increment parameter by 1.0/10.0) or sample it with small enough step so each step is smaller than pixel(based on distance between control points).
|
73,666,163
| 73,666,210
|
WINAPI in function signature causes errors
|
Though I have spent some years in other languages, my ability in C++ is somewhat limited. I currently have a broad goal to figure out how to use a C++ dll as a function in Excel. This question though is focused on a more narrow area of difficulty in trying to achieve this goal. I am following a tutorial found here. I have created the required files below. These files are based on the tutorial files, but with slight modifications for testing purposes.
SquareLib/SquareLib/SquareLib.h
#pragma once
#ifdef SQUARELIB_EXPORTS
#define SQUARELIB_API __declspec(dllexport)
#else
#define SQUARELIB_API __declspec(dllimport)
#endif
extern "C" SQUARELIB_API double square_double(double x);
extern "C" SQUARELIB_API double square_winapi(double* x);
SquareLib/SquareLib/SquareLib.cpp
#include "pch.h"
#include "SquareLib.h"
double square_double(double x){
return x * x;
}
double WINAPI square_winapi(double* x){
return *x * *x;
}
Coming from other languages, double WINAPI in the SquareLib.cpp source file looks like it might be a return type, and at the very least part of the function signature. Therefore, I don't understand why WINAPI is not duplicated in the header file prototype so that the square_winapi() prototype looks like the line below.
extern "C" SQUARELIB_API double WINAPI square_winapi(double* x);
I have also found that Visual Studio will not compile this unless this change is made. However, even if I do make this change and successfully compile the dll, I have discovered other errors if the resulting dll is used.
First, trying to use the dll in Excel as the tutorial explains seems to result in garbage data that Excel doesn't understand. To understand what is happening, I have created a C++ client program that might eventually be able to receive the dll data from get_square_winapi() and check whether it is null, a string, an empty value, or whatever it might be.
SquareClient/SquareClient/SquareClient.cpp
#include <iostream>
#include "SquareLibrary.h"
void printSquare() {
double factor = 4.1;
double result = square_double(factor);
std::cout << "The square of " << factor << " is " << result << std::endl;
}
int main() {
printSquare();
}
Right now, all this does is use the square_double() function. This client program works fine as long as the winapi prototype and function in SquareLib.h and SquareLib.cpp are commented out. For some reason I don't understand, the winapi prototype/function breaks this code.
C2146 syntax error: missing ';' before identifier 'square_winapi' File: SquareLib.h
C4430 missing type specifier - int assumed. Note: C++ does not support default-int File: SquareLib.h
Why does this happen? How do I fix this?
|
Coming from other languages, double WINAPI in the SquareLib.cpp source file looks like it might be a return type
Only the double is the return value. WINAPI is a preprocessor macro that resolves to __stdcall, ie it is the calling convention of the function, not part of the return type.
and at the very least part of the function signature.
Correct.
Therefore, I don't understand why WINAPI is not duplicated in the header file prototype
Like any part of the function signature, the calling convention needs to be present in both the declaration and implementation of the function. So, you are correct that you will need to use the following in the SquareLib.h file:
extern "C" SQUARELIB_API double WINAPI square_winapi(double* x);
If you don't specify a calling convention, the compiler's default will be used, which is usually __cdecl, but can be specified in the compiler's configuration, so be aware of that. As such, you should always be explicit about the calling convention used when defining code that will be used across module/language boundaries.
This client program works fine as long as the winapi prototype and function in SquareLib.h and SquareLib.cpp are commented out. For some reason I don't understand, the winapi prototype/function breaks this code. Why does this happen? How do I fix this?
WINAPI is defined in windef.h, which is #include'd by windows.h, which you need to #include in any code that interacts with the Win32 API. If you are not #include'ing windows.h in your PCH, then you can just use __stcall directly instead of using WINAPI at all:
extern "C" SQUARELIB_API double __stdcall square_winapi(double* x);
double __stdcall square_winapi(double* x){
return *x * *x;
}
|
73,666,291
| 73,666,465
|
How do I clear a struct if I can't use memset?
|
I'm working with a piece of C++ code previously compiled (for x86) with clang++. In converting to gcc, I'm seeing an error on the following line:
memset(tracking, 0, sizeof(dbg_log_tracking_t));
I understand that I can't memset a 'non-trivial' (compiler's words) class, or something with a vtable, but this is a struct, it's a block of memory and nothing more, yet on compile, g++ tells me that I can't clear an object of a non-trivial type.
I'm being given a pointer as a buffer, and I will read data into that buffer from a phy, and the struct is then used to unpack. This struct needs to be zeroed before the read is done.
In C, I could happily shoot myself in the foot. I could memset main() to null if I so chose, and it's quite frustrating that I cannot do so here.
The only solution I can think of is to keep a static instance of this struct that is already zeroed, and memcpy it over, but that just seems like memset with extra steps and wasted memory.
Short of writing a clear function that hits every field of this specific struct (which would have to be done any time I ever want to do this), how do I zero an entire struct?
|
if you are using C++ 11 or superior
tracking = {};
should work
|
73,666,728
| 73,666,981
|
Implications of Derived class having a different ABI, than Base class?
|
While debugging with gdb, printing the vtable yields something like the following:
(gdb) info vtbl *object
vtable for 'my_namespace_B::MyDerivedObject' @ 0x555555690bf0 (subobject @ 0x5555556ab710):
[0]: 0x55555559ff42 <my_namespace_A::MyBaseObject::function1[abi:cxx11]() const>
[1]: 0x5555555a016c <my_namespace_A::MyBaseObject::function2[abi:cxx11]() const>
[2]: 0x5555555a030a <my_namespace_A::MyBaseObject::function3() const>
[5]: 0x5555555a47f8 <my_namespace_B::MyDerivedObject::~MyDerivedObject()>
[6]: 0x5555555a4846 <my_namespace_B::MyDerivedObject::~MyDerivedObject()>
[7]: 0x5555555a0a80 <my_namespace_B::MyDerivedObject::fun1(bool)>
What does the [abi:cxx11] part mean?
I understand that this should mean that that part of the code was compiled using cxx11 features.
is this understanding even correct?
What implications might this have?
Could this be the reason why calling the virtual function fun1 from within BaseObject::nonVirtualMemberFunction yields undefined behavior?
|
This is the abi_tag attribute, either applied directly to your function or the return type is tagged.
Most likely your functions just return std::string, which libstdc++ tags with abi_tag("cxx11") so that code compiled with the old C++03 copy-on-write strings doesn't link to modern code and silently break.
There are no "visible" differences, just that if you compiled something with the old string ABI it wouldn't link. It should work the same as any other virtual function.
|
73,667,322
| 73,698,368
|
Best way to convert a std::vector< std::array<double, 3> > to Python object using Cython
|
I'm using Cython to wrap a C++ library. In the C++ code there is some data that represents a list of 3D vectors. It is stored in the object std::vector< std::array<double, 3> >. My current method to convert this into a python object is to loop over the vector and use the method arrayd3ToNumpy in the answer to my previous question on each element. This is quite slow, however, when the vector is very large. I'm not as worried about making copies of the data (since I believe the auto casting of vector to list creates a copy), but more about the speed of the casting.
|
This this case the data is a simple C type, continguous in memory. I'd therefore expose it to Python via a wrapper cdef class that has the buffer protocol.
There's a guide (with an example) in the Cython documentation. In your case you don't need to store ncols - it's just 3 defined by the array type.
The key advantage is that you can largely eliminate copying. You could use your type directly with Cython's typed memoryviews to quickly access the underlying data. You could also do np.asarray to create a Numpy array that just wraps the underlying data that already exists.
|
73,667,429
| 73,675,079
|
If you std::move an object can you delete the original safely? Should you?
|
I have difficulty understanding std::move behavior and would like to know whether it is necessary to manually call delete for newStudentDan after "addStudent" in an example like below, or it will be a memory leak.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Student {
public:
Student(std::string name): name_{name} {}
void addParent(std::string name) {
parent_ = name;
}
private:
std::string name_;
std::string parent_;
};
class School {
public:
//constructor
School(): name_{"default"} {}
Student* addStudent(Student student);
Student* addStudent(std::unique_ptr<Student>&& ptr, int);
private:
std::string name_;
std::vector<std::unique_ptr<Student>> students_;
};
Student* School::addStudent(Student student) {
return this->addStudent(std::unique_ptr<Student>{ new Student{std::move(student)}}, 1);
}
Student* School::addStudent(std::unique_ptr<Student>&& ptr, int) {
Student* retval{ptr.get()};
students_.push_back(std::move(ptr));
return retval;
}
int main() {
School newSchool;
Student* newStudentDan = new Student("Dan");
newStudentDan->addParent("Lisa");
newSchool.addStudent(*newStudentDan);
//...continues
return 0;
}
|
I think your confusion stems from two related, but separate concepts: storage duration and object lifetime. Moving an object, just like copying, causes a new object to be created, without ending the lifetime of the original. On the other hand, a memory leak is a failure to deallocate memory that is no longer needed, which is indeed the case with newStudentDan in your example.
The direct answer to your question is that yes, you should always delete any object allocated with new, regardless of what you do with it.
Move semantics can be demonstrated without the use of dynamic allocations:
Student& School::addStudent(Student student) {
students_.push_back(std::move(student));
return students_.back();
}
int main() {
School newSchool;
Student newStudentDan {"Dan"};
newStudentDan.addParent("Lisa");
newSchool.addStudent(std::move(newStudentDan));
}
Perhaps the easiest way to think about it is this: std::move does not actually move anything, it allows the compiler to select functions that may "steal" the object's resources, such as by invoking its move constructor or move-assignment operator. These may not be available, in which case the copy operations are used if available.
In the snippet above, Student has an (implicit) move constructor, so it will be the one used to create the new object from newStudentDan. The lifetime of newStudentDan continues until the end of main() and it will still have some memory associated with it, even though its actual data are now owned by the vector. But because it's now a stack variable (it has "automatic storage duration"), destruction and deallocation occur automatically.
Note that not even move constructors do any moving either, in the sense of relocating data in memory. For example, as this detailed answer explains, the move constructor for std::unique_ptr simply copies a pointer and sets the source pointer to nullptr, without touching the object itself. For better or worse, the word "move" is just a term that indicates the type of semantics where the source object will not necessarily be equivalent to the target object.
|
73,668,294
| 73,668,300
|
C++ is saying that -1 < 13 (in programming) is false
|
I have a string called in, a string that has the value of Hello, world!. I also have a integer called i that has the value -1. When I ask C++ to print out if i is less than the length of in (in.length()), it says false but when I try -1 < 15, it says true. Why does it say false? I feel like this is extremely basic math?
|
string::length() returns an unsigned integer. You can't compare that to a negative signed value, so the -1 gets converted to an unsigned value, which wraps it to a very large number, which is not less than the string's length, hence the result is false.
-1 < 15, on the other hand, is comparing two signed integers, so no conversion is needed, and the result is true, as expected.
|
73,668,821
| 73,668,851
|
what does it mean when we create instance of type, created using enum (and not enum class) in c++
|
I recently got a comment from a SO user (on another account) that Enums are are used to create type and not instances! I wanted to cross-check with the community whether it's right.
As far as I understand there is a plain enum (Enum-Type) and Enum Class in C++.
My que dealt with just enum and had not written enum class anywhere, So, I guess,
the user was talking about Enum-Type. So, is it safe to assume that both Enum-Type and Enum-Class are used to create types? (Enum-Type being not type safe while the converse is true for the later).
And, in the following code, I further wonder what's the need to create instance of example, and what purpose does it solve, Because a gets 0 and b gets 1, in step (1) itself, then, whats the need to create instances
Edit: (Pls correct if wrong) The importance of creating instance is that, now, hello would only be able to take either a or b, it can't even take 0.
enum example {a, b} ; // create a type, example // (1)
example hello ; // create instance named hello, of type example // (2)
|
Yes, both enum and enum class define new types (just like struct and class are used to define new types). And yes, enum is not type safe - you can compare two unrelated enums directly for example and enums implicitly convert to int. enum class on the other hand is type safe - you cannot compare unrelated types (unrelated enum classes) and there are no implicit conversions.
See also:
https://en.cppreference.com/w/cpp/language/enum
|
73,668,869
| 73,677,567
|
Map values to values
|
I have a problem, let's assume I have a string
std::string str = "some_characters_here";
and I have a vector with numbers from 0 to 255
std::vector<int> v;
How can I map each number to closest char in string? like this
function map (number) -> char in string perfect if we can do str[n]
so I have a string len, and I can count this:
int n = 255 / str.length();
But I have no idea what to do next.
Each character in the string now has a weight, the only thing left is to figure out how to give each number a symbol (let's say the number is on the range from symbol-1 to symbol, then give it a symbol)
Here is another example:
|
Although the question is not very clear, as I understand it, you want to divide an array with a size of 255 into ranges according to the length of a string and assign the string's characters to those ranges.
std::vector<char> __map(const std::string &str)
{
std::vector<char> result(256);
float n = (float)256 / str.size(), iter = n;
int id = int(n), loopIndex = 0;
size_t strIndex = 0;
while (id < 256)
{
for (; loopIndex < id; ++loopIndex)
result[loopIndex] = str[strIndex];
++strIndex;
iter += n;
id = (int)iter;
}
if (loopIndex < 256)
for (; loopIndex < 256; ++loopIndex)
result[loopIndex] = str[strIndex];
return result;
}
As in the example above, we have pushed the array according to the string length, assigning the characters in the index of the string to the ranges.
int main()
{
const std::string s = ".^&@$!%";
auto rr = __map(s);
for (size_t i = 0; i < rr.size(); i++)
std::cout << i << " : " << rr[i] << '\n';
return 0;
}
One of the points that is not understood here is this; if you want to keep the characters, you need to use std::vector here, but you used an int type vector in your description. Do you want to keep the code of the characters in the vector?
Now let's look at the problem from a different aspect. Instead of keeping the characters in the series, let's return this structure in the form of a series by keeping the beginning and end of a structure and the value of the character.
struct RangeforChar
{
uint8_t start;
uint8_t end;
char value;
RangeforChar(uint8_t start, uint8_t end, char value) : start(start), end(end), value(value) {}
};
std::vector<RangeforChar> _map(const std::string &str)
{
std::vector<RangeforChar> res;
float n = (float)256 / str.size(), iter = n;
int first = 0, last = 0, id = int(n);
size_t strIndex = 0;
while (id < 256)
{
last = id;
res.emplace_back(first, last, str[strIndex++]);
iter += n;
id = (int)iter;
first = last;
}
res.emplace_back(first, 255, str[strIndex++]);
return res;
}
int main()
{
const std::string s = ".^&@$!%";
auto rr = _map(s);
for (const auto& m: rr)
std::cout << "Range : " << +m.start << " - " << +m.end << " --> " << m.value << '\n';
return 0;
}
Output:
Range : 0 - 36 --> .
Range : 36 - 73 --> ^
Range : 73 - 109 --> &
Range : 109 - 146 --> @
Range : 146 - 182 --> $
Range : 182 - 219 --> !
Range : 219 - 255 --> %
We can write a helper method that returns a character from a string.
char h_get(const std::vector<RangeforChar>& rng, int num)
{
for (const auto& m: rng)
if(num < m.end) return m.value;
throw std::domain_error("An unexpected error has occurred in the program.");
}
char _get(const std::string& str, int num)
{
assert(num >= 0 && num <= 255);
auto rr = _map(str);
return h_get(rr, num);
}
const std::string s = ".^&@$!%";
std:: cout << "Char is " << _get(s, 167);
|
73,669,128
| 73,669,153
|
Why can we push function object to std::thread directly?
|
I'm a little bit confuse about why we can do something like this:
std::vector<std::thread> vec;
vec.reserve(2);
vec.emplace_back(std::bind(silly, 1));
vec.emplace_back(std::bind(silly, 2));
for (auto i = 0; i < vec.size(); i++) {
vec[i].join();
}
// for folks who see this post after
// you can use push_back() like this:
vec.push_back(std::thread(std::bind(silly, 3)));
The code above, we push function object to thread vector directly, and I don't know why it is acceptable. Because from my knowledge thread vector could only push thread type object to it. Just like for a int vector, we could only push int type object to it.
The example below is what I can 100% understand, because we push thread object into thread vector!
std::vector<std::thread> vecOfThreads;
std::function<void()> func = []() {
//Do Some Important Work
// .....
//Print Thread ID
std::cout << "From Thread ID : " << std::this_thread::get_id() << "\n";
};
vecOfThreads.push_back(std::thread(func));
std::thread th1(func);
vecOfThreads.push_back(std::move(th1));
for (std::thread &th: vecOfThreads) {
// If thread Object is Joinable then Join that thread.
if (th.joinable())
th.join();
}
Any explanation and suggested material for studying this part is appreciated!
|
Edit: I missread code sample, as stated in comments, in this particular case of emplace_back, the constructor is called without going through the implicit conversion chain, as is the purpose of emplace_back. Leaving the rest nonetheless since question was about pushing.
C++ offers implicit conversions, which is what enables you to do thing like :
double a = 0;
Without getting an error due to assigning an int literal (0) to a double-type variable (a).
The above link can give you detailed explanation on implicit conversion, but that part that interest us is that :
A user-defined conversion consists of zero or one non-explicit single-argument converting constructor or non-explicit conversion function call
In std::thread documentation, there is a constructor that takes a std::function (and optionally its arguments), so it could be used to automagically convert functions into threads when pushing to thread vector, if the rest of the chain is respected (which apparently it isn't). In your code sample, it is directly called without implicit conversions limitations.
|
73,669,245
| 73,670,331
|
Do I need to call glewInit() for every GLFW window I create?
|
This is my first big OpenGL project and am confused about a new feature I want to implement.
I am working on a game engine. In my engine I have two classes: Renderer and CustomWindow. GLFW needs to be initialized, then an OpenGL context needs to be created, then glew can be initialized. There is no problem with this, until I decided to support multiple windows to be created at the same time. Here are the things I am confused about:
Do I need to initialize GLEW for every window that is created? If no, can I still call glewInit() for every window creation and everything be fine?
If I create a window, and then destroy it, do I have to call glewInit() again and will I have to call these functions again?:
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &numberOfTexturesSupported);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_MULTISAMPLE);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_PROGRAM_POINT_SIZE);
If there is any off topic comments that would help, they are very welcomed.
Update 1: More Context
For reference, the reason I want to do this is to implement multiple window rendering that share the same OpenGL context. Note, each window uses its own vertex array object (VAO). Here is the code for reference:
// CustomWindow.cpp
CustomWindow::CustomWindow() {
window = nullptr;
title = defaultTitle;
shouldClose = false;
error = false;
vertexArrayObjectID = 0;
frameRate = defaultFrameRate;
window = glfwCreateWindow(defaultWidth, defaultHeight, title.c_str(), nullptr, nullptr);
if (!window) {
error = true;
return;
}
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK) {
error = true;
return;
}
glGenVertexArrays(1, &vertexArrayObjectID);
glBindVertexArray(vertexArrayObjectID);
allWindows.push_back(this);
}
CustomWindow::CustomWindow(int width, int height, const std::string& title, GLFWmonitor* monitor, GLFWwindow* share) {
window = nullptr;
this->title = title;
shouldClose = false;
error = false;
vertexArrayObjectID = 0;
frameRate = defaultFrameRate;
window = glfwCreateWindow(width, height, title.c_str(), monitor, share);
if (!window) {
error = true;
return;
}
glfwMakeContextCurrent(window);
glGenVertexArrays(1, &vertexArrayObjectID);
allWindows.push_back(this);
}
CustomWindow::~CustomWindow() {
if (window != nullptr || error)
glfwDestroyWindow(window);
unsigned int position = 0;
for (unsigned int i = 0; i < allWindows.size(); i++)
if (allWindows[i] == this) {
position = i;
break;
}
allWindows.erase(allWindows.begin() + position);
if (mainWindow == this)
mainWindow = nullptr;
}
// Rendere.cpp
Renderer::Renderer() {
error = false;
numberOfTexturesSupported = 0;
if (singleton != nullptr) {
error = true;
return;
}
singleton = this;
// Init GLFW
if (!glfwInit()) {
error = true;
return;
}
// Set window hints
glfwWindowHint(GLFW_MAXIMIZED, true);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 4);
// Init GLEW
if (glewInit() != GLEW_OK) {
error = true;
return;
}
// Set graphics message reporting
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(openglDebugCallback, nullptr);
// Set up OpenGL
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &numberOfTexturesSupported);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_MULTISAMPLE);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_PROGRAM_POINT_SIZE);
}
|
After some research, i would say that it depends, therefore it's always best to have a look at the base to form an opinion.
The OpenGL wiki has some useful information to offer.
Loading OpenGL Functions is an important task for initializing OpenGL after creating an OpenGL context. You are strongly advised to use an OpenGL Loading Library instead of a manual process. However, if you want to know how it works manually, read on.
Windows
This function only works in the presence of a valid OpenGL context. Indeed, the function pointers it returns are themselves context-specific. The Windows documentation for this function states that the functions returned may work with another context, depending on the vendor of that context and that context's pixel format.
In practice, if two contexts come from the same vendor and refer to the same GPU, then the function pointers pulled from one context will work in the other.
Linux and X-Windows
This function can operate without an OpenGL context, though the functions it returns obviously can't. This means that functions are not associated with a context in any way.
If you take a look into the source code of glew (./src/glew.c), you will see that the lib simply calls the loading procedures of the underlying system and assigns the results of those calls to the global function pointers.
In other words, calling glewInit multiple times has no other side effect other than that explained in the OpenGL wiki.
Another question would be: do you really need multiple windows for that task? A different approach could be achieved with only one context and multiple framebuffer objects.
Multiple contexts (sharing resources between them) and event handling (which can only be called from the 'main' thread) needs proper synchronization and multiple context switches.
|
73,669,279
| 73,669,542
|
Spacing is incrementing for no reason when printing
|
I'm trying to print a Christmas tree which would look like.
There is an only issue with spacing in front of the leaves if I input 1 it looks fine but for anything above that the spaces increase by 1.
#include <iostream>
#include <iomanip>
using namespace std;
void pineT (int rows , int finish , int spaces) {
int space; // initialize variables.
string total_space = "";
string stars = "";
string all_images = "";
for(int i = rows, k = 0; i <= finish; ++i, k = 0) // getting rows for requested range.
{
for(space = 1; space <= spaces -i; ++space) // intial space
{
total_space += " ";
}
while(k != 2*i-1) // printing stars per row.
{
stars += "*";
++k;
}
all_images += total_space; // one row.
all_images += stars + "\n";
stars = "";
total_space = "";
}
cout<< all_images; // final product.
}
int main() {
string total_spaces = "";
int start = 1, finish = 3; // intial tree layer increases per increment.
int rows;
cin >> rows;
int intial_spaces =rows*2 +1;
int spaces = intial_spaces;
// printing top half of tree.
while ( finish != rows+3) { // To print multple layers.
pineT (start , finish , spaces);
start +=1 ;
finish +=1;
if ((start > rows)) {
spaces-= start;
}
}
return 0 ;
}
output goal with an input of 2:
The top half is just shifted by 1 and when I input 3 it shifts by 2.
*
***
*****
***
*****
*******
Current output when input 2:
*
***
*****
***
*****
*******
Current output when input 3:
*
***
*****
***
*****
*******
*****
*******
*********
|
The first thing to do to find the problem is to determine whether the problem is in the function main or in the function pineT.
When running your program line by line in a debugger, you will determine that when rows == 1, then main will call the function pineT once, like this:
pineT( 1, 3, 3 );
When rows == 2, then main will call the function pineT twice, like this:
pineT( 1, 3, 5 );
and
pineT( 2, 4, 5 );
Since you did not specify what the function pineT should do exactly, I cannot tell you whether the function pineT does not work as intended or whether the problem is how the function main is calling pineT.
However, according to my tests, the function call
pineT( 1, 3, 3 );
has the following output:
*
***
*****
The function call
pineT( 1, 3, 5 );
has the following output:
*
***
*****
And the function call
pineT( 2, 4, 5 );
has the following output:
***
*****
*******
Using this information, it should be possible for you to determine whether the function pineT does not work as intended, or whether it is the function main that does not work as intended.
|
73,670,155
| 73,670,307
|
How to prevent the compiler from checking the syntactic correctness of a certain branch
|
I basically want to select one of the branches at compile-time but can't figure out how to address the error that shows up.
Here is the code (link):
#include <iostream>
#include <vector>
#include <type_traits>
template <typename charT>
struct Foo
{
using value_type = charT;
std::vector<value_type> vec;
void printVec( std::basic_ostream<charT>& out_stream )
{
out_stream.write( std::data( vec ), std::size( vec ) ).write( "\n", 1 );
}
};
// specialization for char
template <>
void Foo<char>::printVec( std::basic_ostream<char>& out_stream )
{
out_stream.write( std::data( vec ), std::size( vec ) ).write( "\n", 1 );
}
// specialization for wchar_t
template <>
void Foo<wchar_t>::printVec( std::basic_ostream<wchar_t>& out_stream )
{
out_stream.write( std::data( vec ), std::size( vec ) ).write( L"\n", 1 );
}
int main( )
{
using FooChar = Foo<char>;
using FooWideChar = Foo<wchar_t>;
#define IS_CHAR 1
#if IS_CHAR == 1
FooChar foo;
foo.vec.resize( 10, '$' );
#else
FooWideChar foo;
foo.vec.resize( 10, L'#' );
#endif
if constexpr ( std::is_same_v< decltype( foo )::value_type,
decltype( std::cout )::char_type > )
{
foo.printVec( std::cout );
}
else if constexpr ( std::is_same_v< decltype( foo )::value_type,
decltype( std::wcout )::char_type > )
{
foo.printVec( std::wcout ); // this is where the compile error occurs
}
else
{
static_assert( std::is_same_v< decltype( foo )::value_type,
decltype( std::cout )::char_type > ||
std::is_same_v< decltype( foo )::value_type,
decltype( std::wcout )::char_type >,
"character type not supported" );
}
}
The error message:
cannot convert 'std::wostream' {aka 'std::basic_ostream<wchar_t>'} to 'std::basic_ostream<char>&'
The message is self-explanatory however I still don't know how to get around this issue. I guess this problem would not arise if the compiler wouldn't check the syntax of the statement inside the else if branch. Is there any way to make the above snippet compile?
|
Lift your if constexpr logic into a template function:
template <typename charT>
void printIt( Foo<charT>& foo )
{
if constexpr ( std::is_same_v<charT, char> )
foo.printVec( std::cout );
else if constexpr ( std::is_same_v<charT, wchar_t> )
foo.printVec( std::wcout );
else
static_assert( sizeof(charT) == 0, "character type not supported" );
}
Also, note you don't need two definitions of printVec() for char. You can simply declare it in the class without a definition:
void printVec( std::basic_ostream<charT>& out_stream );
It should probably be const, then printIt() can take const Foo&.
|
73,670,564
| 73,671,127
|
Is there a way to make function not type-checked in C++?
|
I am currently implementing a class that is a three-way map, meaning each "index" has three keys and one can retrieve each. The function get is defined as:
template<typename returnType, typename getType>
returnType get(getType getVal) {
if (typeid(returnType) == typeid(getType)) {
return getVal;
}
// Here the appropriate value is gotten. Not important for this.
// This is returned just in-case nothing is found.
return *new returnType;
}
This doesn't compile, because getType is not always equal to returnType, which is guaranteed by my check. Is there a way to make this compile, because the getting process is quite expensive. I've tried to just do return returnType(getVal);, which only works if returnType has a constructor for getType.
Solutions I could imagine but didn't manage to pull of:
template specialization
disable type-checking (similar to rust's unsafe)
P.S: I know this optimisation doesn't make a lot of sense, still would like to know if it's possible to compile.
|
typeid is not meant to be used this way at compile-time. If you want to operate on types at compile-time, use the tools from #include<type_traits>. typeid is meant to be used if you need to operate on types at runtime (e.g. store ids for types in a container or obtain a printable name for a type) or you need to determine the actual type of a polymorphic pointer/lvalue at runtime.
To compare types at compile-time use std::is_same_v<returnType, getType>. Since C++17 it is also possible to conditionally compile branches of an if in a template, using if constexpr instead of if:
template<typename returnType, typename getType>
returnType get(getType getVal) {
if constexpr (std::is_same_v<returnType, getType>) {
return getVal;
} else {
// Here the appropriate value is gotten. Not important for this.
// This is returned just in-case nothing is found.
return /*some returnType*/;
}
}
Also note that applying * to a new expression is practically always wrong. You are returning *new returnType immediately by-value. That is a guaranteed immediate memory leak. new returns a pointer to newly allocated memory with a new object of the given type in it. Returning the dereferenced pointer by-value means that this new object is again copied into the return value and at the same time the lvalue/pointer to the first newly created object is lost in the copy/move constructor.
To create an object to return directly, do not use new. Just return a temporary object using the functional explicit cast notation:
return returnType{};
or even shorter, since returnType is already mentioned in the function return type:
return {};
new is very rarely needed directly in C++. If a variable or a temporary as above also works, then don't use new, and if that doesn't work reconsider whether you shouldn't be using std::unique_ptr/std::shared_ptr/std::vector/std::string/etc. instead of new.
|
73,670,650
| 73,671,155
|
find the total number of subarrays with the ratio of 0's and 1's equal to x:y
|
question
given an array of elements 0, 1, 2 with find the total number of subarrays with the ratio of 0's and 1's equal to x:y.
input
5
1 1
0 1 2 0 1
output
6
\\5 is the size of array 0 1 2 0 1 are elements of the array 1 1 is x and y and now we have to find the subarrays whose counts of 0's and 1's ratio is equal to x and y that is 1 1
\\
here is my approach but it is not giving correct and it gives output 7 rather than 6
#include<bits/stdc++.h>
using namespace std;
int n, x, y;
vector<int> a;
vector<long long> prefix;
map<long long, int> freq;
int main() {
cin >> n;
cin >> x >> y;
a.resize(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i]==0) a[i] = y;
else if( a[i]==0){
a[i]=0;
}
else a[i] = -x;
}
prefix.resize(n+1); prefix[0] = 0;
for (int i = 0; i < n; i++) {
prefix[i+1] = prefix[i] + a[i];
}
for (int i = 0; i < n+1; i++) freq[prefix[i]]++;
long long ans = 0;
for (pair<long long, int> p : freq) {
ans += (long long) p.second * (p.second-1) / 2;
}
cout << ans << endl;
}
|
First, the order you read your inputs is different than what you describe, then your transform of the input values make no sense.
//...
cin >> n;
cin >> x >> y; // program expects x then y, then contents of array.
a.resize(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
if (a[i]==0) a[i] = y;
else if( a[i]==0){ ∕/ case a[i] == 0 was already tested for
// on line above.
a[i]=0;
}
else a[i] = -x;
}
//...
You should sort this out first.
|
73,670,908
| 73,670,969
|
operator<< with cout and precedence
|
The accepted answers to the questions here and here say that it's all about operator precedence and thus,
cout << i && j ;
is evaluated as
(cout << i) &&j ;
since the precedence of Bitwise-Operators is greater than that of Logical-Operators. (It's not the bitwise operator here, but it is the symbol itself which is setting the precedence.)
I wonder then why the following code doesn't output 1:
int x=2, y=1 ;
cout << x>y ;
since the precedence of Relational-Operators is greater than Bitwise-Operators; the last line should get treated as cout << (x>y) ;.
I got a warning that overloaded operator<< has higher precedence than a comparison operator.
What is the precedence of overloaded operator<< in comparison to all other existing operators?
|
someone tell what is the precedence of overloaded operator << in comparison to all other existing operators?
The inserter << has higher precedence than the relational operator<, operator> etc. Refer to operator precedence.
This means that cout << x>y is grouped as(and not evaluated as):
(cout << x)>y;
Now, cout << x returns a reference to cout which is then used as the left hand operand of operator>. But since there is no overloaded operator> that takes cout as left hand operand and int as right hand operand you get the error saying exactly that:
error: no match for ‘operator>’ (operand types are ‘std::basic_ostream’ and ‘int’)
Note
Additionally, in your question you've used the phrase "is evaluated as" which is incorrect. The correct phrase would be "is grouped as".
|
73,671,556
| 73,673,073
|
qt create button when right click
|
I am new in qt I want to create a button when I right click
There is my code:
void MainWindow::right_clicked(QMouseEvent *event)
{
if(event->button() == Qt::RightButton)
{
QPushButton *item = new QPushButton();
item->setIcon(QIcon(":/images/7928748-removebg-preview(1).ico"));
item->setIconSize(QSize(32, 32));
item->setGeometry(QRect(QPoint(event->x(), event->y()), QSize(32, 32)));
}
}
But nothing appears
|
To capture any mouse event in a QWidget you must override the mousePressEvent method.
class MainWindow : public QMainWindow
{
Q_OBJECT
protected:
void mousePressEvent(QMouseEvent *event);
};
And in the mainwindow.cpp, implement it as follows:
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::RightButton) {
// make mainwindow parent of this button by passing "this" pointer
QPushButton *item = new QPushButton(QIcon(":/images/close-button-icon"), "", this);
// set button position to the location of mouse click
item->setGeometry(QRect(QPoint(event->x()-16, event->y()-16), QSize(32, 32)));
item->show();
}
}
If you don't save the pointer to QPushButton, then you will not be able to use it afterwards.
|
73,671,717
| 73,671,765
|
Template paramter pack with different types
|
Can the following function template be made to actually act based on argument type :
#include <iostream>
#include <memory>
#include <tuple>
#include <typeinfo>
using namespace std;
using UPSTR = unique_ptr<char[]>;
template<typename... Ts>
void uprint(Ts const&... strs){
auto tp = std::tie(strs...);
auto& x = std::get<0>(tp);
if(typeid(x)==typeid(UPSTR)) cout << x.get() << endl;
// Error : no match for 'operator<<' and 'const std::unique_ptr<char []>') :
else cout << x << endl;
}
int main(){
UPSTR str = make_unique<char[]>(10); str.get()[0] = 'A';
uprint(str, "hello");
return 0;
}
?
Error from gcc 12.2 : no match for 'operator<<' and 'const std::unique_ptr<char []>')
https://godbolt.org/z/dYG9r7Koj
(MSVC does compile this !)
|
The compiler always instantiates the whole body of a function template, no matter whether some if statements can be proven at compile-time to be false. So any syntax/type errors, even in false branches are reported.
But exactly for this use case, there is if constexpr:
if constexpr (std::is_same_v<std::decay_t<decltype(x)>, UPSTR>)
cout << x.get() << endl;
else
cout << x << endl;
typeid is not compile-time construct, decltype is.
std::decay_t removes references + constness -> easier matching.
Note that since C++20, std::unique_ptr got its operator<< which prints its underlying value exactly through os << x.get() so cout<<x; becomes always valid.
|
73,672,006
| 73,672,074
|
C++, Find out if a string contains a substring?
|
I don't know how to use the find() function to check if a string contains a substring, then the program should print out all Words, and "Contains" if Sentence contains at least one of them. Can anyone help me out? My usage of find() sets A always to true. Thanks for help
#include <iostream>
#include <string>
using namespace std;
string Words, Sentence, buf;
int i, n, j = 0;
string arr[20];
bool A;
int main() {
cout << "Words separated by slashes";
cin >> Words;
cout << "Sentence";
cin >> Sentence;
for (i = 0; i <= Words.length(); i++)
{
if (Words[i] != '/')
{
buf = buf + Words[i];
}
else
{
arr[n] = buf;
n = n + 1;
buf = "";
}
}
for (j = 0; j <= n; j++)
{
cout << arr[j] << "\n";
if (Sentence.find(arr[j]) != string::npos)
{
A = true;
}
}
if (A == true)
{
cout << "Contains.";
}
else
{
enter code herecout << "Does not contain.";
}
}
|
There are a few bugs and issues in this code I think, but the biggest is the for loops all go too far by one.
for (i = 0; i <= Words.length(); i++)
and
for (j = 0; j <= n; j++)
should be
for (i = 0; i < Words.length(); i++)
and
for (j = 0; j < n; j++)
The valid indexes for a string, vector or array are zero upto but not including the size of the string, vector or array.
This mistake causes the bug that you see. Suppose you have two words in arr, e.g. arr = { "stack", "overflow", "", "", ... } . Because you go around the for loop one too many times you end up searching for arr[2] which equals "". This search always succeeds because every string contains the empty string. And so you always set A to true.
|
73,672,049
| 73,672,166
|
How to make copies of the executable itself in C++?
|
I want to make copies of the exe file itself multiple times.
I tried the following code:
#include <fstream>
#include <string>
int main() {
std::ifstream from("main.exe", std::ios::binary);
auto buf { from.rdbuf() };
for(int x { 0 }; x <= 10; ++x) {
std::string name { "main" + std::to_string(x) + ".exe" };
std::ofstream out(name, std::ios::binary);
out << buf;
out.close();
}
from.close();
return 0;
}
But it doesn't work as I expected (It does not copy the executable repeatedly. See the size column in the following screenshot):
How do I solve this problem?
|
Reading from the input file stream buffer consumes the data. You need to reset the stream to the start after copying the file:
...
for (int x{ 0 }; x <= 10; ++x) {
std::string name{ "main" + std::to_string(x) + ".exe" };
std::ofstream out(name, std::ios::binary);
out << buf;
out.close();
from.seekg(0, std::ios::beg); // need to go back to the start here
}
...
You could simply use the std::filesystem standard library functionality for this though:
int main() {
std::filesystem::path input("main.exe");
for (int x{ 0 }; x <= 10; ++x) {
std::filesystem::path outfile("main" + std::to_string(x) + ".exe");
std::filesystem::copy_file(input, outfile, std::filesystem::copy_options::overwrite_existing);
}
return 0;
}
|
73,672,132
| 73,673,078
|
The proper way to initialize array of char with constant string
|
I use a struct to transfer data over TCP-IP and I have to stick with certain packet size, so I use char array of fixed size for text data. Due to the fact that I can't initialize it otherwise, I forced to copy string to that array in constructor using simple function (based on strcpy). The problem is: analyzer (clang-tidy Ubuntu LLVM 14.0.0) tells me
warning: constructor does not initialize these fields: receiver [cppcoreguidelines-pro-type-member-init]
but in fact that is not true. Tell me, please, how do I change my code to suppress those warnings messages? I understand, that I can initialize those arrays with zeros using {} and than fill them with the needed data, but it looks like double work..
inline void copyName(char *dst, const char *src) {
strncpy(dst, src, MAX_NAME_LENGTH);
}
struct Header {
const MessageType type;
char receiver[MAX_NAME_LENGTH];
static uint32_t messageId;
Header();
Header(MessageType type, const char* receiver);
};
Header::Header(const MessageType type, const char *receiverName)
: type(type) // the warning is here
{
copyName(receiver, receiverName);
Header::messageId++;
}
P.S> Found some workaround (which, of course, not the answer to the actual question): there is the option IgnoreArrays for that warning which, when set to true, suppresses those warnings
|
The warning is a false positive. The clang-tidy docs for the warning you got say:
The check takes assignment of fields in the constructor body into account but generates false positives for fields initialized in methods invoked in the constructor body.
https://releases.llvm.org/10.0.0/tools/clang/tools/extra/docs/clang-tidy/checks/cppcoreguidelines-pro-type-member-init.html
Seems like a poor check to me, but if you want to keep it enabled you might be able to suppress this one instance of it using the magic // NOLINT comment...somewhere?
|
73,672,215
| 73,692,450
|
Get user input with multple values formated with comma
|
I want to achive someting like this:
User input values here for example 1,2,3
Your values: 1,2,3 [1,2,3 is inputed by user in one line]
and this values are pushed to array.I need check here if number is not bigger than max number for example 4 and isnt below 1.
I came up with this code. It takes msg to show for user and max num,but as you can see it only can return single value and i have no idea how to modify it to work as i discribed it.
const int getMultipleIntAboveZero(const std::string &msg,int maxNum){
int num;
std::cout<< msg;
while(!(std::cin>>num)|| num < 1 || num > maxNum){
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout<<"\nInvalid input. Try again: ";
}
return num;
}
|
How can I get integer array inputted by user with commas?
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector< int > getMultipleIntAboveZero(std::string msg, int maxNum) {
std::istringstream iss (msg);
std::string unit;
std::vector<int> nums;
int num;
while(std::getline(iss, unit, ',')) {
num = std::stoi(unit);
if (num >= 1 && num <= maxNum) {
std::cout << num << '\n';
nums.push_back(num);
} else {
std::cout<<"Invalid input. Try again\n";
}
}
return nums;
}
int main()
{
printf("Your values: ");
std::string msg;
std::cin >> msg;
getMultipleIntAboveZero(msg, 4);
}
|
73,673,455
| 73,673,506
|
Put an array in the end of another array C++
|
Normally it's a question about a buffer with a null-terminated string, but we can extrapolate it to a general case.
I have a big array of a fixed length, let's say 10:
char outputArray[10] = {'-','-','-','-','-','-','-','-','-','-'};
And I have some other (Edited: smaller) array (in my case it's a char buffer with null terminator) with a variable length. Let's say it's a buffer of 6 elements, but the actual length is indicated by another variable.
char inputArray[10] = {'h','i','/0',...some other values, i'm not interested in};
int arrLength = 2; // For my task it means a strlen(inputArray);
How to put a small array at the end of a big array, to get this:
outputArray = {'-','-','-','-','-','-','-','-','h','i'} // the null terminator isn't important, it's not about the strings, it's about arrays.
Constraints:
I can't use std, so only "native" solutions (it's for Arduino)
C++11
Code should be memory and time efficient (some elegant algorithm without too much loops and too much temporary variables or calculations please)
Thank you in advance
Edited:
Thank to @ThomasWeller for an answer. I have a small precision though. What if I need to clean all the elements before the inserted array?
For example I had some garbage
{'a','k','$','-','n','"','4','i','*','%'};
And I need to get
{'-','-','-','-','-','-','-','-','h','i'};
Do I need 2 loops? First to reset an array and the second one to set the actual result?
|
It can be done with a single for loop and a single variable:
for (char i=0; i<arrLength; i++)
{
outputArray[10-arrLength+i] = inputArray[i];
}
If you make arrLength a char instead of an int, this will even save you 2 bytes of memory ;-)
Use memset() to set all memory to an initial value and then memcpy() the contents at the end:
char output[10];
char input[10] = "hi\0------";
char arrLength = 2;
void setup() {
memset(output, '-', 10); // "----------"
memcpy(output+10-arrLength, input, arrLength);
Serial.begin(9600);
Serial.write(output, 10);
}
void loop() { }
|
73,674,436
| 73,700,701
|
EspHome custom component
|
i have a probleme with custom code in esphome..
There is the error :
src/screen.h:23:59: error: cannot convert 'MyCustomComponent::MyCustomComponent(esphome::template_::TemplateNumber*&, esphome::template_::TemplateNumber*&, esphome::template_::TemplateNumber*&, esphome::homeassistant::HomeassistantTextSensor*&)::<lambda(String)>' to 'std::function<void(std::__cxx11::basic_string<char>)>'
23 | { str = str_n; });
| ^
and the code :
MyCustomComponent(esphome::template_::TemplateNumber *&_led_r,esphome::template_::TemplateNumber *&_led_g,esphome::template_::TemplateNumber *&_led_b,esphome::homeassistant::HomeassistantTextSensor *&_str)
{
_led_r->add_on_state_callback([this](float led_r_n)
{ led_r = led_r_n; });
_led_g->add_on_state_callback([this](float led_g_n)
{ led_g = led_g_n; });
_led_b->add_on_state_callback([this](float led_b_n)
{ led_b = led_b_n; });
_str->add_on_state_callback([this](String str_n)
{ str = str_n; });
}
I'm really lost..
thank you in advance
EDIT :
here is my code :
here is my code, in case I specify that I run this on a HomeAssistant instance with EspHome in version 2022.8.3
#include "esphome.h"
#include <Wire.h>
#include "rgb_lcd.h"
class MyCustomComponent : public Component, public CustomAPIDevice {
public:
rgb_lcd lcd;
bool enable = false;
int led_r = 0;
int led_g = 0;
int led_b = 0;
String str = "ff";
MyCustomComponent(esphome::template_::TemplateNumber *&_led_r,esphome::template_::TemplateNumber *&_led_g,esphome::template_::TemplateNumber *&_led_b,esphome::homeassistant::HomeassistantTextSensor *&_str)
{
_led_r->add_on_state_callback([this](float led_r_n)
{ led_r = led_r_n; });
_led_g->add_on_state_callback([this](float led_g_n)
{ led_g = led_g_n; });
_led_b->add_on_state_callback([this](float led_b_n)
{ led_b = led_b_n; });
_str->add_on_state_callback([this](String str_n)
{ str = str_n; });
}
void setup() override {
lcd.begin(16, 2);
}
void loop() override
{
lcd.setRGB(led_r,led_g,led_b);
}
|
As shown here
void esphome::text_sensor::TextSensor::add_on_state_callback(std::function< void(std::string)>callback)
You should use std::string instead of String (Arduino string), those are incompatible.
I'm not sure what you're going to do with String str = "ff"; but In case you still want to use Arduino String, you should be able to use like
_str->add_on_state_callback([this](std::string str_n)
{ str = String(str_n); });
|
73,674,935
| 73,675,091
|
Can I add main function in C++ header file?
|
Hi guys I have a vehicule.h header file like this
#include <iostream>
using namespace std;
class Vehicule{
private:
string type;
//etc...
};
//can this function be there or do i need to add it on .cpp file?
int main(){
return 0;
}
|
Technically yes, you can. However, if you do put a non-inline function definition such as main into a header, then you may only include the header into one translation unit. This makes the header rather pointless. In conclusion, don't do it because it isn't useful.
|
73,675,285
| 73,675,448
|
Active Qt - add member to Outlook distribution list
|
I'm trying to use Active Qt to modify a distribution list in Outlook. I'm able to access it and list all of its members with the following code:
QAxObject* outlook = new QAxObject("Outlook.Application");
QAxObject* session = outlook->querySubObject("Session");
QAxObject* contactsFolder = session->querySubObject("GetDefaultFolder(olFolderContacts)");
QAxObject* distList = contactsFolder->querySubObject("Items(QString)", "My contact list");
int memberCount = distList->property("MemberCount").toInt();
QAxObject* member;
for (int i = 1; i <= memberCount; i++) {
member = distList->querySubObject("GetMember(int)", i);
qDebug() << member->property("Name").toString() << " "
<< member->property("Address").toString();
delete member;
}
But when I'm trying to add a member to the list:
QAxObject* newQaxMember = session->querySubObject("CreateRecipient(QString)", "Name LastName");
IDispatch* newMember = 0;
newQaxMember->queryInterface(QUuid("00020400-0000-0000-C000-000000000046"), (void**)&newMember);
distList->querySubObject("AddMember(IDispatch*)", QVariant::fromValue(newMember));
I'm getting an error:
QAxBase::querySubObject: AddMember(IDispatch*): Error calling function or property in ({0006103C-0000-0000-C000-000000000046})
When I use dynamicCall() method instead of querySubObject(), there's no error, but also no new member appear on the list in Outlook.
What am I doing wrong?
|
Use the Resolve method right after a new recipient is created. The method attempts to resolve a Recipient object against the Address Book. And if the recipient is resolved (see the corresponding property) you may call the DistListItem.AddMember method to add a new member to the distribution list in Outlook. Here is how it looks in VBA:
Sub AddNewMember()
'Adds a member to a new distribution list
Dim objItem As Outlook.DistListItem
Dim objMail As Outlook.MailItem
Dim objRcpnt As Outlook.Recipient
Set objMail = Application.CreateItem(olMailItem)
Set objItem = Application.CreateItem(olDistributionListItem)
'Create recipient for distlist
Set objRcpnt = Application.Session.CreateRecipient("Eugene Astafiev")
objRcpnt.Resolve
objItem.AddMember objRcpnt
'Add note to list and display
objItem.DLName = "Northwest Sales Manager"
objItem.Body = "Regional Sales Manager - NorthWest"
objItem.Save
objItem.Display
End Sub
|
73,675,349
| 73,675,371
|
C++. What's the best way to initialize multiple static variables in a templated class?
|
There are class with multiple static variables, e.g.
template<class T>
struct A
{
// some code...
static int i;
static short s;
static float f;
static double d;
// other static variables
};
The main way is to use the full template name
template<typename T>
int A<T>::i = 0;
template<typename T>
short A<T>::s = 0;
template<typename T>
float A<T>::f = 0.;
template<typename T>
double A<T>::d = 0.;
// other inits of static variables
this solution contains a lot of the same code (template<typename T> and A<T>)
And if the template has several types, this leads to increase this code, e.g.
struct B<T1, T2, T3, T4>
{
// some code
static int i;
//other static variables
};
...
template<typename T1, typename T2, typename T3, typename T4>
int B<T1, T2, T3, T4>::i = 0;
//other static variable
It looks ok for 1-2 static variables, but if you need more it looks terrible
I think about using macros, something like this
#define AStaticInit(TYPE) template<typename T> TYPE A<T>
AStaticInit(int)::i = 0;
AStaticInit(short)::s = 0;
AStaticInit(float)::f = 0.;
AStaticInit(double)::d = 0.;
// other inits of static variables
#undef TArray
But perhaps there are better options for initializing several static variables in a template class with minimum code?
|
Make them inline to be able to give them initializers:
template<class T>
struct A
{
// some code...
inline static int i = 0;
inline static short s = 0;
inline static float f = 0.f;
inline static double d = 0.;
// other static variables
};
|
73,675,368
| 73,675,380
|
Calling overrided method on Derived class casted from void ptr causes segmentation fault
|
Calling overrided method on Derived class casted from void ptr causes segmentation fault.
It doesn't if derive from concrete (non abstract) class.
#include <cstdio>
struct Base{
virtual void base_method() = 0;
};
struct Derived : Base{
int x;
void own_method(){
printf("own %d", x);
}
void base_method() override{
printf("base %d", x);
}
};
int main() {
auto * char_ptr = new char[500];
void * void_ptr = char_ptr;
auto derived_ptr = (Derived*)void_ptr;
derived_ptr->x = 15;
derived_ptr->own_method();
// derived_ptr->base_method(); SEGMENTATION ERROR IF UNCOMMENT
return 0;
}
|
You didn't run the constructor of Derived, so your code has UB. In case of ItaniumABI, your virtual table is not populated and thus you're likely jumping to an undefined address. If you'd like to use the char array / void* as the memory for Derived, you can do placement new:
#include <new>
auto derived_ptr = new(void_ptr)Derived;
|
73,675,476
| 73,677,441
|
Window background visible through textures
|
What can I try to solve this problem? In this example (see a screenshot below) I am using OpenGL 1.1 with deprecated functions like: glEnableClientState, glMatrixMode, glTexCoordPointer, and so on. Thanks in advance.
You can see the whole example code in this thread: https://community.khronos.org/t/window-background-visible-through-textures/109061
I draw with DEPTH_TEST:
glEnable(GL_DEPTH_TEST);
/* ... */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Player
glBindTexture(GL_TEXTURE_2D, spriteTexture);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(playerBody->GetPosition().x * WORLD_SCALE,
playerBody->GetPosition().y * WORLD_SCALE, 10.f);
glScalef(16.f, 16.f, 1.f);
glDrawArrays(GL_TRIANGLE_STRIP, drawingIndex, 4);
// Coin
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(178.f, 120.f, 10.f);
glScalef(16.f, 16.f, 1.f);
glDrawArrays(GL_TRIANGLE_STRIP, 24, 4);
// Enemy
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(194.f, 184.f, 10.f);
glScalef(16.f, 16.f, 1.f);
glDrawArrays(GL_TRIANGLE_STRIP, 20, 4);
// Background
glBindTexture(GL_TEXTURE_2D, backgroundTexture);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, 0.f);
glScalef(256.f, 216.f, 1.f);
glDrawArrays(GL_TRIANGLE_STRIP, 16, 4);
glfwSwapBuffers(window);
Texture:
Various window background values to show that I have an alpha channel:
For glClearColor(1.f, 0.f, 0.f, 1.f);
For glClearColor(0.2f, 0.5f, 0.3f, 1.f);
My Settings:
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
GLuint createTexture(char *path)
{
int h_image, w_image, cnt;
unsigned char *data = stbi_load(path, &w_image, &h_image, &cnt, 0);
if (data == NULL)
{
cout << "Failed to load an image" << endl;
glfwTerminate();
exit(-1);
}
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w_image, h_image, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
}
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(data);
return texture;
}
|
Transparency is achieved with the alpha channel and Blending only works when the textures have an alpha channel. When the alpha channel of the transparent background is 0.0 and the alpha channel of the object is 1.0 then you can use the following blending function:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
How can the objects be blended with the background if there is no background? You have to draw the background before you draw the objects and you don't nee the depth test at all. You must draw the object after the background. Using the depth test, fragments are discarded before they can be blended. You have to disable the depth test and draw the objects backt to front.
To render the scene you have to
disable blending and disable the depth test
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
draw the background
enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
draw the objects in the scene
|
73,675,612
| 73,676,371
|
Why I got syntax error, when trying to use concept?
|
I am using Visual Studio 2022, with the latest compiler. I have a problem, when I am trying to create concept definition. I got many syntax error, for example
syntax error: identifier 'has_type_member'
syntax error: missing ';' before '{'
template<typename T>
concept has_type_member = requires { typename T::type; };
I have tried many other basic examples about concepts.
Thanks for your help!
|
In Visual Studio 2022, ISO C++ 14 Standard in enabled by default. Concept feature is available since C++20.
To enable ISO C++20 standard for your project, right click on the project name and select Properties, under Configuration Properties -> General -> C++ Language Standard select ISO C++20 Standard (/stdc++20).
|
73,675,691
| 73,675,716
|
Change Include Path of Interface library
|
I have just created an interface library called "foo". Now I would like to include each of the modules of foo like this:
#include "foo/module.h"
Right now, I always have to write the include path as following
#include "foo/include/module.h"
Is it somehow possible to tell Cmake to ignore the "include" within the path? My CMakelists.txt of the Interface lib foo looks like this:
add_library(foo INTERFACE)
target_include_directories(foo INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
An the main CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.22.1)
project(project)
add_executable(${PROJECT_NAME} main.cpp)
add_subdirectory(foo)
target_link_libraries(${PROJECT_NAME} foo)
What am I doing wrong? Is there anyone who can help me with this?
Thank you very much in advance!
Best regards,
Simon
|
Is it somehow possible to tell Cmake to ignore the "include" within the path?
That's not CMake's job. CMake is a build system that hands off the work of actually compiling the C++ text to the compiler and linker. CMake provides command line parameters and tracks which files need to be compiled, but it doesn't deal in how exactly the compiler parses a #include directive. It can affect that through command-line switches, but only to the extent that compilers permit it.
While every compiler allows users to define a set of directories to look in when processing include directives, to my knowledge, none of them will insert said directory text into the middle of the include string.
Most libraries that deliver headers will have them in an include or inc directory. When building code that links to this library, the path to that directory will be given as one of the include paths. Within that directory, they will usually have a library_name directory, and it is within that directory where the actual headers are.
That is, it's supposed to be "include/foo/module.h", which you would include with #include "foo/module.h".
|
73,675,909
| 73,675,916
|
Bottom coordinates of CListBox is not set correctly
|
MFC beginner question.
I created a listbox and a button using CListBox::Create and CButton::Create respectively, using CRect for their size and location.
The two CRect has the same height, but when they are shown in the screen, the height of the listbox is shorter than that of the button.
I checked the pixel coordinate using a mouse click event handler OnLButtonDown, and noticed that the size and location of the button are correct. The bottom coordinate of the CListBox is not correct. Why is this happening?
The option I used to create the listbox was WS_CHILD | WS_VISIBLE | LBS_STANDARD, and used WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON for the button. I tried removing the LBS_STANDARD, but still the height was not changed.
The MSDN on CListBox::Create just describes this:
rect
Specifies the list-box size and position. Can be either a CRect object or a RECT structure.
Is there something I missed?
|
Add the LBS_NOINTEGRALHEIGHT style:
Specifies that the size of the list box is exactly the size specified by the application when it created the list box. Normally, the system sizes a list box so that the list box does not display partial items.
|
73,677,437
| 73,677,487
|
How to use SFML without errors?
|
My code for Text_Box.cpp is:
#include <SFML/Graphics.hpp>
int main1() {
sf::RenderWindow window(sf::VideoMode(800, 600), "Window",
sf::Style::Titlebar | sf::Style::Close);
sf::Font arial;
arial.loadFromFile("arial.ttf");
sf::Text t;
t.setFillColor(sf::Color::White);
t.setFont(arial);
std::string s = "This is text that you type: ";
t.setString(s);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if (event.type == sf::Event::TextEntered) {
if (event.text.unicode < 128) {
s += static_cast<char>(event.text.unicode);
}
else {
// Time to consider sf::String or some other unicode-capable string
}
}
}
t.setString(s);
window.clear(sf::Color::Black);
window.draw(t);
window.display();
}
return 0;
}
I copied this above code to learn by changing commands from it.
I am including it in my main file of c that is, main.c and using it at the very beginning of main function. My main.c code is:
#include <stdio.h>
#include "Text_Box.cpp"
int main() {
main1();
return 0;
}
but it is giving several errors like:
Severity Code Description Project File Line Suppression State
Error C4233 nonstandard extension used: '__is_final' keyword only supported in C++, not C Project1 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\type_traits 543
Severity Code Description Project File Line Suppression State
Error C4233 nonstandard extension used: '__is_trivially_constructible' keyword only supported in C++, not C Project1 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\type_traits 741
etc.
I am using visual studio 2019.
How can it be fixed? Is there something I am doing wrong? I have a doubt that do I need to compile SFML on my own as I am using visual studio 2019?
EDIT:
I tried without main.c file, renaming main1 to main and after adding additional dependencies, it is giving errors on executing:
sfml-graphic-d-2.dll not found,
sfml-window-d-2.dll not found,
sfml-system-d-2.dll not found.
It also says reinstalling may fix this. So do I need to compile sfml as website of sfml mentions this?
|
The compiler needs to specify (in the project settings)
/Zc:__cplusplus
Never do it bellow. Remove main.c and rename main1 to main.
main.c
#include <stdio.h>
#include "Text_Box.cpp"
int main() {
main1();
return 0;
}
|
73,677,576
| 73,677,707
|
Visual Studio: two little projects with identical "Command Lines" but one cannot find the headers?
|
I have a solution with two one-source-file projects in it. Each file is:
#include <mosquitto.h>
The first compiles fine. The second says it cannot find a header. The source code in the second is identical to the first, so it is a mystery why it cannot compile.
Pre-compiled headers are not being used in either, so it is curious that the /Fp option is issued, I don't see how it can be playing a role.
/permissive- /ifcOutput "x64\Release\" /GS /GL /W3 /Gy /Zc:wchar_t /I"C:\Program Files\mosquitto2.0.14\devel" /Zi /Gm- /Od /sdl /Fd"x64\Release\vc143.pdb" /Zc:inline /fp:precise /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oi /MD /FC /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Fp"x64\Release\Good.pch" /diagnostics:column
/permissive- /ifcOutput "x64\Release\" /GS /GL /W3 /Gy /Zc:wchar_t /I"C:\Program Files\mosquitto2.0.14\devel" /Zi /Gm- /O2 /sdl /Fd"x64\Release\vc143.pdb" /Zc:inline /fp:precise /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oi /MD /FC /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Fp"x64\Release\Bad.pch" /diagnostics:column
Another user suggests posting the actual failed output.
Build started...
1>------ Build started: Project: Bad, Configuration: Debug x64 ------
1>Bad.cpp
1>T:\MyFirm\dev\MinorProjects\Bad\Bad.cpp(55,10): fatal error C1083: Cannot open include file: 'mosquitto.h': No such file or directory
1>Done building project "Bad.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
|
I turned on Tools->Options->Projects and Solutions->Build and Run->verbosity=Detailed, and compared the CL.exe commands issued.
To my surprise, the /I include option was NOT present on the failed build command, despite being in the Properties dialog "Command Line" page as pasted above.
The issue was that I was building in Debug, but for some reason the Properties dialog was editing Release options. So, while the "Command Line" page was showing the options that would be used were I building Release, they weren't used while building Debug.
|
73,677,991
| 73,678,042
|
I want to take inputs of 2d vector using ranged based for loop. How can i do?
|
As a beginner i am exploring multiple methods to increase my clarity, so i did this question.
// no problem with this looping method
vector <vector<int>> vec(n,vector<int>(m));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> vec[i][j];
}
}
// but i tried in this way using ranged based loop, and it doesn't work.
// I think i need a few modification here, so i need your help.
for(vector<int> v1d : vec){
for(int x : v1d){
cin >> x;
}
}
Same code, just cin replaced by cout, i can print that vector elements easily.
but in case of cin i am having problem.
no error, but it's not working.
Thanks
|
You need to take the values by reference in the range base for-loops. Otherwise v1d and x will be copies and any changes you make to those copies will not be affecting the content of vec in any way.
for(auto& v1d : vec) { // or: std::vector<int>& v1d
// ^
for(auto& x : v1d) { // or: int& x
// ^
std::cin >> x;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.