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 |
|---|---|---|---|---|
72,647,311 | 72,648,533 | Template function with multiple parameters of same type | I'm trying to create a function that can take multiple parameters of the same type, passed in as a template. The number of arguments is known in compile time:
struct Foo
{
int a, b, c;
};
template <uint32_t argsCount, typename T>
void fun(T ...args) // max number of args == argsCount
{
// ...
// std::array<T, argsCount>{ args... };
}
int main()
{
fun<3, Foo>( { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } );
// Dont want to do:
// fun( Foo{}, Foo{}, Foo{} );
// nor:
// fun<Foo, Foo, Foo>( ... );
return 0;
}
I must take into consideration these constraints:
no heap memory allocations
no va_args
Is it possible to do something similar in C++14 (preferably C++14, but curious what are the solutions in newer versions)?
edit: cleaned up the initial sloppy pseudcode.
| If you change the function into a functor, you can introduce a parameter pack in the body of the type of the functor.
First create a helper to turn <N, T> -> std::tuple<T, T, T, ..., T> (N times):
template<std::size_t N, typename T>
struct repeat {
private:
// enable_if<true, T> == type_identity<T>
template<std::size_t... I>
static std::enable_if<true, std::tuple<std::enable_if_t<I==I, T>...>>
get(std::index_sequence<I...>);
public:
using type = typename decltype(get(std::make_index_sequence<N>{}))::type;
};
Then have your functor take a std::tuple<Args...>, where Args will be a parameter pack with T N times:
template<typename T, typename Args>
struct fun_t;
template<typename T, typename... Args>
struct fun_t<T, std::tuple<Args...>> {
static constexpr std::size_t argsCount = sizeof...(Args);
void operator()(Args... args) const {
// ...
// std::array<T, argsCount>{ args... };
}
};
template<std::uint32_t argCount, typename T>
constexpr fun_t<T, typename repeat<argCount, T>::type> fun;
int main() {
fun<3, Foo>({ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 });
}
|
72,647,450 | 72,649,109 | Sending an email using curl c++ | Im trying to send an email using curl c++, i managed to log in well and when i run the program it works fine, does not throw any error, but the email never comes.
This is my code:
#include <iostream>
#include <curl/curl.h>
static const char *payload_text =
"Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n"
"To: " "mailto" "\r\n"
"From: " "mymail" "\r\n"
"Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@"
"rfcpedant.example.org>\r\n"
"Subject: SMTP example message\r\n"
"\r\n" /* empty line to divide headers from body, see RFC5322 */
"The body of the message starts here.\r\n"
"\r\n"
"It could be a lot of lines, could be MIME encoded, whatever.\r\n"
"Check RFC5322.\r\n";
size_t read_function(char *buffer, size_t size, size_t nmemb,char *data)
{
size_t len;
if(size == 0 or nmemb == 0)
{
return 0;
}
if(data)
{
len = strlen(data);
memcpy(buffer, data, len);
return len;
}
return 0;
}
int main()
{
CURL *curl;
CURLcode res = CURLE_OK;
const char *data = payload_text;
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_USERNAME, "mymail");
curl_easy_setopt(curl, CURLOPT_PASSWORD, "password");
curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587");
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, "my mail");
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, "mailto");
curl_easy_setopt(curl, CURLOPT_READDATA,payload_text);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_function);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
}
res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
return 0;
}
I think the problem is in the curl options READDATA and READUNCTION.
In the documentation says that you have to pass as an argument to READDATA a data pointer.
const char *data = payload_text; is the data pointer, right?
then READFUNCTION takes as an argument a function which return the size of the data and i think that is what size_t read_function(char *buffer, size_t size, size_t nmemb,char *data) is doing.
I am new in this so any advice would be good for me.
| I found this to be a helpful starting point:
https://curl.se/libcurl/c/smtp-mail.html
There are two main problems with your code:
Your read_function didn't keep track of how much of the payload has been read so it would keep giving the same content to libcurl over and over and never signal the end of the message.
You were setting CURLOPT_MAIL_RCPT to a string when in fact it should be a struct curl_slist * because there can be multiple recipients.
Here is a fixed example that I tested on my computer and it worked. Private data at the top of the file was modified before posting.
#define USERNAME "david"
#define PASSWORD "xxxxx"
#define MAILTO "david@example.com"
#define MAILFROM "you@example.com"
#define SMTP "smtp://your.smtp.server.example.com:25"
#include <stdio.h>
#include <curl/curl.h>
const char * payload_text =
"Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n"
"To: " MAILTO "\r\n"
"From: " MAILFROM "\r\n"
"Subject: SMTP example message with libcurl 6\r\n"
"\r\n"
"Hello world!\r\n";
struct ReadData
{
explicit ReadData(const char * str)
{
source = str;
size = strlen(str);
}
const char * source;
size_t size;
};
size_t read_function(char * buffer, size_t size, size_t nitems, ReadData * data)
{
size_t len = size * nitems;
if (len > data->size) { len = data->size; }
memcpy(buffer, data->source, len);
data->source += len;
data->size -= len;
return len;
}
int main()
{
CURL * curl = curl_easy_init();
if (!curl)
{
fprintf(stderr, "curl_easy_init failed\n");
return 1;
}
curl_easy_setopt(curl, CURLOPT_USERNAME, USERNAME);
curl_easy_setopt(curl, CURLOPT_PASSWORD, PASSWORD);
curl_easy_setopt(curl, CURLOPT_URL, SMTP);
curl_easy_setopt(curl, CURLOPT_MAIL_FROM, MAILFROM);
struct curl_slist * rcpt = NULL;
rcpt = curl_slist_append(rcpt, MAILTO);
curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, rcpt);
ReadData data(payload_text);
curl_easy_setopt(curl, CURLOPT_READDATA, &data);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_function);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
// If your server doesn't have a proper SSL certificate:
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
return 0;
}
|
72,647,540 | 72,647,770 | Cuda AtomicAdd for int3 | In Cuda AtomicAdd for double can be implemented using a while loop and AtomicCAS operation.
But how could I implement an atomic add for type int3 efficiently?
| After further consideration, I'm not sure how an atomicAdd on an int3 would be any different than 3 separate atomicAdd operations, each on an int location. Why not do that?
(An int3 cannot be loaded as a single quantity anyway in CUDA at the machine level. The compiler is guaranteed to split that into multiple loads, so although there would be a hazard to asynchronously read the int3, that hazard would be there anyway, with or without atomics.)
But to answer the specific question you asked, it's not possible using atomics.
int3 is a 96-bit type.
CUDA atomics support operations up to 64 bits only. Here is an atomic add example for float2 (a 64-bit type) and you could do something similar for up to e.g. short3 or short4.
You could alternatively use a reduction method or else a critical section. There are plenty of questions here on the SO cuda tag that discuss reductions and critical sections.
A reduction method could be implemented as follows:
Each thread that wants to make an atomic update to a particular int3 location uses this method to create a queue or list of the atomic update quantities.
Once the list generation is complete, launch a kernel to do a parallel reduction on the list, so as to produce the final reduced quantity that belongs in that location.
|
72,649,616 | 72,650,893 | Why do I get an undefined reference although everything seems alright ? (C++ Mingw) | My problem is fairly trivial and simple, I am trying to write a packer and to do so I need to parse PE files, so I'm trying to use the C++ pe-parse library.
I built it following the instructions and I'm now trying to link it to my simple main.cpp file:
#include <pe-parse/parse.h>
int main(int ac, char **av)
{
peparse::parsed_pe *p = peparse::ParsePEFromFile(av[0]);
return 0;
}
Here is my file structure:
.
βββ src
β main.cpp
βββ lib
β pe-parse.lib
βββ bin
β pe-parse.dll
βββ include
β pe-parse
nt-headers.h
parse.h
to_string.h
MinGW is indeed x64 (x86_64-w64-mingw32) and my libraries also (pei-x86-64 for both pe-parse.dll and pe-parse.lib)
When I run
g++ -Wall -Wextra .\src\main.cpp -I.\include\ -L.\bin\ -lpe-parse
from root, I get the following linking error:
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe:
C:\Users\gz\AppData\Local\Temp\ccxml3rK.o:packer.cpp:(.text+0x1f): undefined reference to `peparse::ParsePEFromFile(char const*)'
collect2.exe: error: ld returned 1 exit status
When I run nm on pe-parse.lib I am able to find the symbol. pe-parse.dll does not contain any, and I tried to to replace -L.\bin\ with -L.\lib\
Any ideas ? I believe the .lib is an import library that has to be linked with the .dll, but I can't find a way to.
Thank you.
| You have a library produced by MSVC and you are trying to use g++ to link with it.
Microsoft C++ compiler is not compatible with g++. Objects produced by one of them cannot use objects compiled by the other. They use vastly different ABIs and different standard library implementations.
Your only option is to recompile everything with one compiler.
|
72,649,753 | 72,650,835 | How to break circular dependency between exe and dll | A C++ app has this exe/dll layout:
Main.exe, Framework.dll, PluginA.dll, PluginB.dll, ..., PluginN.dll
Both Main.exe and Framework.dLL provide functions to the Plugin#.dll.
The Plugins are depedent on Main.exe and Framework.dll, but not the other way around.
Framework.dll depends on functions provided by Main.exe
Now, the problem is that there is a circular dependency between Main.exe and Framework.dll
because Main.exe depends on 1 class in Framework.dll that it uses to
manage the lifecycle of Framework.dll
So, in Main.exe, it would be something like this:
#include "Framework.hpp"
int main() {
Framework fw;
fw.Init();
while (Quit() == false) {
fw.Begin();
DoWork();
fw.End();
MoreWork();
}
fw.Shutdown();
return 0;
}
So, Main.exe depends on only 1 class from Framework.dll, but that's enough to
create their circular dependency.
Is there a way to still use that one Framework class from Main.exe while still breaking
the circular dependency? Specifically, so that Main.exe doesn't require the export library Framework.lib to build.
| The usual solution to this (although it's usually used when two libraries have a circular dependency) is to create a 'dummy' version of one of them that defines all the relevant entry points but is not in any way dependent on the other and doesn't need to link against it. That can then be used as a kind of 'bootstrap'.
So in your case, you might create yourself a dummy_framework.cpp file that you can build to provide a framework.lib that main can then link against. Once you've done that, you can compile the 'real' framework to generate the 'real' framework.dll and you should then have a fully functional version of your app. (You can rebuild main if you want, but there shouldn't actually be any need.)
This is all perfectly viable so long as the API of framework is reasonably stable, but even if it isn't, you'll get compiler or (more likely) linker errors when you try to build dummy_framework so you can update it then.
|
72,649,896 | 72,650,319 | Passing templated friend function of a class to other function as parameter results in error | The following code demonstrates the problem.
#include <functional>
namespace test {
template <class T>
class A {
public:
friend auto foo(const A& obj) { return 1; }
};
template <class Function, class... Args>
void bar(Function f, Args&&... args) {
const auto result = std::invoke(f, std::forward<Args>(args)...);
// do stuff with result
}
} // namespace test
auto main() -> int {
test::A<int> value;
test::bar(foo<int>, value); // results in compile time error
test::bar(test::foo<int>, value); // results in compile time error
return 0;
}
Here is the here link to compiler explorer
It probably has to do something with argument dependent lookup, but i cannot really get it.
| The problem is that the friend declaration for foo that you've provided is for a non-template function but while calling bar you're trying to use foo as a template.
There are 2 ways to solve this:
Method 1
Here we provide a separate parameter clause for foo.
namespace test
{
template <class T> class A {
public:
template<typename U> //separate parameter clause added here
friend auto foo(const A<U>& obj);
};
//definition
template<typename U>
auto foo(const A<U>& obj) { return 1; }
template <class Function, class... Args>
void bar(Function f, Args&&... args) {
const auto result = std::invoke(f, std::forward<Args>(args)...);
// do stuff with result
}
} // namespace test
auto main() -> int {
test::A<int> value;
test::bar(test::foo<int>, value); //works
return 0;
}
Working demo
Method 2
Here we provide a forward declarations for the function template foo and then define it later outside the class.
namespace test
{
//forward declarations
template <class T> class A;
template<typename TT> auto foo(const A<TT>& obj);
template <class T> class A {
public:
//friend declaration
friend auto foo<>(const A& obj);
//---------------------^^---------------->note the angle brackets
};
//definition
template<typename TT>
auto foo(const A<TT>& obj) { return 1; }
template <class Function, class... Args>
void bar(Function f, Args&&... args) {
const auto result = std::invoke(f, std::forward<Args>(args)...);
// do stuff with result
}
} // namespace test
auto main() -> int {
test::A<int> value;
test::bar(test::foo<int>, value); //works
return 0;
}
Working demo
|
72,650,120 | 72,663,851 | How to select tuple elements by certain condition on types | I want to apply certain functionality to some elements of a tuple based on a given condition or constraint of the types.
Below is a small dummy example where I want to call a callback function for all the elements in the tuple that holds an arithmetic type. In my current solution, I use std::apply and if constexpr on the type constraint as the condition to call the callback.
However, I assume this is iterating through all the elements of the tuple?
And now I am wondering if there is an alternative to do this. In my head, it should be possible to select the indices of the elements of interest at compile-time, because all the types are known and then apply the functionality only for the elements at those indices. But I don't know if this is possible, nor how to translate this to code.
#include <iostream>
#include <string>
#include <tuple>
#include <type_traits>
template <typename... Args>
struct Foo {
using my_tuple = std::tuple<Args...>;
template <typename Fn>
void CallForArithmetic(Fn&& fn) {
auto arithmetic_call = [&]<typename T>(const T& x) {
if constexpr (std::is_arithmetic_v<T>) {
fn(x);
}
};
std::apply([&](auto&&... arg) { (arithmetic_call(arg), ...); }, tuple_);
};
private:
my_tuple tuple_;
};
int main() {
Foo<int, std::string> foo{};
int calls = 0;
// will be called only once for int type
foo.CallForArithmetic(
[&calls](const auto& arg) { std::cout << calls++ << '\n'; });
}
| It's really "as if" you are iterating over the full tuple. In general, the compiled program will only do that if it has to, or if all optimisations are disabled, to aid debugging. And indeed, starting from -O1 (gcc) or -O2 (clang), a slightly simplified version of your code compiles to "return 1;":
main:
mov eax, 1
ret
Note: msvc finds the same result, but generates a lot of extra clutter.
So, as Jarod42 suggested, you can definitely expect your compiler to figure this out, and go with the solution that is easiest for you as a human. And if you're not sure, Compiler Explorer is a great tool for questions like yours.
|
72,650,435 | 72,650,522 | When GCC does not provide __cpp_lib_uncaught_exceptions feature? | Following piece of code does not work right on Alpine Linux:
#ifndef __cpp_lib_uncaught_exceptions
namespace std {
int uncaught_exceptions() noexcept {
return std::uncaught_exception();
}
}
#endif
Source
Error:
[ 89%] Linking CXX executable AdsLibTest.bin
/usr/lib/gcc/x86_64-alpine-linux-musl/11.2.1/../../../../x86_64-alpine-linux-musl/bin/ld: /usr/lib/gcc/x86_64-alpine-linux-musl/11.2.1/../../../../lib/libstdc++.a(eh_catch.o): in function `std::uncaught_exceptions()':
/home/buildozer/aports/main/gcc/src/gcc-11.2.1_git20220219/libstdc++-v3/libsupc++/eh_catch.cc:149: multiple definition of `std::uncaught_exceptions()'; CMakeFiles/AdsLibTest.bin.dir/main.cpp.o:main.cpp:(.text+0x8d0): first defined here
collect2: error: ld returned 1 exit status
make[2]: *** [_deps/ads-build/AdsLibTest/CMakeFiles/AdsLibTest.bin.dir/build.make:98: _deps/ads-build/AdsLibTest/AdsLibTest.bin] Error 1
It looks like GCC does not provide __cpp_lib_uncaught_exceptions feature. Why this could happen?
| Adding declarations to namespace std causes (with a few specific exceptions) undefined behavior. There is no reason that this should work, even if the compiler does correctly report that it doesn't provide std::uncaught_exceptions.
In particular, if the standard library implementation supported std::uncaught_exceptions and the file was compiled with language standard set to below C++17, then the feature test will claim that std::uncaught_exceptions is unsupported, but the standard library .a/.so may still provide the definition for it. This would cause a duplicate definition error.
As @ShadowRanger notes, there is also likely an inline missing on the function definition, because it may be included in multiple in multiple translation units.
Also, in order to use a feature test macro, it is necessary to include <version> (since C++20) or the header file corresponding to that features, e.g. in this case <exception>. Otherwise the macro is not defined and the feature check will always fail. It seems that the header is not including <exception>, but is including <stdexcept> though, which technically is not sufficient. However, practically, <stdexcept> is likely going to include <exception> and hence that would likely still work. For current libstdc++ this seems to be the case at least.
So, I would assume that your issue lies in the chosen compiler options, e.g. the language standard to compile for.
|
72,651,084 | 72,651,140 | Why does std::set work with my free function operator<, but not my class member function operator<? | If I use the free function operator <, my program works. If I use the implementation inside the class, I get a compiler error. Why doesn't implementing this as a class member function work?
Part of the error I get:
usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_function.h:386:20: error: invalid operands to binary expression ('const my' and 'const my')
{ return __x < __y; }
~~~ ^ ~~~
The code :
class my{
public:
int a;
double b;
my(int p){
a=p;
b=0;
}
bool operator> (const my other){
return this->a > other.a;
}
bool operator < (const my other) {
return this->a < other.a;
}
};
// bool operator < ( const my othe2,const my other) {
// return othe2.a < other.a;
// }
int main(){
set<my> s={10,5};
s.emplace(8);
s.emplace(-8);
for(auto t:s){
cout<<t.a<<",";
}
}
| They should be overloaded with const directive. Otherwise, the non const operators can't be applied to const my whatever a.k.a. std::set<my>::key_type whatever inside std::set. Add
bool operator> (const my& other) const {
return this->a > other.a;
}
bool operator < (const my& other) const {
return this->a < other.a;
}
Additionally other should be passed by reference const my& other.
|
72,652,032 | 72,663,030 | Attempting to do a T test with Rcpp using Boost: "No member named" errors | I am trying to make some statistical calculations in R faster by using Rcpp. First, I wrote the code in R. Then I wrote the code in C++ using Qt Creator, which required me to use the Boost package. Now, when I try to use sourceCpp() to compile a simple function that uses boost::math::statistics::two_sample_t_test(), I get
two errors--click here to see how it looks in RStudio.
/Library/Frameworks/R.framework/Versions/3.6/Resources/library/BH/include/boost/compute/algorithm/random_shuffle.hppno member named 'random_shuffle' in namespace 'std'; did you mean simply 'random_shuffle'?
~/Documents/Research/P-value correction project/Perm FDR with C++ using Rcpp/PermFDR_R/Rcpp.cppno member named 'two_sample_t_test' in namespace 'boost::math::statistics'
Here is a screenshot of the code in /Library/Frameworks/R.framework/Versions/3.6/Resources/library/BH/include/boost/compute/algorithm/random_shuffle.hpp that pops up when this happens.
Here is the R code.
library(Rcpp)
library(rstudioapi)
library(BH)
Sys.setenv("PKG_CXXFLAGS"="-std=c++17")
sourceCpp("Rcpp.cpp")
Here is the C++ code.
//[[Rcpp::depends(BH)]]
#include <Rcpp.h>
#include <vector>
#include <cmath>
#include <iostream>
#include <random>
#include <boost/math/statistics/t_test.hpp>
#include <boost/math/distributions/students_t.hpp>
#include <boost/math/tools/univariate_statistics.hpp>
#include <boost/compute/algorithm/random_shuffle.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <iomanip>
#include <numeric>
#include <random>
//[[Rcpp::plugins(cpp17)]]
using namespace std;
#include <Rcpp.h>
using namespace Rcpp;
/*
* Performs a T test on the measurements according to the design (1s and 2s)
* and returns a P value.
*/
double designTTest(vector<double> ints, vector<int> design) {
if (ints.size() != design.size()) {
cout << "ERROR: DESIGN VECTOR AND MEASUREMENT VECTOR NOT EQUAL IN LENGTH!";
throw;
}
vector<double> cIntensities;
vector<double> tIntensities;
for (int i = 0; i < design.size(); i++) {
if (design[i] == 1) {
cIntensities.push_back(ints[i]);
} else if (design[i] == 2) {
tIntensities.push_back(ints[i]);
} else {
cout << "ERROR: DESIGN SYMBOL IS NOT 1 OR 2!";
throw;
}
}
auto [t, p] = boost::math::statistics::two_sample_t_test(cIntensities, tIntensities);
return p;
}
// [[Rcpp::export]]
double ttestC(NumericVector ints, NumericVector design) {
vector<double> intVec = as<std::vector<double>>(ints);
vector<int> designVec = as<std::vector<int>>(design);
return designTTest(intVec, designVec);
}
Thank you!!
| There is a lot going on in your question, and I am not sure I understand all of (the 'design sorting' is very unclear).
I can, however, help you with the mechanics of Rcpp, and use of Boost via BH. I can suggest a number of changes:
you do not need to specify either C++11 or C++17; R already defaults to C++14 (if the compiler supports it) under recent version (Edit: We re-add C++17 to ensure structured bindings work)
you do not need all those headers: we need one for Rcpp, and one for Boost
I recommend against using namespace ... and suggest explicit naming
you do not need a wrapper from R vectors to std::vector<...> as Rcpp does that for you
I simplified the error reporting via Rcpp::stop()
With all that, plus a mini-demo to run the function, your code becomes simpler and short.
Code
// [[Rcpp::depends(BH)]]
// [[Rcpp::plugins(cpp17)]]
#include <Rcpp.h>
#include <boost/math/statistics/t_test.hpp>
// Performs a T test on the measurements according to the design (1s and 2s)
// and returns a P value.
// [[Rcpp::export]]
double designTTest(std::vector<double> ints, std::vector<double> design) {
if (ints.size() != design.size()) Rcpp::stop("ERROR: DESIGN VECTOR AND MEASUREMENT VECTOR NOT EQUAL IN LENGTH!");
std::vector<double> cIntensities, tIntensities;
for (size_t i = 0; i < design.size(); i++) {
if (design[i] == 1) {
cIntensities.push_back(ints[i]);
} else if (design[i] == 2) {
tIntensities.push_back(ints[i]);
} else {
Rcpp::stop("ERROR: DESIGN SYMBOL IS NOT 1 OR 2!");
}
}
auto [t, p] = boost::math::statistics::two_sample_t_test(cIntensities, tIntensities);
return p;
}
/*** R
designTTest(c(1,2,1,2,1), c(2,1,2,1,2))
*/
We can source this for compilation and the example (with possibly non-sensical data).
Output
> Rcpp::sourceCpp("~/git/stackoverflow/72652032/answer.cpp")
> designTTest(c(1,2,1,2,1), c(2,1,2,1,2))
[1] 0
>
I removed a bunch of compilation noise that goes away when you add -Wno-parentheses to your CXXFLAGS in ~/.R/Makevars. CRAN does not let me (as BH maintainer) keep th upstream #pragmas so noisy it is ...
|
72,652,379 | 72,652,802 | Which C++/Java graphics library does React Native use? | Since Flutter is using Skia for graphics, I was wondering what the equivalent for that would be for React Native.
I managed to find an android.graphics.Canvas class in the React Native source code but that's about it. Finding it a bit harder to wrap my head around the React Native engine as opposed to the Flutter engine.
| Contrary to Flutter, React Native doesn't render native UI elements on its own.
View and Text, which are building blocks for React Native UI alter the corresponding OS UI elements, and rendering is handled by Native code via React Native Bridge.
This architecture makes React Native not suitable for graphic-intensive apps like drawing or games.
Sponsored by Shopify, William Candillon and Christian Falch are bringing Skia to React Native - https://shopify.github.io/react-native-skia/
|
72,652,813 | 72,653,928 | How to use extern for declaring/defining global variable in C++ and CUDA | I have the following code structure composed of one .cpp, one .cu and one .hxx
UTILITIES.hxx
#ifndef UTILITIES_HXX
#define UTILITIES_HXX
namespace B{
extern int doors;
}
FILE2.cu
#include "utilities.hxx"
namespace A {
int foo (){
switch(B::doors){
//do something
}
}
}
FILE3.cxx
#include "utilities.hxx"
namespace B{
int doors=-1;
class Vehicle{
public:
void operation() {
doors++;
A::foo();
doors++;
A::foo();
}
}
}
I am declaring the doors variable as extern in the header and I am defining it in the .cxx file. So after that, the second .cpp should be able to use it. However I am getting the following error when linking:
/usr/bin/ld: ../src/libapp.a(FILE2.cu.o): in function A::foo(void)': /MYPATH/FILE2.cu:19: undefined reference to B::doors'
What am I doing wrong? Actually the foo function in the FILE2.cu is a normal C++ function, no CUDA involved at all.
| missing #endif, missing return statement, no prototype for A::foo(), missing semicolon
These changes seem to work for me:
$ cat utilities.hxx
#ifndef UTILITIES_HXX
#define UTILITIES_HXX
namespace B{
extern int doors;
}
#endif
$ cat file2.h
namespace A {
int foo ();
}
$ cat file2.cu
#include "utilities.hxx"
namespace A {
int foo (){
switch(B::doors){
//do something
}
return 0;
}
}
$ cat file3.cpp
#include "utilities.hxx"
#include "file2.h"
namespace B{
int doors=-1;
class Vehicle{
public:
void operation() {
doors++;
A::foo();
doors++;
A::foo();
}
};
}
$ nvcc -shared file2.cu file3.cpp -Xcompiler -fPIC
$ nvcc -lib file2.cu file3.cpp
$
I can only work with what you have shown.
|
72,652,920 | 72,653,229 | How to disable a wxTextCtrl Widget in wxWidgets C++? | I'm writing a wxWidgets program in C++. It has several single line wxTextCtrls in it and I need to disable them so the user cannot enter text in them. Later, when a menu item is clicked, I want to enable them again. How do I do this?
| Since wxTextCtrl is a subclass of wxWindow, it contains (probably overridden) virtual method Enable of wxWindow, documentation for which can be found here and which controls whether the window is enabled for user input according to its boolean argument (which defaults to true - enable input). Also, there is a handy non-virtual Disable method, which is defined to be equivalent to Enable(false).
You can use it like this to disable text control (assuming you save pointer to your wxTextCtrl instance in a m_pTextCtrl member of your window class):
m_pTextCtrl = new wxTextCtrl(...);
// ...
m_pTextCtrl->Disable();
and like this to enable it in your menu item event handler:
m_pTextCtrl->Enable();
|
72,653,144 | 72,653,228 | OnRenderSizeChanged overriden with reduced access error? | I am hosting a Win32 OpenGL window in WPF through a DLL. In the DLL when I try to override OnRenderSizeChanged from the base class HwndHost I get the error that it is being overridden with reduced access. Why is this happening and how can I fix it?
I am following these two tutorials Creating OpenGL Windows in WPF and Walkthrough: Host a Win32 Control in WPF. The latter is from Microsoft.
Here is my function:
virtual void OnRenderSizeChanged(SizeChangedInfo^ sizeInfo) override
{
if (m_hDC == NULL || m_hRC == NULL)
return;
// Apply DPI correction
// NOTE: sizeInfo->NewSize contains doubles, so we do the multiplication before
// converting to int.
int iHeight = (int)(sizeInfo->NewSize.Height * m_dScaleY);
int iWidth = (int)(sizeInfo->NewSize.Width * m_dScaleX);
if (iWidth == 0 || iHeight == 0)
return;
wglMakeCurrent(m_hDC, m_hRC);
glViewport(0, 0, iWidth, iHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, 1.0, 100.0);
// gluPerspective( 67.5, ((double)(iWidth) / (double)(iHeight)), 1.0, 500.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
| A class that implements a virtual method from a base class or any method from an interface cannot reduce the access of that method.
Making the function public fixed it.
public:
virtual void OnRenderSizeChanged(SizeChangedInfo^ sizeInfo) override
|
72,653,257 | 72,668,698 | How do I close this Gtk::MessageDialog before it's parent window is destructed? | I'm currently trying to create a simple Gtkmm program that has a button which spawns a dialog box. I'm currently having issues, however, as the destructor for the AppWindow class causes a segfault closing the dialog box. I check if the unique_ptr is nullptr before calling close, but even with that check it will crash if the dialog has already been closed before the main window has. Am I taking the correct approach here? Is the unique_ptr getting freed before the destructor is called?
main.c
#include "AppWindow.hpp"
#include <cstdio>
#include <cstdlib>
#include <gtkmm/application.h>
int main(int argc, char **argv) {
std::shared_ptr<Gtk::Application> app = Gtk::Application::create("org.dylanweber.test");
return app->make_window_and_run<AppWindow>(argc, argv);
}
AppWindow.hpp
#include <gtkmm/button.h>
#include <gtkmm/messagedialog.h>
#include <gtkmm/window.h>
#include <iostream>
#pragma once
class AppWindow : public Gtk::Window {
public:
AppWindow();
virtual ~AppWindow();
private:
Gtk::Button m_button;
std::unique_ptr<Gtk::MessageDialog> dialog;
void on_button_clicked();
};
AppWindow.cpp
#include "AppWindow.hpp"
AppWindow::AppWindow() : m_button("Hello, world!") {
this->m_button.set_margin(10);
this->m_button.signal_clicked().connect(sigc::mem_fun(*this, &AppWindow::on_button_clicked));
this->set_child(this->m_button);
}
AppWindow::~AppWindow() {
if (this->dialog != nullptr) {
this->dialog->close(); // seg fault here
}
}
void AppWindow::on_button_clicked() {
this->dialog = std::make_unique<Gtk::MessageDialog>(
"Button clicked", false, Gtk::MessageType::QUESTION, Gtk::ButtonsType::OK);
this->dialog->set_transient_for(*this);
this->dialog->set_secondary_text("Hello");
this->dialog->set_default_response(Gtk::ResponseType::OK);
this->dialog->show();
}
| Suggestion in the comments is right, you should leave your destructor empty and not call dialog->close() there. To see why, note that this function is a wrapper for GTK C API function gtk_window_close, defined like this for Gtk::Window class (from which Gtk::MessageDialog inherits through Gtk::Dialog):
// in gtk/gtkmm/window.cc
void Window::close()
{
gtk_window_close(gobj());
}
Here gobj() returns internal gobject_ pointer (defined in ObjectBase class) pointing to C API's GTK handle, which current class incapsulates. This pointer is used inside gtk_window_close this way:
// in gtk/gtkwindow.c
void
gtk_window_close (GtkWindow *window)
{
GtkWindowPrivate *priv = gtk_window_get_instance_private (window);
if (!_gtk_widget_get_realized (GTK_WIDGET (window)))
return;
if (priv->in_emit_close_request)
return;
g_object_ref (window);
if (!gtk_window_emit_close_request (window))
gtk_window_destroy (window);
g_object_unref (window);
}
// in gtk/gtkwidgetprivate.h
static inline gboolean
_gtk_widget_get_realized (GtkWidget *widget)
{
return widget->priv->realized;
}
As VS debugger told when running your example, segfault happens because widget is 0 in _gtk_widget_get_realized. It was cleared when dialog was closed, because by default closing (through close method or close button) a window means destroying it, as you can see e.g. by a call to gtk_window_destroy inside gtk_window_close. This destroy using GTK's C API gtk_window_destroy function through a pretty complex callback mechanism reaches appropriately registered C++ functions relating to memory management. Data breakpoint helped pinpoint exactly where gobject_ was set to 0 - Object::destroy_notify_ (which itself was indirectly called from reference counting code of GTK because dialog's reference count dropped to 0):
// gtk/gtkmm/object.cc
void Object::destroy_notify_()
{
//Overriden.
//GTKMM_LIFECYCLE
#ifdef GLIBMM_DEBUG_REFCOUNTING
g_warning("Gtk::Object::destroy_notify_: this=%p, gobject_=%p\n", (void*)(Glib::ObjectBase*)this, (void*)gobject_);
if(gobject_)
g_warning(" gtypename=%s\n", G_OBJECT_TYPE_NAME(gobject_));
#endif
//Actually this function is called when the GObject is finalized, not when it's
//disposed. Clear the pointer to the GObject, because otherwise it would
//become a dangling pointer, pointing to a non-existent object.
gobject_ = nullptr;
if(!cpp_destruction_in_progress_) //This function might have been called as a side-effect of destroy_() when it called g_object_run_dispose().
{
if (!referenced_) //If it's manage()ed.
{
#ifdef GLIBMM_DEBUG_REFCOUNTING
g_warning("Gtk::Object::destroy_notify_: before delete this.\n");
#endif
delete this; //Free the C++ instance.
}
else //It's not managed, but the C gobject_ just died before the C++ instance..
{
#ifdef GLIBMM_DEBUG_REFCOUNTING
g_warning("Gtk::Object::destroy_notify_: setting gobject_ to 0\n");
#endif
}
}
}
So, after closing a dialog, MessageDialog's internal handle is cleared to 0 (BTW, MessageDialog destructor is not called during this, which I also checked in a debugger), and since you call a close function which assumes it isn't, you get memory access problems. Destructor correctly works in case gobject_ was already cleared, so you don't get problems with recreating MessageDialog in on_button_clicked after it was closed (where std::unique_ptr calls destructor for previous object if it's present), as well as in case gobject_ still points to valid object, so you shouldn't have problems with it even if dialog wasn't closed before recreation. For the same reasons, MessageDialog destructor called in AppWindow destructor is OK regardless of whether the dialog was closed before the window.
P.S. Note that the gtkmm .cc files here are from vcpkg buildtrees, generated using gtkmm's custom preprocessing gmmproc tool during build process from .ccg source files, so you won't find them in repositories.
|
72,653,259 | 72,653,434 | How can I delete a self-defined node and let it be nullptr in the function | class node
{
public:
node* next;
int val;
};
void func(node* root)
{
node* p=root->next;
delete p;
p=nullptr;
}
int main()
{
node* root=new node();
node* nxt=new node();
root->val=1;root->next=nxt;
nxt->val=2;nxt->next=nullptr;
func(root);
cout<<(nxt==nullptr)<<endl;//false
cout<<(root->next==nullptr)<<endl;//false
}
How can I modify the func() to let last two line output 1?You can only delete nxt through root in func().
Edit:
At first I hold the thought that root->next and nxt are exactly one thing since root->next=nxt.The fact is that root->next is just a copy of nxt.They have same value but are stored in different memory.In other words, they are two different pointer but point to the same memory where stores a node with val==2 and next==nullptr.Thus it's impossible to delete nxt through root.And the same mistake happened in func().
I modify the code to show the similarity and difference between root->next and nxt.
int main()
{
node* root=new node();
node* nxt=new node();
root->val=1;root->next=nxt;
nxt->val=2;nxt->next=nullptr;
//point to same memory
cout<<(root->next)<<endl;
cout<<(nxt)<<endl;
cout<<"---------"<<endl;
//stored in different memory
cout<<&(root->next)<<endl;
cout<<&nxt<<endl;
}
And get output like this:
0x7219b0
0x7219b0
---------
0x7219a0
0x61ff08
What's more,I find that root->next subtract &(root->next) is always 0x10.In my opinion,the first value is where the node with val==2 is stored,the second value is a memory in the node with val==1.I guess it's because the two node is allocated almost the same time,so the operating system allocate them in a contiguous segment of memory.
Hope this can help other beginner.
| In func(), p is its own unique variable. In your example, it holds a copy of the address held in root->next. So, whatever you do to p itself, will not effect root->next in any way. However, when you are calling delete p, you are destroying the Node object that both p and root->next are pointing at. You are setting p to nullptr (which is redundant since p goes out of scope immediately afterwards), but you are leaving root->next dangling.
To fix func() so that the (root->next==nullptr) condition can become true in main(), you have two choices:
get rid of p and just act on root->next directly:
void func(node* root)
{
delete root->next;
root->next = nullptr;
}
make p be a reference to root->next rather than a copy:
void func(node* root)
{
node* &p = root->next;
delete p;
p = nullptr;
}
But, nothing that func() does can affect the nxt variable in main() at all, since nxt is local to main() and func() has no concept that nxt exists. That is why the (nxt==nullptr) condition can never become true in your example. In fact, the nxt variable does not need to even exist at all, eg:
class node
{
public:
int val;
node* next = nullptr;
};
void func(node* root)
{
node* &p = root->next;
delete p;
p = nullptr;
}
int main()
{
node* root = new node{1};
root->next = new node{2};
func(root);
cout << (root->next == nullptr) << endl; // true
}
|
72,653,519 | 72,664,662 | Am I correctly rotating my model using matrices? | I have been getting unexpected behavior while trying to rotate a basic cube. It may be helpful to know that translating the cube works correctly in the y and z direction. However, translating along the x axis is backwards(I negate only x for proper results) which I haven't been able to figure out why.
Furthermore, rotating the cube has been a mess. Without any sort of transform the cube appears correctly. Once I add a rotation transformation the cube is not displayed until I change one of the x,y,z rotation values from 0(Putting all values back to 0 makes it disappear again). Once it appears the cube won't rotate around whichever x,y,z plane I first changed unless I change two or more of the coordinates. It also wobbles around its origin when rotating.
Below is a snippets of my code I believe has incorrect math.
/* Here's how I setup the matrices for a mvp matrix*/
proj = glm::perspective(glm::radians(90.0f), (960.0f / 540.0f), 0.1f, 400.0f);
view = glm::lookAt(glm::vec3(0, 0, -200), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
glm::mat4 model = glm::mat4(1.0f);
/* Here's how I transform the model matrix, note
translating works properly once the cube is visible*/
model = glm::translate(model, glm::vec3(-translation[0], translation[1], translation[2])); //negative x value
model = glm::rotate(model, 30.0f, rotation);
glm::mat4 mvp = proj * view * model;
shader->Bind();
shader->SetUniformMat4f("MVP", mvp);
renderer.Draw(*c_VAO, *c_EBO, *shader);
/* Here's how I use these values in my vertex shader */
layout(location = 0) in vec4 position;
...
uniform mat4 MVP;
...
void main()
{
gl_Position = u_MVP * position;
....
};
I've checked both the translation and rotation vectors values and they are as expected but I am still going mad trying to figure out this problem.
| The unit of the angle of glm::rotate is radians. Use glm::radians to convert form degrees to radians:
model = glm::rotate(model, 30.0f, rotation);
model = glm::rotate(model, glm::radians(30.0f), rotation);
|
72,653,572 | 72,653,665 | Argument of type "const wchar_t*" is incompatible with parameter of type "LPTSTR" | I am a programmer familiar with C# & Java and new to C++. I am trying to create an editor in C# WPF for my C++ OpenGL application and I am following these tutorials: Creating OpenGL Windows in WPF and Walkthrough: Host a Win32 Control in WPF. The latter is from Microsoft.
This line of code Helper::ErrorExit(L"RegisterWindowClass"); gives me this error: Argument of type "const wchar_t*" is incompatible with parameter of type "LPTSTR". It is the L that is triggering this according to Visual Studio and I don't exactly know how to fix it.
public:
//
// Taken from MSDN
//
static void ErrorExit(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
0, NULL);
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
::MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
ExitProcess(dw);
}
| TEXT("RegisterWindowClass") is supposed to be used.
Avoid using L"RegisterWindowClass" or "RegisterWindowClass" with parameters of type LPTSTR.
Also change the parameter type to LPCTSTR in static void ErrorExit(LPCTSTR lpszFunction).
|
72,654,201 | 72,654,260 | What is the use case for not having lazy evaluation of value_or()? | I was having trouble when using foo.value_or(bar()) in my code, because I wasn't expecting the function bar() to be called when the optional variable foo had a value. I've since found this question that explains that value_or() doesn't use lazy evaluation.
Now I'm left wondering why that is, when lazy evaluation has always been a standard aspect of conditionals in C and C++. I find this very counter-intuitive, and I assume I wasn't the first and won't be the last to be tripped up by it. With the risk of asking to look into the minds of the people who devised std::optional, is there a use case that explains why lazy evaluation would not be a good idea here?
| It's not possible to design a function that does lazy evaluation. Function arguments are always evaluated if the function call itself is evaluated. The ONLY things that can short-circuit or evaluate in a lazy way are the built-in && and || and ?: operators.
Other related comments:
A few Standard library functions or features do things that would not be possible to implement in portable code, so they require some compiler "magic". But they try to keep those sorts of things limited.
Even an overloaded operator function operator&& or operator|| still must evaluate its operands, so that's a caution about overloading those: they'll never act just like the built-in versions.
Although the value_or function itself can't put off evaluating its argument, there are some tricks you could use to pass in a lazy placeholder that only does a computation if it's actually needed.
|
72,654,323 | 72,656,297 | Accessing parent window from a dialog in mfc | I am making a doc/view arch SDI application.
I invoke a COptionsDialog in CSquaresView.
void CSquaresView::OnOptions()
{
COptionsDialog dlg(this);
if (dlg.DoModal() == IDOK)
...
}
In COptionsDialog I want to access CSquaresView.
BOOL COptionsDialog::OnInitDialog()
{
CDialog::OnInitDialog();
CWnd *pParent = GetParent();
if (pParent) {
CSquaresView *pView = dynamic_cast<CSquaresView*>(pParent); //pView is always NULL
if (pView != NULL)
{
CSquaresDoc* pDoc = pView->GetDocument();
...
}
But I always get pView as NULL;
Please help me to solve this problem.
| The observed behavior makes sense. A (modal) dialog's owner must be
an overlapped or pop-up window [...]; a child window cannot be an owner window.
CView-derived class instances generally are child windows. As such they cannot be the owner of a (modal) dialog. When you pass a child window into the c'tor of a CDialog-derived class, the system walks up the window hierarchy until it finds an overlapped or pop-up window, and uses that as the owner of the dialog. Regardless of whether you then call GetParent, GetAncestor, or CWnd::GetOwner, it is this true owner (usually your CFrameWnd-derived implementation) where window traversal starts.
Thus, you cannot generally use standard window traversal to find the window passed into a (modal) dialog's constructor. However, MFC records the CWnd(-derived) class instance you pass into your COptionsDialog constructor and stores it in a protected member variable m_pParentWnd, inherited from the CDialog class.
As long as COptionsDialog derives public/protected from CDialog or CDialogEx, the implementation can access this class member.
The following OnInitDialog implementation will do what you're looking for:
BOOL COptionsDialog::OnInitDialog()
{
CDialog::OnInitDialog();
CSquaresView *pView = dynamic_cast<CSquaresView*>(m_pParentWnd);
if (pView != NULL)
{
CSquaresDoc* pDoc = pView->GetDocument();
...
}
There are other options available. For example, you could supply a COptionsDialog constructor that takes both a CWnd* and a CSquaresDoc*, delegating the first onto the base class c'tor and storing the document pointer in a (private) class member. This makes for code that's easier to follow in that it explicitly spells out, that the dialog depends on the document.
|
72,654,401 | 72,654,683 | "A breakpoint instruction (__debugbreak() statement or a similar call) was executed in Main.exe", but there is no error? | I have an infinite loop that breaks if user exits out of the main window. I have the following code running in the loop:
unsigned int* renderableShapeIndices = new unsigned int[aNumberCreatedAtRuntime];
// Do something
delete[] renderableShapeIndices;
Then the following happens a couple of loop iterations and cease to happen after the first iteration:
1st breakpoint:
A breakpoint instruction (__debugbreak() statement or a similar call) was executed in Main.exe.
2nd breakpoint:
Unhandled exception at 0x00007FF8C3B8C729 (ntdll.dll) in InTimeEngine2D.exe: 0xC0000374: A heap has been corrupted (parameters: 0x00007FF8C3BF7780).
Has anyone else gone through similar issues? I have no idea what is going on.
Another interesting factor about this is that it only happens in debug mode. It does not happen in release mode.
| The answer to the problem is in the comment section of the question.
Apparently, if one attempts to write to an array outside of its bounds, it will, but it ends up overwriting data of other places in the code, causing bugs in other parts of the program, even if these two parts of the program are unrelated. In my case, they were completely unrelated.
|
72,654,526 | 72,654,586 | Calling the overriding function through a reference of base class | I googled and learnt the differences between function hiding and function overriding.
I mean I understand the output of testStuff(), which is seen in the below code snippet.
But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function through the said reference finally invoking the function of the derived class other than the base class.
Could somebody shed some light on this matter?
Here is the code snippet:
#include <iostream>
using namespace std;
class Parent {
public:
void doA() { cout << "doA in Parent" << endl; }
virtual void doB() { cout << "doB in Parent" << endl; }
};
class Child : public Parent {
public:
void doA() { cout << "doA in Child" << endl; }
void doB() { cout << "doB in Child" << endl; }
};
void testStuff() { //I can understand this function well.
Parent* p1 = new Parent();
Parent* p2 = new Child();
Child* cp = new Child();
p1->doA();
p2->doA();
cp->doA();
p1->doB();
p2->doB();
cp->doB();
}
int main()
{
Child cld;
Parent prt = cld;
Parent &ref_prt = cld;
prt.doA();
ref_prt.doA();
prt.doB();
ref_prt.doB(); //The one which most surprised me! I know `Child::doB()` overrides `Parent::doB()`. And I understand the output for `testStuff()`.
//But I still do not understand this line and `Parent &ref_prt=cld`.
return 0;
}
Here is the output:
doA in Parent
doA in Parent
doB in Parent
doB in Child
|
But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function through the said reference finally invoking the function of the derived class other than the base class.
It is indeed exactly like that.
If a member function is virtual in a class, then calling it through a pointer-or-reference to that class will result in a dynamic dispatch, so if the actual object is of a derived class which overrides that function (btw, it neededn't declare it virtual because it's already virtual; and it'd better delcare it override, so that it errors out if it doesn't really override, e.g. because you mistyped the name), than that override will be called.
Tha page linked above should sufficient to shed light on this as well as other doubts.
|
72,654,693 | 72,654,744 | Default constructed std::string c_str() value | std::string s1;
std::string s2;
assert(strlen(s1.c_str()) == 0);
assert(s1.c_str() == s2.c_str());
Does these two assert always true?
I use C++11, and I have checked the standard, the Table 63 in Β§21.4.2 says:
data() a non-null pointer that is copyable and can have 0 added to it
size() 0
capacity() an unspecified value
I think c_str() is the same as data(). But I have some question about this defination.
Does "CAN have 0 added to it" == "MUST and ALWAYS have 0 added to it"?
Does all default constructed std::string shared a same underlay buffer?
I test on gcc, these two assert is true. I wonder does these always true for all compiler?
| The first assertion is guaranteed to succeed. c_str() always returns a pointer to a null-terminated string with the same string contents as held by the std::string object, which is an empty string for both s1.
The second assertion is not guaranteed to succeed. There is nothing requiring the c_str() returned from a std::string to be the same if the content is the same. Default-constructed strings do not need to share the same underlying buffer. That would be an implementation detail of a particular standard library implementation. (I think libstdc++ does something like this depending on configuration for some backwards-compatibility(?) reasons if I remember correctly, see the --enable-fully-dynamic-string configure option).
Note that prior to C++11, data() did not have the same effect as c_str(). data() was not guaranteed to give a pointer to a null-terminated string. If the string was empty, then the pointer returned by it was not allowed to be dereferenced. So replacing c_str() with data() in your examples would, prior to C++11, result in undefined behavior on the call to strlen.
The wording "and can have 0 added to it" is somewhat weird and I am not completely sure what it is supposed to convey, but for C++11 (draft N3337) data()'s return value is further specified in [string.accessors]/1 so that data() + i == &operator[](i) for all i in the range [0,size()] and operator[] is specified in [strings.access]/2 to return a reference to a CharT() (aka a null character) for operator[](size()) without any conditions.
The strange wording has also been replaced via editorial change in 2018, see https://github.com/cplusplus/draft/pull/1879.
|
72,655,106 | 72,655,314 | I'm getting a SIGSEV signal when running a program on HackerRank | I had made a post yesterday but I scrapped it and approached it with C++ instead of Java.
I tested the code on the compiler installed on my computer and it ran fine. When I run it on HackerRank, it keeps giving me Segmentation fault. Please find the code and compiler output below.
I read a few posts that mentioned it can happen due to illegal memory access, but I don't see where I did so. I have spent over 5 hours already and will be coming back to this in a while. Any help is appreciated.
struct Date
{
int Day;
int Year;
int Month;
bool latest(Date d){
if (Year > d.Year){
return true;
}
else if (Year == d.Year)
{
if(Month > d.Month){
return true;
}
else if (Month == d.Month){
if(Day> d.Day){
return true;
}
}
}
}
};
Date ThirdLatest(std::vector<Date> &dates) {
vector<Date> d;
int length = dates.size();
//std::cout << std::unitbuf;
for (int i=0; i<length; i++){
int flag = 0;
for (int j=0; j<d.size(); j++){
if (dates[i].Day == d[j].Day && dates[i].Month == d[j].Month && dates[i].Year == d[j].Year){
flag = 1;
break;
}
}
if (flag ==1)
d.push_back(dates[i]);
}
Date temp;
for (int i=0; i<d.size(); i++){
for (int j=i+1; j<d.size(); j++){
if (!d[i].latest(d[j])){
temp.Day = d[i].Day;
temp.Month = d[i].Month;
temp.Year = d[i].Year;
d[i].Day = d[j].Day;
d[i].Month = d[j].Month;
d[i].Year = d[j].Year;
d[j].Day = temp.Day;
d[j].Month = temp.Month;
d[j].Year = temp.Year;
}
}
}
return d[2];
}
int main() {
int numberOfEntries;
int res = scanf("%d\n", &numberOfEntries);
std::vector<Date> dates;
for (int i = 0; i < numberOfEntries; ++i)
{
Date date;
res = scanf("%d-%d-%d", &date.Day, &date.Month, &date.Year);
dates.push_back(date);
}
Date result = ThirdLatest(dates);
printf("%02d-%02d-%d\n", result.Day, result.Month, result.Year);
return 0;
}
Compiler output
Reading symbols from Solution...done.
[New LWP 71078]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 ThirdLatest (dates=...) at Solution.cpp:57
57 for (int i=0; i<length; i++){
To enable execution of this file add
add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual. E.g., run from the shell:
info "(gdb)Auto-loading safe path"
Sample input:
7
14-04-2001
29-12-2061
21-10-2019
07-01-1973
19-07-2014
11-03-1992
21-10-2019
Expected output: 19-07-2014
| The error is here
if (flag ==1)
d.push_back(dates[i]);
It should be
if (flag == 0)
d.push_back(dates[i]);
You got your logic wrong. You are trying to avoid adding duplicates to your vector but you ended up adding only duplicates which means that nothing gets added to the d vector. Then this line
return d[2];
results in an illegal access error.
Plus this function is missing a return statement
bool latest(Date d){
if (Year > d.Year){
return true;
}
else if (Year == d.Year)
{
...
}
return false; // this line is necessary
}
|
72,655,842 | 72,655,916 | Area of Boost c++ in Square Meters | I have a
boost::geometry::model::polygon<Point> Algorithm::poly
and i'm looking for the area of the polygon with
area = bg::area(poly);
the result is
1.10434e+08
When i'm reading the documentation, i can see
"The units are the square of the units used for the points defining the surface". I really don't understand what it means.
https://www.boost.org/doc/libs/1_65_0/libs/geometry/doc/html/geometry/reference/algorithms/area/area_1.html
I would like to know if we have a way to transform the return of the bg::area in a m2 result.
With another tool (i can't use it in my code) i can see that the total of m2 from the polygon is 11043 m2.
How can i have 11043 with 1.10434e+08.
| The points in polyare cartesian (x,y) coordinates. What is their unit? are they in mm, cm, attoparsec?
The resulting unit is the square of that. But we can work that out from the data given:
sqrt(1.1043e+08 / 11043) = srqt(10000) = 100
So it seems your points are in 0.01 m == centimeter, so the area returned is in cmΒ²
(1mΒ² = 10000cmΒ²)
|
72,655,861 | 72,656,057 | string returns xstring file location | #include <iostream>
#include <conio.h>
#include <stack>
#include <string>
using namespace std;
int main{
string h = "";
h = ("" + 'a');
cout << h;
return 0;
}
Output: "nity\VC\Tools\MSVC\14.29.30133\include\xstring"
I am honestly clueless as to what to do. I've never had this happen before.
Note: I've found a way to avoid this by appending the char like this:
string g="";
g+='a';
Regardless, why is this?
| "" is a literal of type const char[1], which is the identical as const char* in most regards. 'a' is a literal of type char, which is really just an integer type. So if you do "" + 'a', you will get a pointer to 'a' (=97 in ASCII) characters after wherever the compiler decides to put the "". Which is then converted to an std::string.
In the working example, you convert the "" literal to std::string first, then add a char to it. std::string overloads the + and += operators, so it will produce a reasonable result.
|
72,656,102 | 72,657,951 | OpenSSL BIO thread safety | OpenSSL's FAQ about thread safety says the following:
Yes but with some limitations; for example, an SSL connection cannot be used concurrently by multiple threads. This is true for most OpenSSL objects.
It does not allow me to understand whether the following will be safe:
I call a blocking read on a BIO
If my application should be terminated before the response is received, I call close on that BIO
| OpenSSL does not guarantee thread safety if you call 2 functions using the same BIO object at the same time from 2 different threads. However that is not what you are doing.
You are sharing an fd between two different threads. One copy of the fd is being used by the OpenSSL library in the BIO_read() call in one thread, and you are calling close() on the same fd in a different thread.
Sharing an fd in this way is allowed on Linux so there should be no problems in your case. I can't speak for Windows.
|
72,656,369 | 72,656,544 | Overloaded operator= to switch between template types | I have a template class that multiple classes are inheriting from to basically make some user-friendly builders, hiding the functions that are not required on different builders, while following DRY.
However, I'm having trouble switching between the builder types. I'd prefer to use the operator= to switch without hassle and have the following code.
template<class T> class BuilderFunctions
{
protected:
std::string text;
public:
template<class Other>
BuilderFunctions<T>& operator=(const Other& other);
};
template <class T>
template <class Other>
BuilderFunctions<T>& BuilderFunctions<T>::operator=(const Other& other)
{
// yes, I need same object protection
text = other.text;
return *this;
}
Classes
class BuilderGenericList : public BuilderFunctions<BuilderGenericList>
{
public:
BuilderGenericList() = default;
};
// Build configuration details
class BuilderRootList : public BuilderFunctions<BuilderRootList>
{
private:
// I'll delete the functions I don't want accessed here
public:
BuilderRootList() = default;
};
Code that says no
// Real world you'd build the root first and switch out to another builder or be using a prototype to seed another builder
BuilderRootList cmakeRoot;
BuilderGenericList list;
// Separate to make sure it's not trying to use cop constructor
list = cmakeRoot;
Except I might be doing something I shouldn't be doing with template classes, although others seem to have success with templates in the operators, so assume possible, and I'm making some kind of mistake.
More info: The error I get is:
Error C2679 binary '=': no operator found which takes a right-hand operand
of type 'BuilderRootList' (or there is no acceptable conversion)
So It's definitely looking for my operator=, it's just not generating one from the template
| When you do the template inheritance, you have to be explicit in case of base classes members. More read:
Why do I have to access template base class members through the this pointer?
Derived template-class access to base-class member-data
Accessing base member functions in class derived from template class
In your case, the members text, and operator=, can be brought via using declaration.
class BuilderGenericList : public BuilderFunctions<BuilderGenericList>
{
public:
BuilderGenericList() = default;
using BuilderFunctions<BuilderGenericList>::text;
using BuilderFunctions<BuilderGenericList>::operator=;
// ... so on, other members from base if needed!
};
// Build configuration details
class BuilderRootList : public BuilderFunctions<BuilderRootList>
{
public:
BuilderRootList() = default;
using BuilderFunctions<BuilderRootList>::text;
using BuilderFunctions<BuilderRootList>::operator=;
// ... so on, other members from base if needed!
};
Live Demo
Note that, this will make the memberusing BuilderFunctions<BuilderGenericList>::text public, if this is not what wanted, consider the suggestion by @Jarod42 in other answer.
|
72,656,837 | 72,657,678 | QT CPP login dialog cloisng when input wrong password | I made a simple login with qdialog on main.cpp file. When I input wrong password, Dialog didn't asks password again, simple closing a dialog. How can I make asks again when input wrong?
QT 5.15
C++
Here is my code
QString login = QInputDialog::getText(NULL, "Login","username",QLineEdit::Normal);
if (login == cnstnt::username)
{
QString getPassword = QInputDialog::getText(NULL, "Login","password",QLineEdit::Password);
QString hashpassword = hlpr::passwordHash(getPassword.toUtf8());
if(hashpassword == hlpr::getTxtPassword()){
w.show();
}else{
QMessageBox::warning(nullptr, "error!", "wrong password!");
}
}
else
{
QMessageBox::warning(nullptr, "error!", "KullanΔ±cΔ± adΔ±nΔ±z hatalΔ±!");
}
| This should work:
QString login = QInputDialog::getText(NULL, "Login","username",QLineEdit::Normal);
if (login == cnstnt::username)
{
QString getPassword = QInputDialog::getText(NULL, "Login","password",QLineEdit::Password);
QString hashpassword = hlpr::passwordHash(getPassword.toUtf8());
while (hashpassword != hlpr::getTxtPassword()) {
QMessageBox::warning(nullptr, "error!", "wrong password!");
QString getPassword = QInputDialog::getText(NULL, "Login","password",QLineEdit::Password);
hashpassword = hlpr::passwordHash(getPassword.toUtf8());
}
w.show();
}
else
{
QMessageBox::warning(nullptr, "error!", "KullanΔ±cΔ± adΔ±nΔ±z hatalΔ±!");
}
The loop condition checks if the password is incorrect. If it is, it shows a message and asks for password again until the password is a match.
|
72,656,838 | 72,656,982 | no operator "/" matches these operands | trying to make player shoot 360
is there something wrong or misspelled?
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
using namespace sf;
int main()
{
RenderWindow window(VideoMode(800, 600), "360 shooting object");
CircleShape circle(25.f);
circle.setFillColor(Color::White);
Vector2f circleCenter;
Vector2f mousePosWindow;
Vector2f aimDirection;
Vector2f aimDirectionNorm;
while(window.isOpen())
{
Event event;
while(window.pollEvent(event))
{
if(event.type==Event::Closed) window.close();
if(Keyboard::isKeyPressed(Keyboard::Escape)) window.close();
}
draw(window, circle);
update(window, circle, circleCenter, mousePosWindow, aimDirection, aimDirectionNorm);
}
return 0;
}
void update(RenderWindow &window, CircleShape &shape, Vector2f circleCenter,
Vector2f mousePosWindow, Vector2f aimDirection, Vector2f aimDirectionNorm)
{
circleCenter = Vector2f(shape.getPosition().x + shape.getRadius(),
shape.getPosition().y + shape.getRadius());
mousePosWindow = Vector2f(Mouse::getPosition(window));
aimDirection = mousePosWindow - circleCenter;
aimDirectionNorm = aimDirection / sqrt(pow(aimDirection.x, 2)) + sqrt(pow(aimDirection.y, 2));
}
im using sfml
error at the aimDirectionNorm part
no operator matches the '/' operand
what wrong with the '/' operator i don't understand
i delete some code i
| Firstly your math is wrong
aimDirectionNorm = aimDirection / sqrt(pow(aimDirection.x, 2)) +
sqrt(pow(aimDirection.y, 2));
should be
aimDirectionNorm = aimDirection / sqrt(pow(aimDirection.x, 2) +
pow(aimDirection.y, 2));
Secondly operator/ requires a Vector2f and a float but sqrt returns a double. Because Vector2f is a template the normal double to float conversion does not happen.
Simple way to get a float would be to use sqrtf and powf
aimDirectionNorm = aimDirection / sqrtf(powf(aimDirection.x, 2) +
powf(aimDirection.y, 2));
|
72,656,879 | 72,657,888 | Boost Spirit parser rule to parse square brackets | I have to parse a string that can optionally have square brackets in it. For e.g. This can be my token string:
xyz[aa:bb]:blah
I have used rules like
+(~qi::char_("\r\n;,="))
+(~qi::char_("\r\n;,=") | "[" | "]")
+(qi::char_ - qi::char_("\r\n;,="))
But none of them accepts the square brackets. Is there some special handling of [] in the parser?
| You need to show the code. Here's a simple tester that shows that all of the parsers succeed and give the expected result:
Live On Coliru
#include <boost/spirit/include/qi.hpp>
#include <iomanip>
namespace qi = boost::spirit::qi;
int main()
{
using It = std::string::const_iterator;
for(std::string const input : {"xyz[aa:bb]:blah"})
{
qi::rule<It, std::string()> rules[] = {
+(~qi::char_("\r\n;,=")),
+(~qi::char_("\r\n;,=") | "[" | "]"),
+(qi::char_ - qi::char_("\r\n;,=")),
};
for(auto const& r : rules)
{
std::string out;
std::cout << std::boolalpha
<< qi::parse(begin(input), end(input), r, out) << " -> "
<< std::quoted(out) << "\n";
}
}
}
Printing:
true -> "xyz[aa:bb]:blah"
true -> "xyz[aa:bb]:blah"
true -> "xyz[aa:bb]:blah"
The best guesses I have, not seeing your actual code:
you are using a skipper that eats some of your characters (see Boost spirit skipper issues)
you are using an input iterator that interferes
you're invoking UB. To be honest, without context, this seems the most likely
If you show more code I'll happily diagnose which it is.
|
72,657,632 | 72,657,725 | Last node is not printed in Linked List | I was trying to learn the Linked list and perform insertion operations from beginning of the list. while printing the nodes, the first node is not printed. Here is the core functions which I have written. Can someone help me?
struct Node //basic structure for a node
{
ll data; //data which we want to store
Node* link; //address of the next node;
};
Node* head=NULL;
void Insert(ll x) //insertion at beginning
{
Node* temp=new Node();
temp->data=x;
temp->link=head; //we are linking new node with previously connected node
head=temp;
}
void Print()
{
Node* temp=head;
while(temp->link!=NULL) //traversing the list until last element(last element.link = NULL)
{
cout<<temp->data<<" ";
temp=temp->link;
}
cout<<endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
f(i,0,5)
{
ll x;cin>>x;
Insert(x);
}
Print();
return 0;
}
| Your Print function requires that the last node is linked or it won't be printed. Since the last node is never linked, it will never be printed.
void Print()
{
Node* temp = head;
while(temp) // <- corrected condition
{
std::cout << temp->data << ' ';
temp = temp->link;
}
std::cout << '\n';
}
|
72,657,973 | 72,658,442 | Scope of dynamic (multidimm) array when initialized with pointer and new | I'm royally confused right now. I have seen similar questions asked, and my implementation seems to be along the lines of these solutions, but I just can't get it to work.
I need to have a UtilClass that can initialize and dump a multi-dimensional dynamic array. I just want to pass the pointer the the array in BaseClass that I want initialized along with the dims. I chose to use the new keyword instead of malloc(), but I'm worried that the scope of the pointers is limited to the init function and not to the lifetime of the BaseClass (or the array pointer for that matter) and that's why the dump function produces a SEGFAULT.
Here is some code to explain:
// BaseClass.h
#pragma once
include "UtilClass.h"
class BaseClass
{
public:
UtilClass* util{nullptr};
double** array{nullptr};
};
// BaseClass.cpp
#include "BaseClass.h"
BaseClass::BaseClass() {
util = new UtilClass();
util->init(array, 4, 6);
util->dump(array, 4, 6);
}
// UtilClass.h
#pragma once
class UtilClass {
void init(double** array, int rows, int cols);
void dump(double** array, int rows, int cols);
};
// UtilClass.cpp
#include "UtilClass.h"
void UtilClass::init(double **darray, int rows, int cols) {
int i,j;
array = new double*[rows];
for (i = 0; i < rows; i++)
array[i] = new double[cols];
for (i = 0; s < rows; i++)
for (j = 0; a < cols; j++) {
data[i][j] = 1;
std::cout << "Data in array " << data[i][j] << std::endl; // This obviously works
}
}
void dump(double** array, int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
std::cout << array[i][j] << " "; // But this produces a SEGFAULT
std::cout << std::endl;
}
| Let me start off with a piece of advice: it's best to reuse existing tools. Consider using std::vector for dynamically-allocated array. This is well tested, optimized and easy to use. Otherwise, you'll need to deal with conundrums of memory management (e.g. deallocate the allocated chunks of memory in the dtor of BaseClass).
Regarding your question: when you call init, you pass the pointer by value. This means that the init method allocates some memory and stores the pointer to it in its local copy of darray. At the end of init this local variable is gone (you lose access to it, leaking whole allocated memory). Change the method to:
void UtilClass::init(double ***array, int rows, int cols) {
int i,j;
*array = new double*[rows];
for (i = 0; i < rows; i++)
(*array)[i] = new double[cols];
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++) {
(*array)[i][j] = i*j;
std::cout << "Data in array " << (*array)[i][j] << std::endl; // This obviously works
}
}
When calling dump, you need to pass 4 and 6 (and not 5 and 6).
|
72,658,026 | 72,658,186 | Clang and GCC disagree on whether overloaded function templates are ambiguous | I'm trying to port some code written for GCC (8.2) to be compilable by Clang:
#include <tuple>
struct Q{};
using TUP = std::tuple<Q>;
template<typename Fn>
inline
void feh(Fn&, const std::tuple<>*)
{}
template<typename Fn, typename H>
inline
void feh(Fn& fn, const std::tuple<H>*)
{
fn(H{});
}
template<typename Fn, typename H, typename... R>
inline
void feh(Fn& fn, const std::tuple<H, R...>*)
{
fn(H{});
using Rest = const std::tuple<R...>*;
feh<Fn, R...>(fn, static_cast<Rest>(nullptr));
}
template<typename Tuple, typename Fn>
inline
void fe(Fn& fn, const Tuple * tpl = nullptr)
{
feh(fn, tpl);
}
int main()
{
auto r = [] (Q const&) {};
TUP tup;
fe<TUP>(r, &tup);
}
GCC 8.2 (and 12.1) compiles the code just fine. However, Clang 11.0.0 (and 14.0.0) complains that the call from fe to feh is ambiguous between void feh(Fn& fn, const std::tuple<H>*) [with Fn = (lambda at <source>:38:14), H = Q] and void feh(Fn& fn, const std::tuple<H, R...>*) [with Fn = (lambda at <source>:38:14), H = Q, R = <>].
https://godbolt.org/z/5E9M6a5c6
Which compiler is right?
How can I write this code so both compilers accept it?
Both if constexpr and fold expressions would work in C++17, but this is a library header included by many projects, and not all of them are compiled with C++17. I need a solution which works in C++11.
| clang++ is correct because both functions matches equally good. I'm unsure which compiler that is correct, but...
A C++11 solution could be to just add the requirement that the Rest part must contain at least one type and that is easily done by just adding R1. That would mean that the rest of your code could be left unchanged:
template<typename Fn, typename H, typename R1, typename... R>
inline
void feh(Fn& fn, const std::tuple<H, R1, R...>*)
{
fn(H{});
using Rest = const std::tuple<R1, R...>*;
feh<Fn, R1, R...>(fn, static_cast<Rest>(nullptr));
}
A C++17 solution would be to remove the other feh overloads and use a fold expression:
template <typename Fn, typename... H>
inline void feh(Fn& fn, const std::tuple<H...>*) {
(..., fn(H{}));
}
This is a unary left fold over the comma operator which "unfolded" becomes:
(((fn(H1{}), fn(H2{})), ...), fn(Hn{}))
|
72,658,358 | 72,658,579 | Is it safe to grab the ownership of a STL vector's pointer? | I want to use the vector to collect some generated ints, the number of which I don't know until runtime. However, the interface I have to implement requires returning a native pointer which is supposed to be freed by the caller. The vector is going to be quite large, so, to avoid copying, I do the following:
std::vector<int>* const Collector = new std::vector<int>;
//Several Collector.push_back();s
int* ReturnPointer = Collector->data();
free(Collector);
return ReturnPointer;
The code above is meant to avoid the vector's deconstruction which will free the data pointer that I have to return - and the vector controller itself is freed.
My question is: is this trick safe? Or is there a better solution?
IMPORTANT: The full architecture is out of my control. I'm not allowed to return something other than a native pointer or require the callers to change their calling code. That is, I can't return that vector.
I know that it's bad to free a newed pointer. Then what about doing:
std::vector<int>* const Collector = (std::vector<int>*)malloc(sizeof(std::vector<int>*));
*Collector = std::vector<int>;
//Several Collector.push_back();s
int* ReturnPointer = Collector->data();
free(Collector);
return ReturnPointer;
This time I freed the malloced pointer, is this OK?
| You can, but not with std::vector<int>. You need an allocator that is compatible with the deallocation, and that will not deallocate the final array.
If you new, new[] or malloc you must respectively delete, delete[] or free, mixing those is undefined behaviour. You must check how the interface deallocates the return value.
You also don't need to new the local vector.
template <typename T>
class releasing_allocator {
bool * released;
public:
using value_type = T;
releasing_allocator(bool * released) : released(released) {}
T * allocate(std::size_t n) { return new T[n]; }
void deallocate(T * p, std::size_t n) { if (!*released) delete[] p; }
};
bool done = false;
std::vector<int, releasing_allocator<int>> Collector{ releasing_allocator { &done } };
Collector.push_back(42); // etc
done = true;
return Collector.data();
Because of these issues, it is typical to require the caller to allocate whatever they will deallocate.
|
72,659,156 | 72,659,705 | Convert double to integer mantissa and exponents | I am trying extract the mantissa and exponent part from the double.
For the test data '0.15625', expected mantissa and exponent are '5' and '-5' respectively (5*2^-5).
double value = 0.15625;
double mantissa = frexp(value, &exp);
Result: mantissa = 0.625 and exp = -2.
Here the mantissa returned is a fraction. For my use case (ASN.1 encoding), mantissa should be integer. I understand by right-shifting the mantissa and adjusting the exponent, I can convert binary fraction to the integer. In the eg, 0.625 base 10 is 0.101 base 2, so 3 bytes to be shifted to get the integer. But I am finding it difficult to find a generic algorithm.
So my question is, how do I calculate the number bits to be shifted to convert a decimal fraction to a binary integer?
| #include <cmath> // For frexp.
#include <iomanip> // For fixed and setprecision.
#include <iostream> // For cout.
#include <limits> // For properties of floating-point format.
int main(void)
{
double value = 0.15625;
// Separate value into significand in [.5, 1) and exponent.
int exponent;
double significand = std::frexp(value, &exponent);
// Scale significand by number of digits in it, to produce an integer.
significand = scalb(significand, std::numeric_limits<double>::digits);
// Adjust exponent to compensate for scaling.
exponent -= std::numeric_limits<double>::digits;
// Set stream to print significand in full.
std::cout << std::fixed << std::setprecision(0);
// Output triple with significand, base, and exponent.
std::cout << "(" << significand << ", "
<< std::numeric_limits<double>::radix << ", " << exponent << ")\n";
}
Sample output:
(5629499534213120, 2, -55)
(If the value is zero, you might wish to force the exponent to zero, for aesthetic reasons. Mathematically, any exponent would be correct.)
|
72,659,627 | 72,659,757 | Template Error with passing member functions that contain a mutex | I spend an hour wiggling down a large class I needed to pass a member function of to a minimal example. The compiler error given is:
error C2664: 'B::B(const B &)': cannot convert argument 1 from '_Ty'
to 'const B &'
Below is a minimal example and the Code compiles fine when using a pointer to the mutex. Can somebody help me understand what went wrong here and why and how I could have gotten hints towards that from the error message in 'tuple'?
Thanks everyone!
#include <functional>
#include <iostream>
#include <string>
#include <mutex>
class A {
public:
std::string Init(std::function<std::string(void)> f) {
return f();
}
};
class B {
std::mutex lock;
std::string member = "Hello World!";
public:
std::string foo() {
return member;
}
};
int main() {
auto callback3 = std::bind(&B::foo, B());
auto instance = A();
std::cout << instance.Init(callback3) << "\n";
}
| A std::mutex is non-copyable, its copy constructor is deleted. There are no defined semantics for copying a mutex, what does that mean? If a mutex has locked something, does it mean that, somehow, two mutexes managed to lock the same object, the original and the copy, and both must be unlocked. For this reason a std::mutex is not copyable.
This makes B non-copyable too.
std::bind requires a copyable callable object to work with, which results in this compilation error.
|
72,660,072 | 72,663,972 | How to get filename from __FILE__ and concat with __LINE__ at compile time | I'm trying to concat filename and line without path at compile time. Like /tmp/main.cpp20 -> main.cpp:20
#include <array>
#include <iostream>
using namespace std;
#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#define LINE_STRING STRINGIZE(__LINE__)
constexpr const char* file_name(const char* path) {
const char* file = path;
while (*path) {
if (*path++ == '/') {
file = path;
}
}
return file;
}
constexpr std::size_t str_size(const char* str) {
auto i = str;
while (*i != '\0') ++i;
const auto length = i - str;
return length;
}
template <std::size_t N1, std::size_t N2>
constexpr std::array<char, N1 + N2 + 2> formatFilename(const char* name,
const char* line) {
auto total_size = N1 + N2 + 2;
std::array<char, N1 + N2 + 2> res{};
std::size_t i = 0;
for (; i < N1; ++i) {
res[i] = name[i];
}
res[i++] = ':';
for (int j = 0; j < N2; ++j) {
res[i + j] = line[j];
}
res[total_size - 1] = '\0';
return res;
}
int main() {
constexpr char *p = &(
formatFilename<str_size(file_name(__FILE__)), str_size(LINE_STRING)>(
file_name(__FILE__), LINE_STRING)[0]);
cout << p << endl;
}
But it seems not work and return a compilation error
main.cpp: In function βint main()β:
main.cpp:46:46: error: call to non-βconstexprβ function βstd::array<_Tp, _Nm>::value_type& std::array<_Tp, _Nm>::operator[](std::array<_Tp, _Nm>::size_type) [with _Tp = char; long unsigned int _Nm = 12; std::array<_Tp, _Nm>::reference = char&; std::array<_Tp, _Nm>::value_type = char; std::array<_Tp, _Nm>::size_type = long unsigned int]β
Is there any way to do it at compile time?
| For your specific case (getting the filename without path and the line number) there are a few easier approaches that you might want to use:
1. Using __FILE_NAME__ instead of __FILE__
Both gcc and clang support the __FILE_NAME__ macro, that just resolves to the filename instead of the full file path.
clang builtin macros
gcc common macros
Utilizing those you can write it as a single macro:
#define STRINGIFY(x) STRINGIFY_IMPL(x)
#define STRINGIFY_IMPL(x) #x
#define FILENAME __FILE_NAME__ ":" STRINGIFY(__LINE__)
// Usage:
constexpr char* foo = FILENAME;
std::cout << foo << std::endl;
msvc unfortunately doesn't offer the __FILE_NAME__ macro, but you could utilize the /FC compiler switch to specify if you want the full path for __FILE__ or just the filename.
--
2. Let the compiler do the string concatenation
Adjacent character sequences are automatically combined by the compiler - e.g. "a" "b" "c" would be combined into "abc".
You can use this to let the compiler do the concatenation for you.
After that we can just increment the pointer to that combined string past the last slash to trim off the path:
#define STRINGIFY(x) STRINGIFY_IMPL(x)
#define STRINGIFY_IMPL(x) #x
#define FILENAME __FILE__ ":" STRINGIFY(__LINE__)
constexpr const char* filename_without_path(const char* path) {
const char* result = path;
while(*path != '\0')
if(*path++ == '/') result = path;
return result;
}
// Usage:
constexpr const char* foo = filename_without_path(FILENAME);
std::cout << foo << std::endl;
|
72,660,983 | 72,661,891 | Nearest Neigbor Search - Find which values are out of place based on position | I am currently working on a program in C++ which analyzes positions detected in the current frame compared to the last frame. In the case where one or more position is detected in the current frame, I need to estimate which objects are new. To do this, I can't simply find which values are the furthest from all other values as it isn't accurate enough.
Example:
vector<float> currentFramePosition = {0.08, 0.19, 0.22, 0.56, 0.7, 0.9};
vector<float> lastFramePosition = {0.09, 0.23, 0.52, 0.8, 0.98};
In this example, we can see that there is one new value. If we assume the value that is the furthest away from the last frame's values we get that the new value is the 0.7 at the 4th index. If we look at it objectively the new value should be 0.19 if we want to minimize the total distance. If we match 0.19 with 0.23, 0.22's closest value will be 0.52 and that distance is bigger than the distance between 0.7 and 0.8.
There can be more than one new value in each frame.
Is there a way to find which values are new without the function being too time complex?
Thanks!
| One way of solving this would be to frame it as a minimum-weight bipartite matching problem. Specifically, youβre trying to pair off items in the old frame with items in the new frame in a way that minimizes the total distance between the matched points. There are many standard algorithms for solving this problem in a reasonable amount of time. The Hungarian algorithm is probably the most famous, but you should be able to find an existing set of efficient libraries that will compute minimum-weight bipartite matchings.
|
72,661,534 | 72,661,632 | Is throwing a temporary value as reference undefined behavior? | To my surprise, std::runtime_error only has a const std::string& constructor, but no value constructor. Thus I am wondering if throw std::runtime_error("Temporary" + std::to_string(100)); is defined. After all we are creating an exception object that refers to a temporary object inside the scope of a function that immediately exits (as we throw out of it). Further investigation showed that while returning a constant reference to a temporary value immediately causes a segfault on my system, throwing one doesn't:
const std::string& undefined_behavior() {
return "Undefined " + std::to_string(1);
}
void test() {
throw std::runtime_error("Hello : " + std::to_string(2));
}
void test2() {
const std::string& ref = "Hello : " + std::to_string(3);
throw ref;
}
int main(int argc, char** argv) {
//std::cout << undefined_behavior() << std::endl;
try {
test();
} catch(const std::runtime_error& ex) {
std::cout << ex.what() << std::endl;
}
try {
test2();
} catch(const std::string& ref) {
std::cout << ref << std::endl;
}
}
On my system, undefined_behavior() crashes immediately but test() and test2() run fine.
While I know the call to undefined_behavior() is undefined behavior, is test() and test2() undefined? If not, do thrown values get a specfied treatment?
And if they are all undefined but happened to work on my computer by accident, what is the proper way to throw an exception with a variable message?
| The const std::string& constructor doesn't cause the exception object to store a reference to the passed std::string. std::runtime_error will make an internal copy of the passed string (although the copy will be stored in an usual way, probably reference-counted in an allocation external to the exception object; this is to give better exception guarantees when the exception object is copied, which the standard requires).
A function taking a const lvalue reference doesn't usually mean that it takes ownership or stores a reference to the object.
Prior to C++11 there was no reason to not use a const reference here, since it was always more efficient than passing by-value. With C++11 move semantics that changed and it is true that usually these kind of constructors had rvalue reference variants added with C++11, so that passing a temporary std::string object to the constructor would allow more efficient move-construction instead of copy-construction.
My guess is that this simply never was done for the exception classes because the performance of their construction should not be important in comparison to the overhead of actually throwing the exception.
So in test()'s case a temporary string object is created from the + operation, which is passed to the constructor and the exception object will make a copy of it. After the initialization of the exception object the temporary string is destroyed, but that is not a problem, since the exception object stores/references a copy.
In test2() the same would apply if you had written throw std::runtime_error(ref). However, here a reference is bound immediately to the temporary object materialized from the return value of +. This causes its lifetime to be extended to that of the reference variable. Therefore again, the temporary lives long enough for the std::runtime_error to make a copy from it.
But since you write simply throw ref that is not exactly what happens. throw ref will throw a std::string, because that is the type of the ref expression. However, throw doesn't actually use the object referenced by the expression as exception object. The exception object is initialized from the operand of the throw expression. So here, the exception object will be another std::string object (in unspecified storage) which will be initialized from the temporary that ref refers to.
undefined_behavior() has undefined behavior when the return value is used, because the temporary std::string object materialized from the + return value and which the return value of undefined_behavior() references is not lifetime-extended. Although it is again immediately bound by a reference, the lifetime-extension rule specifically doesn't apply to objects bound to a reference in a return value initialization. Instead the temporary is destroyed when the function returns, causing the function to always return a dangling reference.
|
72,661,625 | 72,661,795 | Pybind11 - Function with unknown number of arguments | I want to get a list of arguments
my current c++ code:
m.def("test", [](std::vector<pybind11::object> args){
return ExecuteFunction("test", args);
});
my current python code:
module.test(["-2382.430176", "-610.183594", "12.673874"])
module.test([])
I want my python code to look like this:
module.test("-2382.430176", "-610.183594", "12.673874")
module.test()
How can I get all arguments passed through Python?
| Such generic functions module.test(*args) can be created using pybind11:
void test(py::args args) {
// do something with arg
}
// Binding code
m.def("test", &test);
Or
m.def("test", [](py::args args){
// do something with arg
});
See Accepting *args and **kwargs and the example for more details.
|
72,661,799 | 72,661,937 | Makefile only using the first entry of wildcard | I just got into Makefiles and I have a problem when turning the .cpp files in .o files. The list of files to be used are defined as the following:
# Directories
BIN_DIR = bin
SRC_DIR = src
ICD_DIR = include
OBJ_DIR = $(BIN_DIR)/obj
# Files
SOURCES := $(wildcard $(SRC_DIR)/*.cpp)
OBJECTS := $(SOURCES:$(SRC_DIR)/%.cpp=$(OBJ_DIR)/%.o)
EXECUTABLE = main
If I @echo the files, I have what I want:
SOURCES
src/main.cpp src/random_graph.cpp src/word_graph.cpp
OBJECTS
bin/obj/main.o bin/obj/random_graph.o bin/obj/word_graph.o
To compile my program I have the following two functions:
# Make executables from objects
$(BIN_DIR)/$(EXECUTABLE): $(OBJECTS)
$(CXX) $(CXXFLAGS) $^ -o $@
@echo "Build successful!"
# Make objects
$(OBJECTS): $(SOURCES)
mkdir -p $(@D)
$(CXX) $(CXXFLAGS) -c $< -o $@
The problem is, when making the object files, I want to link src/main.cpp -> bin/obj/main.o, src/random_graph.cpp -> bin/obj/random_graph.o and src/word_graph.cpp -> bin/obj/word_graph.o, but it links src/main.cpp to each if the object files (making 3 copies).
Is there a way to link each .cpp file to the object .o file with the same name?
| I suggest that you create a pattern to build a single object file:
$(BIN_DIR)/$(EXECUTABLE): $(OBJECTS)
$(CXX) $(CXXFLAGS) -o $@ $(OBJECTS)
bin/obj/%.o : src/%.cpp | $(OBJ_DIR)
$(CXX) $(CXXFLAGS) -c $< -o $@
$(OBJ_DIR):
mkdir -p $(OBJ_DIR)
Since $(BIN_DIR)/$(EXECUTABLE) requires all object files, they will all be built using the above bin/obj/%.o and each object file also depends on the corresponding source file, so any change you make to that source file will cause a rebuild of the object file.
You can also move out the creation of $(OBJ_DIR) like above. It's unnecessary to try to create it if it already exists.
|
72,662,023 | 72,663,521 | LoadString returns empty string | I want to store positions of some objects in resource file and I've decided to store it in STRINGTABLE resource, because I couldn't find better type.
My resource file:
#include "resource.h"
// POSITIONS_ID = 10 defined in resource.h
STRINGTABLE
{
POSITIONS_ID "100 100 \
200 350 \
400 800"
}
I've tried to get this string differently, but the problem is the same
One of my attempts:
char* data = new char[100];
int length = LoadStringA(NULL, POSITIONS_ID, data, 100); // length = 0
cout << GetLastError() << endl // out 0, so there aren't any errors
// but data = "\0"
I've also tried to use wchar_t as type of data with LoadStringW function, but result is the same. I've tried GetModuleHandle(NULL) instead of NULL too.
I don't understand what is wrong.
Some more information:
HRSRC r = FindResource(Null, MAKEINTRESOURCE(POSITIONS_ID), RT_STRING) // return 0;
cout << GetLastError() << endl; // return 1814(The specified resource name cannot be found in the image file.)
So problem is that resource can't be found, but I still don't understand why.
| In "resource.h" file I defined POSITIONS_ID this way #define POSTIONS_ID 0010 to make defines look better, but for some reason leading zeros mustn't be used in resource ids.
Also I've find out, that when I use FindResource with type RT_STRING, I am looking for STRINGTABLE resource, that contains up to 16 string, so I have to use function this way FindResource(NULL, MAKEINTRESOURCE(POSITIONS_ID / 16 + 1), RT_STRING).
Thank everyone for help.
|
72,662,468 | 72,666,184 | Outside of using volatile, how can I assure that I'm querying the latest value from memory? | I understand that the compiler may choose to hold a value in cache, and that I can ensure that it reads the latest value from memory every time by using volatile, but are there other ways I can ensure that the latest value is being read without adding a type qualifier?
|
Outside of using volatile, how can I assure that I'm querying the latest value from memory?
You can't be assured that you're actually accessing memory, at least not in a portable way. Even if you use std::atomic or atomic variables (e.g. atomic_int in C) there is no guarantee that the value will come from to memory and not cache.
There are 4 cases:
it's not atomic, so there's no guarantee at all
it is atomic and the target platform isn't cache coherent (e.g. some ARM CPUs) and the compiler probably had to ensure the data came from memory as it's the only way to ensure atomicity.
it is atomic and the target platform is cache coherent (e.g. 80x86 CPUs) and therefore you probably have no reason to care if the data came from cache or memory in the first place
you actually do care if the data came from cache or memory (e.g. you're writing a tool to benchmark RAM bandwidth, or test for faulty RAM). In this case you're going to have to resort to non-portable tricks - exploiting target specific cache eviction policy, using inline assembly, asking the OS to make the memory "uncached", etc.
|
72,662,728 | 73,032,981 | How to manipulate images in SFML? | I need to implement a class (inherited from sf::Image) that allows me to find 'distance' between two images. By that I mean a measure of how the images differ from each other pixel by pixel (the specifics don't matter). The main idea is to take an image, draw something on it and look at how much it changed. To draw something I need to convert my image into an sf::RenderTexture (probably?). The problem is that I can't draw on sf::RenderTexture inside of a class (only in the main loop directly), it just shows me an empty dark blue background for some reason. How can I fix that?
| You really shouldn't derive from sf::Image (see also Composition over Inheritance).
To go from a sf::RenderTexture to an sf::Image you can use renderTexture.getTexture().copyToImage(), but keep in mind that requires transferring of data from the GPU's VRAM to the CPU's RAM and as such it can be rather slow, meaning you may not want to do that every frame, but only when you need it.
To then compare images, you can access the pixel information with getPixelsPtr() on the sf::Image instance.
Don't hesitate to check out the official documentation on how to use sf::Image or sf::RenderTexture.
|
72,663,001 | 72,663,085 | Why does this example involving std::accumulate compile (badly), and how to guard against misuse? | Surprinsingly (for me), this compiles:
std::vector<int> v;
std::accumulate(std::cbegin(v), std::cend(v), 0, [](double sum, auto i){
return sum + 0.1;
});
(gcc 12 with --std=c++20a)
This is bad, because if I look at the signature of std::accumulate, it returns what's passed in the init argument, which in my case is the integer 0. But obviously, the passed lambda works with (takes and returns) doubles. So there must be some double to int coercion happening somewhere, that the compiler, surprinsingly, allows.
To ensure proper behavior, my code now reads std::accumulate(std::cbegin(v), std::cend(v), 0.0,..., (notice the 0.0). But this is unsatisfactory because next time when I'm less careful, I will write just 0 not 0.0.
I would like to know why does GCC allow this and is there a way (I suspect a compiler flag) to prevent this from compiling?
| This is the defined behavior of std::accumulate. It will initialize the accumulator with the initial value provided and take on its type. Then it will repeatedly add new values with the accumulator, always assigning the intermediate results to the accumulator object. The assignment coerces the double result of the lambda into a int (the type of the accumulator). This is allowed, because C++ always allows implicit double-to-int conversion. Similarly while adding, the current value of the accumulator will be implicitly converted to double to fit the lambda's parameter.
std::accumulate is not defined to perform any check on the types so that no such conversion happens. If you want that, you will need to write your own wrapper around std::accumulate enforcing these constraints, for example:
// doesn't cover some edge cases
// prevents only conversion in the accumulator assignment
// not in the `op` arguments
template<typename It, typename T, typename O>
T my_accumulate(It first, It last, T init, O op) {
static_assert(std::is_same_v<decltype(op(std::move(init), *first)), T>, "Incompatible init type!");
return std::accumulate(first, last, init, op);
}
The lambda may also be used to enforce stricter typing in various ways. The comments under the question list some possibilities:
Use double& instead of double as type. This enforces that the accumulator has type double, because otherwise the reference cannot bind to it. However, const double& or double&& won't work, since these are allowed to bind to temporaries, which would again be created implicitly.
Declare the type as auto instead of double. This will guarantee that the type is deduced to the type of the accumulator. Then static_assert with std::is_same that it is deduced to double.
(Since C++20) Declare the type as std::same_as<double> auto instead of double which has the same effect as above, but instead of a hard failure during instantiation it will cause overload resolution on the lambda to fail due to constrain violation.
As far as I know there is no warning flag in common compilers that could warn about this, because the conversion happens in an implicit instantiation from a template, where e.g. the -Wconversion flag and similar warning flags are usually not applied to avoid too much noise.
|
72,663,242 | 72,663,288 | C++ ofstream write in file from input, without new line after each word | Basically I have a function, that writes into a .txt file.
The user has to input, what will be written in the file.
The problem is, every word has a new line, even tho it's written in the same line, while doing the input.
But I want it to be the way the user inputs it.
void Log_Write::WriteInLog(std::string LogFileName)
{
system("cls");
std::string input;
std::ofstream out;
out.open(LogFileName, std::fstream::app);
out << "\n\nNEW LOG ENTRY: " << getCurrentTime()<<"\n"; //
while (true)
{
system("cls");
std::cout << "Writing in Log\n\nType 'x' to leave editor!\n\nInsert new entry: ";
std::cin >> input;
if (input == "x")
break;
out << input << "\n"; // How do I change this so it doesn't create a new line for each word
}
out.close();
}
Sample Input:
1st Input:Test Input
2st Input:Next input
Sample Output in file.txt:
Test
Input
Next
Input
(Without the spaces in between!)
| std::cin >> input; just reads to the first whitespace while std::getline(std::cin, input); would read the whole line.
One way of fixing it:
while(
system("cls"),
std::cout << "Writing in Log\n\nType 'x' to leave editor!\n\nInsert new entry: ",
std::getline(std::cin, input)
) {
if (input == "x")
break;
out << input << '\n';
}
I put the std::getline call last in the while condition to make the loop exit if std::getline fails.
Now, the above looks pretty nasty so I suggest putting clearing the screen and prompting the user in a separate function instead.
Example:
#include <iostream>
#include <string>
#include <string_view>
std::istream& prompt(std::string_view prompt_text, std::string& line,
std::istream& in = std::cin,
std::ostream& out = std::cout) {
std::system("cls");
out << prompt_text;
std::getline(in, line);
return in;
}
void Log_Write::WriteInLog(std::string LogFileName) {
// ...
auto prompt_text = "Writing in Log\n\n"
"Type 'x' to leave editor!\n\n"
"Insert new entry: ";
while (prompt(prompt_text, input)) {
if (input == "x") break;
out << input << '\n';
}
}
|
72,663,249 | 72,663,990 | find out if cursor had been set in ncurses.h | I'm creating a wrapper for menu.h and want to ensure that when a menu is displayed, the cursor is turned off, however I don't want to just do a
curs_set(0);
and potentially screw up some other ui that depends on a certain cursor setting...
TLDR: is there any way to find out the current setting of curs_set?
| It's in the manual page:
The curs_set routine sets the cursor state to invisible, normal, or
very visible for visibility equal to 0, 1, or 2 respectively. If the
terminal supports the visibility requested, the previous cursor state
is returned; otherwise, ERR is returned.
|
72,663,370 | 72,664,851 | Allow Only Explicit Specialization of Template Class | I want to limit a template class to the only explicit implementations. I can do this with many functions as:
template<typename T>
static T getEnumFromString(const std::string& in_string) = delete; // only allow templates we define (catches them at compile time)
template<> static A getEnumFromString(const std::string& in_string);
template<> static B getEnumFromString(const std::string& in_string);
I have a template class, that stores enum/string in maps, where I use a static_assert to limit to only enums, but this is not limiting enough due to enums visible (only want those defined in enclosing class):
template<typename TEnum>
class kvEnumHelper {
static_assert(std::is_enum_v<TEnum>);
public:
std::string getStringFromEnum(const TEnum& in_enum) const;
TEnum getEnumFromString(const std::string& in_string) const;
protected:
kvEnumHelper();
void initialize(std::vector<EnumTextPair<TEnum>> enumInitializer);
private:
std::map<TEnum, std::string> mapEnumToString;
std::map<std::string, TEnum> mapStringToEnum;
};
I implement explicit class for each enum, (where the enum/string pairs are defined in the constructor) e.g.:
class AenumHelper : public kvEnumHelper<tA> {
using myEnum = tA;
public:
AenumHelper();
};
inline static AenumHelper aEnumHelper;
The issue is that the static assert is insufficient, as there are many other enums in scope that do not apply here. I have tried permutations like:
template<typename TEnum> kvEnumHelper<TEnum> = delete;
template<typename TEnum> class kvEnumHelper<TEnum> = delete;
template<> class kvEnumHelper<> = delete;
kvEnumHelper = delete;
//
Is there a way, similar to the function case, to allow explicit specialization for my kvEnumHelper<> class?
| There are a few ways how you could accomplish this.
1. Explicitly list the acceptable enums
One way would be to explicitly list the acceptable enums in your static_assert:
godbolt
#include <type_traits>
template<class T, class... Other>
constexpr bool is_same_one_of = (std::is_same_v<T, Other> || ...);
enum Enum1 {};
enum Enum2 {};
enum Enum3 {};
template<class T>
class kvEnumHelper {
static_assert(
is_same_one_of<T, Enum1, Enum2 /* , ... more enum types ... */>,
"T must be either Enum1 or Enum2"
);
/* ... actual implementation ... */
};
kvEnumHelper<Enum1> foo1; // ok
kvEnumHelper<Enum2> foo2; // ok
kvEnumHelper<Enum3> foo3; // compile error
2. Inherit implementation
Another option would be to move the actual implementation into a separate class and only make the specializations inherit from the implementation class.
godbolt
#include <type_traits>
enum Enum1 {};
enum Enum2 {};
enum Enum3 {};
template<class T>
class kvEnumHelper {
static_assert(
!std::is_same_v<T, T>, // always false, but only when actually instanciated
"Enum Class is not supported"
);
};
template<class TEnum>
class kvEnumHelperImpl {
/* ... actual implementation ... */
};
template<> class kvEnumHelper<Enum1> : public kvEnumHelperImpl<Enum1> {};
template<> class kvEnumHelper<Enum2> : public kvEnumHelperImpl<Enum2> {};
kvEnumHelper<Enum1> foo1; // ok
kvEnumHelper<Enum2> foo2; // ok
kvEnumHelper<Enum3> foo3; // compile error
3. Using an additional trait
Yet another alternative would be to use a trait that can specialized for the enum types you would want to be usable with kvEnumHelper.
godbolt
template <class T>
constexpr bool allow_enum_helper = false;
enum Enum1 {};
enum Enum2 {};
enum Enum3 {};
template<class T>
class kvEnumHelper {
static_assert(
allow_enum_helper<T>,
"Enum Class is not supported"
);
/* ... actual implementation ... */
};
template<>
constexpr bool allow_enum_helper<Enum1> = true;
template<>
constexpr bool allow_enum_helper<Enum2> = true;
kvEnumHelper<Enum1> foo1; // ok
kvEnumHelper<Enum2> foo2; // ok
kvEnumHelper<Enum3> foo3; // compile error
If you already have a function like getEnumFromString that is deleted and has specializations for the allowable enum types you could use that to detect if kvEnumHelper<T> should be allowed by detecting if the function is deleted or not.
godbolt
#include <string>
enum Enum1 {};
enum Enum2 {};
enum Enum3 {};
template<typename T>
T getEnumFromString(const std::string& in_string) = delete; // only allow templates we define (catches them at compile time)
template<> Enum1 getEnumFromString(const std::string& in_string);
template<> Enum2 getEnumFromString(const std::string& in_string);
template<class T>
constexpr bool allow_enum_helper = requires { getEnumFromString<T>(std::string{}); };
template<class T>
class kvEnumHelper {
static_assert(
allow_enum_helper<T>,
"Enum Class is not supported"
);
/* ... actual implementation ... */
};
kvEnumHelper<Enum1> foo1; // ok
kvEnumHelper<Enum2> foo2; // ok
kvEnumHelper<Enum3> foo3; // compile error
|
72,664,029 | 72,664,101 | MSVC vs Clang/GCC bug during overload resolution of function templates one of which contains a parameter pack | I was using parameter pack when I noticed that one such case(shown below) compiles fine in gcc and clang but not in msvc:
template<class T> void func(T a, T b= T{})
{
}
template<class T, class... S> void func(T a, S... b)
{
}
int main()
{
func(1); // Should this call succeed?
}
Here is the link for verifying the same: https://godbolt.org/z/8KsrcnMez
As can be seen the above program fails in msvc with the error message:
<source>(13): error C2668: 'func': ambiguous call to overloaded function
<source>(6): note: could be 'void func<int,>(T)'
with
[
T=int
]
<source>(2): note: or 'void func<int>(T,T)'
with
[
T=int
]
<source>(13): note: while trying to match the argument list '(int)'
But the same compiles fine with gcc and clang.
Which compiler(s) is right here?
| MSVC is right in rejecting the code. According to temp.func.order#5.example-2 the call func(1) is ambiguous. The example given in the standard is as follows:
Note: Since, in a call context, such type deduction considers only parameters for which there are explicit call arguments, some parameters are ignored (namely, function parameter packs, parameters with default arguments, and ellipsis parameters).
template<class T > void g(T, T = T()); // #3
template<class T, class... U> void g(T, U ...); // #4
void h() {
g(42); // error: ambiguous
}
This means that in the example in question, the call func(1) is ambiguous as well.
Errata
Note that cppreference has errata in below given example:
template<class T>
void g(T, T = T()); // #1
template<class T, class... U>
void g(T, U...); // #2
void h()
{
g(42); // calls #1 due to the tie-breaker between parameter pack and omitted parameter
}
As can be seen in the above example, cpprefernce incorrectly says that the first overload #1 should be choosen.
This has been fixed in recent edit that i made.
|
72,664,301 | 72,664,686 | How to make Tensorflow-lite available for the entire system in Ubuntu | My tflite directory is as follows:
/home/me/tensorflow_src/tensorflow/lite/
However, I fail to import it in my C++ project:
#include "tensorflow/lite/interpreter.h" // getting a not found error
How can I add resolve this error? My assumption is that I'd need to add the tflite to my bash to make it available for all of my projects. How can I add tflite to the bash file?
This is my CMAKE file:
cmake_minimum_required(VERSION 3.22)
project(mediafile_device_crossverification)
set(CMAKE_CXX_STANDARD 17)
set(OpenCV FOUND 1)
find_package(OpenCV REQUIRED)
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable(mediafile_device_crossverification main.cpp src/VideoProcessing.cpp src/VideoProcessing.h)
| There are various options:
First option: Install/copy the tensorflow header files to e.g. /urs/local/include that folder is usually in the system include path by default.
Second option: GCC has some environment variables that can be used to modify the system include path. C_INCLUDE_PATH and CPLUS_INCLUDE_PATH, your can add them to .bashrc to set them when you login. See: https://gcc.gnu.org/onlinedocs/cpp/Environment-Variables.html
Third option is to add /home/me/tensorflow_src to the include path in the CMakefile.
When searching the include path #include <tensorflow/lite/interpreter.h> should be used.
|
72,665,022 | 72,665,125 | Lib SDL C++ Why wont my app compile with -static and libc | I am trying to learn how to use SDL and I've been trying to get my app to run on other systems. when I try to compile using g++ -I src/include -L src/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2 -static-libgcc -static-libstdc++ -static I get a massive bunch of SDL errors saying undefined and the app doesn't finish compiling. However when running without -static it will compile but not include libc. How would I fix this issue while still being able to run on other systems without them installed?
I am also using MinGW-w64 for GCC
| You're missing some flags. Running pkg-config --libs --static sdl2 will tell you the right flags.
If you don't have pkg-config installed (you could get it from MSYS2), you can look up the flags manually in the file called sdl2.pc, which is shipped with SDL2.
For me this command prints -L/mingw64/lib -lSDL2main -lmingw32 -lSDL2main -lSDL2 -mwindows -lmingw32 -ldinput8 -lshell32 -lsetupapi -ladvapi32 -luuid -lversion -loleaut32 -lole32 -limm32 -lwinmm -lgdi32 -luser32 -lm -Wl,--no-undefined -lmingw32 -lSDL2main -lSDL2 -mwindows.
You also need -static, even though it doesn't appear in the output. You can remove -static-libgcc -static-libstdc++, since they're implied by -static.
|
72,665,285 | 72,665,331 | Nested Classes with Template | I'm having issues using a nested class with a template. The first snippet is provided, I just have to implement it.
template <typename T>
class a {
public:
class b {
public:
func();
I thought the implementation would look something like this, but it isn't working.
template<typename T>
a<T>::b<T>::func(){}
| There's not much wrong with your start. You just need to to tie it together.
template <typename T>
class a {
public:
class b {
public:
void func(); // return type missing
}; // missing
}; // missing
template <typename T>
void a<T>::b ::func() {}
// ^ not <T>
Demo
|
72,665,491 | 72,692,573 | How to convert for loop matrix multiplication using Eigen C++: incorrect results | I have the following for loop that works:
static const int ny = 10;
std::vector<double> ygl(ny+1);
double *dVGL;
dVGL = (double*) fftw_malloc(((ny+1)*(ny+1))*sizeof(double));
memset(dVGL, 42, ((ny+1)*(ny+1))* sizeof(double));
double *dummy1;
dummy1 = (double*) fftw_malloc(((ny+1)*(ny+1))*sizeof(double));
memset(dummy1, 42, ((ny+1)*(ny+1))* sizeof(double));
double *dummy2;
dummy2 = (double*) fftw_malloc(((ny+1)*(ny+1))*sizeof(double));
memset(dummy2, 42, ((ny+1)*(ny+1))* sizeof(double));
for (int i = 0; i < ny+1; i++){
for (int j = 0; j < ny+1; j++){
ygl[j] = -1. * cos(((j) * EIGEN_PI )/ny);
dummy1[j + ny*i] = 1./(sqrt(1-pow(ygl[j],2)));
dummy2[j + ny*i] = 1. * (i);
dVGL[j + ny*i] = dummy1[j + ny*i] * sin(acos(ygl[j]) * (i)) * dummy2[j + ny*i];
}
}
The above works fine, now I convert to Eigen and I am getting off results:
Eigen::Matrix< double, 1, ny+1> v1;
v1.setZero();
std::iota(v1.begin(), v1.end(), 0);
Eigen::Matrix< double, ny+1, ny+1> dummy1;
dummy1.setZero();
Eigen::Matrix< double, ny+1, ny+1> dummy2;
dummy2.setZero();
for (int j = 0; j < ny+1; j++){
v[j] = 1./(sqrt(1-pow(ygl[j],2)));
}
dummy1 = v.array().matrix().asDiagonal(); //this is correct
dummy2 = v1.array().matrix().asDiagonal(); //this is correct
Eigen::Matrix< double, ny+1, ny+1> dVGL;
dVGL.setZero();
for (int i = 0; i < ny+1; i++){
for (int j = 0; j < ny+1; j++){
ygl[j] = -1. * cos(((j) * EIGEN_PI )/ny);
dVGL(j + ny*i) = sin(acos(ygl[j]) * (i)); //this is correct
}
}
//##################################
dv1 = (dummy1) * (dVGL) * (dummy2); //this is incorrect, dVGL outside for loop is different from inside for loop!!
I have been wracking my brain for a week now over this I cannot seem to fix it. why is dVGL out side the for loop is different?? (off as if my rows and columns have length ny+1, but When I flatten my array I am using just ny.) why is that?
I feel like this should be a simple issue.
| Thanks to @chtz in the comments, I was able to fix this problem simply by changing my indexing:
dVGL(j + (ny+1)*i) = sin(acos(ygl[j]) * (i));
dv1 = (dummy1) * (dVGL) * (dummy2); //Then this is correct
|
72,665,745 | 72,666,095 | vkCreateRenderPass returns invalid pointer | I am creating a render pass like so
const bool createRenderPass() {
VkAttachmentDescription colorAttachment{};
colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
VkSubpassDependency dependency{};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
printf("%s\n\r", "failed to create render pass!");
return false;
}
return true;
};
However when I run it renderPass results in an invalid pointer: 0xe000000000e
Up to this stage, each stage of the render pipeline, (i.e, instance/device/swapchain/imageview creation) has been valid. So what is going wrong with the renderPass?
|
However when I run it renderPass results in an invalid pointer: 0xe000000000e
There are two types of handle returned by Vulkan functions:
dispatchable:
Dispatchable handle types are a pointer to an opaque type. This pointer may be used by layers as part of intercepting API commands, and thus each API command takes a dispatchable type as its first parameter.
non-distpatchable:
Non-dispatchable handle types are a 64-bit integer type whose meaning is implementation-dependent.
VkRenderPass is defined as a non-distpatchable handle. There's no reason to look at the value and consider it as anything other than a 64 bit value. Whether or not it's a valid memory pointer is completely irrelevant.
You say in the comments that the function returns VK_SUCCESS and the validation layers don't report anything wrong. So what is the problem? If you're still having a problem rendering, it's likely not the render pass object, but something else.
|
72,665,889 | 72,665,921 | Is it possible to initialize a enumeration data member inside constructor? | I have 2 questions
Is enumeration constant of int datatype?
For class Card, do I create two data member of enum type Face and Suit and then initialize it via the constructor?
Background:
9.23 (Card Shuffling and Dealing) Create a program to shuffle and deal a deck of cards. The
program should consist of class Card, class DeckOfCards and a driver program. Class Card should
provide:
a) Data members face and suitβuse enumerations to represent the faces and suits.
b) A constructor that receives two enumeration constants representing the face and suit
and uses them to initialize the data members.
c) Two static arrays of strings representing the faces and suits.
d) A toString function that returns the Card as a string in the form βface of suit.β You
can use the + operator to concatenate strings.
Class DeckOfCards should contain:
a) An array of Cards named deck to store the Cards.
b) An integer currentCard representing the next card to deal.
c) A default constructor that initializes the Cards in the deck.
d) A shuffle function that shuffles the Cards in the deck. The shuffle algorithm should
iterate through the array of Cards. For each Card, randomly select another Card in the
deck and swap the two Cards.
e) A dealCard function that returns the next Card object from the deck.
f) A moreCards function that returns a bool value indicating whether there are more Cards
to deal.
This is from c++ how to program by deitel.
sorry, I am quite confused because I have never initialized scoped enum in class constructor before.
| An enumeration constant presumably is of an enum type: https://en.cppreference.com/w/cpp/language/enum .
Yes, depending on the kind enumeration, it can be converted to integers, sometimes the conversion makes sense (e.g. for the face value) but in some cases you want to stay away from it (e.g. for the suit value).
For the later enum class helps.
And yes, it seems that the exercise is pushing you into designing the Card class like that.
enum Suit { spades, clubs, hearts, diamonds };
enum Face { ace, two, three, ...};
class Card {
public:
Suit s;
Face f;
};
Finally, to answer the question on the title, you don't need a constructor because you can already do:
Card my_card{spades, two};
But otherwise, yes you can have a constructor that takes enums:
class Card {
...
Card(suit my_suit, face my_face) : s{my_suit}, f{my_face} {}
};
Note that this is where books go out their way to make you think that a certain thing should implemented in a certain way just because you have learned a new feature of the language.
This is not the only way to implement a Card class or more importantly a Card game application.
It depends a lot what you do with them later.
Specially what kind of "collections" you tolerate for the Cards class.
(A card in isolation is kind of meaningless.)
Think also if Cards should be copyable?, movable?, swappable? (or even mutable!?).
What about special values, is there a "blank card"? is there a "jack"?
How to ensure in the logic of the program that there are no duplicated flying around?
These are the real questions in the design of a class, IMO.
|
72,665,933 | 72,666,564 | Find size of glm::vec3 array | I have this glm::vec3 array and I would like to know the size of the array:
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
So far the size is 10 but is there a way to find that in code?
I have tried cubePositions->length() but it only gives me the value 3.
I have tried glm::length(cubePositions) but it doesn't seem like thats how you use the glm::length function. This way gives an error.
Thank you for any help!
| cubePositions is a C style array. It decays to a pointer to glm::vec3. See here about array to pointer decay: What is array to pointer decay?.
Therefore when you use cubePositions->length() it's equivalent to using cubePositions[0].length(), which returns the glm length of the first element (i.e. 3 because it's a vec3).
To get the number of elements in the array in this case you can use:
auto num_elements = sizeof(cubePositions) / sizeof(cubePositions[0]);
Note: this will work only in the scope where cubePositions is defined because only there the real size of the array is known. It will no longer work e.g. if you pass cubePositions to another function, because then the array will decay to a pointer and will "loose" it's sizeof.
However - this is not the recomended way to do it in C++.
It is better to use std::vector for a dynamic size array.
It has a method: size() to retrieve the number of elements:
#include <vector>
std::vector<glm::vec3> cubePositions = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
auto num_elements = cubePositions.size();
Note: if your array has a fixed size (known at compile time), you can also use std::array. It also has a size() method, although in this case it is not as useful, as the size cannot change dynamically and is actually one of the template parameters.
Update::
As @HolyBlackCat commented below, it is better to use std::size to get the number of elements in an old C array:
auto num_elements = std::size(cubePositions);
It will not compile if you pass a decayed pointer rather than a real array. Just keep in mind that as I wrote above you'd better avoid old C arrays if you can.
|
72,666,452 | 72,666,606 | Why doesn't memory blow up for an infinite pointer chain in C++? | Beginner question: In relation to this original question here, every variable we generate has a memory address to it, and the pointer holds that memory address. The pointer itself also has its own memory address. Why doesn't this recursively generate an infinite chain of memory-addresses that hold other memory-addresses until your memory (that holds all these memories) blow up, whenever you declare just a single variable? What am I missing here?
|
What am I missing here?
The names of the pointers.
An expression like &(&a) is not valid; there needs to be a name for an address before you can take the address again. (There are more precise ways to express that, but the more precise ways can also be more confusing at this stage.)
In the linked-to question, there is a variable with a name.
int a = 10;
This variable has a value (a) and an address (&a). However, the address is not itself necessarily stored in memory until it is given a name.
int *p = &a;
At this point, there is the value a, the address of that value (&a stored in p), and the address of a pointer to that value (&p). However, the address of p is not necessarily stored in memory until it is given a name.
int **q = &p;
And so on.
Yes, you could theoretically have an unbounded chain of these names, but each name is necessary. If you stop generating names, you stop getting things to take the address of. Even if you find a way to get the compiler to generate names for you (so you don't have to type each out, which would take forever), the compiler will stop generating those names once it hits one of its internal limits. So, possible in theory, but not in practice.
|
72,666,655 | 72,666,679 | Why when i add \ to cout it dosent display it on output | When I try to do printf("----/");, the \ is removed from the output
#include <iostream>
int main() {
std::cout << ("Welcome to the game\n\n");
printf("--------\n");
printf("----O---\n");
printf("---/|\--\n");
printf("---/-\--\n");
}
output:
--------
----0---
---/|--
---/---
| The answer has been given already: \ is special, because it's the escape character, and you need to escape it with itself if you want a literal \ in the outoupt.
This, however, can make the drawing confused.
To improve the things, you can use raw strings literals
printf(R"(--------
----O---
---/|\--
---/-\--)");
Notice that I've truly inserted a line break in place of the \n escape sequence, because \n would be literally interpreted as a \ followed by the letter n.
Clearly, you can still have issues, if a string contains exactly the characters )", because it will be detected as the closing token of the string:
// +---- code invalid from here
// |
// v
printf(R"(-----)"---)");
but you can still solve it, for instance by adding another set of wrapping "s:
printf(R""(-----)"---)"");
or anything else in between the " and (, and between ) and " (not symmetrized):
printf(R"xyz(-----)"---)xyz");
// ^
// |
// +--- not zyx
|
72,667,067 | 72,667,190 | The "sticks" variable cannot be re-assigned to 0 in C++14 | I am writing a program to resolve the request:
Count the number of match sticks used to create numbers in each test case
Although it is a simple problem, the thing that makes me quite confusing is that the program has no error but the output is not as expected.
Source Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char,int> digits={
{'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
};
map<char,int> peterMap;
int t; cin >> t;
string peterNum[t];
for(string &a:peterNum) cin >> a;
for(string b:peterNum){
int sticks = 0;
string tomNum, n;
for(char c:b) ++peterMap[c];
for(auto d:peterMap) sticks += d.second*digits[d.first];
cout << sticks << ' ';
}
return 0;
}
Input:
5 (Number of test cases)
1 0 5 10 15
Output:
2 8 13 21 28
Expected Output:
2 6 5 8 7
| There are 3 problems with your code
don't use <bits/stdc++.h>, it is non-standard and promotes bad practice.
variable-length arrays are not standard C++, use std::vector instead. But this is actually not necessary in this case, because...
peterMap is completely unnecessary and needs to be removed, it is screwing up your result.
Try this instead:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<char,int> digits = {
{'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
};
int t; cin >> t;
for (int i = 0; i < t; ++i) {
string a; cin >> a;
int sticks = 0;
for(char ch : a) sticks += digits[ch];
cout << sticks << ' ';
}
return 0;
}
Online Demo
|
72,667,689 | 72,668,526 | How to understand the type returned by the final overrider is implicitly converted to the return type of the overridden function that was called? | As per the document, which says that[emphasis mine]:
When a virtual function call is made, the type returned by the final overrider is implicitly converted to the return type of the overridden function that was called.
How to understand that in the right way?
According to the output of the demo code below, it seems that the type returned by the final overrider depends the static type of the instance (which the member function would be invoked on).
If I miss something, please let me know.
Here is the demo code snippet:
#include<iostream>
#include<typeinfo>
#define print() std::cout << __PRETTY_FUNCTION__ << std::endl;
class B {};
struct Base
{
virtual void vf1(){print();};
virtual void vf2(){print();};
virtual void vf3(){print();};
virtual B* vf4(){print();};
virtual B* vf5(){print();};
};
class D : private B
{
friend struct Derived; // in Derived, B is an accessible base of D
};
class A; // forward-declared class is an incomplete type
struct Derived : public Base
{
void vf1(){print();}; // virtual, overrides Base::vf1()
void vf2(int){print();}; // non-virtual, hides Base::vf2()
D* vf4(){print();}; // overrides Base::vf4() and has covariant return type
// A* vf5(){print();}; // Error: A is incomplete type
};
int main()
{
Derived d;
Base& br = d;
Derived& dr = d;
std::cout<<typeid(br.vf4()).name()<<std::endl; // calls Derived::vf4() and converts the result to B*
std::cout<<typeid(dr.vf4()).name()<<std::endl; // calls Derived::vf4() and does not convert the result to B*
B* p = br.vf4(); // calls Derived::vf4() and converts the result to B*
D* q = dr.vf4(); // calls Derived::vf4() and does not convert the result to B*
}
Here is the output:
P1B
P1D
virtual D* Derived::vf4()
virtual D* Derived::vf4()
|
the return type of the overridden function that was called.
Note the word choice. The function that was called, not the function that was executed. Your examples focus on executing the same function. The function that was called depends on how you place the call (compile time), not how the call is answered (run time).
For a reference ref of type A&, the expression ref.foo() is call to A::foo(). After the call is made, polymorphism may kick in and redirect execution to a different function, but this does not change what was called. You called A::foo(), but maybe it was B::foo() that answered the call. Virtual functions are tricky like that, covering for each other.
Do you mind? Not really. You are interested in results, not in who delivers them. As long as the function answering the call honors the contract made by A::foo(), all is fine. They can trade shifts if they wish.
In this story, the contract includes the type of the returned value. This cannot be messed with, or else the call stack gets corrupted. Unfortunately, there might be a covariant return type in play. Fortunately, B::foo() knows that if it is covering for A::foo(), it has to adapt to the current contract and throw in an implicit conversion gratis when it returns. It just goes without saying.
Still, B considers the conversion a downgrade. It's fine for the riffraff using A references. Let them have their inferior return value; the good stuff is reserved for those discriminating few who insist upon B references. These fine folks will call B::foo(), and the downgrade/conversion is skipped for them. Classy.
|
72,667,852 | 72,668,060 | Why does my concept not work if specifying two requirements | I have the following code:
#include <concepts>
#include <functional>
#include <iostream>
template<typename T>
concept OperatorLike = requires(T t, const std::string s) {
{ t.get_string(s) } -> std::same_as<const std::string>;
{ t.get_int(s) } -> std::same_as<const int>;
};
template<typename T, typename O>
concept Gettable = requires(T t, O op) {
t.apply_get(0, op);
t.apply_post(0, op); };
template<std::semiregular F>
class RestApiImpl {
F m_get_method;
public:
RestApiImpl(F get = F{}) : m_get_method{std::move(get)} {}
void register_get(F functor) {
m_get_method = std::move(functor);
}
template<OperatorLike IF>
requires std::invocable<F, const int, IF>
void apply_get(const int req, IF interface){
m_get_method(req, std::move(interface));
}
template<OperatorLike IF>
requires std::invocable<F, const int, IF>
void apply_post(const int req, IF interface){
m_get_method(req, std::move(interface));
}
};
class ASpecificJSONLibrary{
public:
std::string operator[](std::string key){
return key + "_withLambda";
}
};
class Server{
public:
ASpecificJSONLibrary libObj; // this is a
struct impl;
void run(Gettable<impl> auto& api){
api.apply_get(0, impl(*this));
}
struct impl {
public:
Server& m_server;
impl(Server& server ) : m_server(server){}
const std::string get_string(const std::string key) {
return (m_server.libObj)[key];
};
const int get_int(std::string const key) {
return 1;
}
};
};
int main(){
auto get = [](int, OperatorLike auto intf){
std::string dummy = "dummy";
std::cout << intf.get_string(dummy);
};
RestApiImpl api(get);
Server server;
server.run(api);
return 0;
};
If remove the line t.get_int(s) } -> std::same_as<int>; from the concept OperatorLike everything seems to work as it should. I am not sure why adding this additional requirement gives me a compile error. The compile error also refers only to the fact that the there is no matching function to the run method, which is because the Gettable concept is not satisfied. But the root cause looks like it is the OperatorLike concept
Another observation just made is that if I remove all the consts from the operatorLike concept it all just seem to work including the additional requirements
| The compound requirement
{ t.get_int(s) } -> std::same_as<const int>;
tests whether decltype((t.get_int(s))) is the same as const int. However, that is a pointless test, because there are no const prvalues of non-class type and these would be the only expressions for which decltype could result in const int.
A prvalue of non-class type will always have its const stripped. So even if get_int is declared to return const int, the type of the call expression t.get_int(s) will always be int, not const int.
In general having top-level const on a return type is almost always useless. The only use case I can think of is a class type return value for which you want to disallow calling non-const member functions without storing in a variable first, but there are better ways of achieving that (e.g. &-qualified member functions).
|
72,668,066 | 72,668,075 | mktime returns -1 but valid data | I try to find a way for a default date (if date is not valid).
Common way works fine:
set(2022,6,17,12,12,0,0,0)
void KTime::Set(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nDST, bool isUTC)
{
assert(nYear >= 1900);
assert(nMonth >= 1 && nMonth <= 12);
assert(nDay >= 1 && nDay <= 31);
assert(nHour >= 0 && nHour <= 23);
assert(nMin >= 0 && nMin <= 59);
assert(nSec >= 0 && nSec <= 59);
struct tm atm;
atm.tm_sec = nSec;
atm.tm_min = nMin;
atm.tm_hour = nHour;
atm.tm_mday = nDay;
atm.tm_mon = nMonth - 1; // tm_mon is 0 based
atm.tm_year = nYear - 1900; // tm_year is 1900 based
atm.tm_isdst = nDST;
m_time = isUTC ? utc_mktime(&atm) : mktime(&atm);
assert(m_time != -1); // indicates an illegal input time
}
But if I set to the same function:
set(1900,1,1,0,0,0,0,0)
I will get a mktime = -1
Any idea where is my logic bomb?
| mktime (and the rest of the POSIX date functions) only work for dates >= 1970-01-01 00:00:00, the UNIX epoch.
mktime, quoth the manual,
returns -1 if time cannot be represented as a time_t object
and 1900 definitely can't be represented as a time_t, since it's 70 years early.
|
72,668,467 | 72,668,583 | Transform variadic type list to tuple of pairs | Is the following type transformation possible:
T1, T2, T3, T4, ...., T2n-1, T2n
---> transform to --->
tuple<
pair<T1, T2>,
pair<T3, T4>,
...,
pair<T2n-1, T2n>
>
Such a meta-function
template <class... Args>
using split_in_pairs_t = ???
would be used like so:
template <class... Args>
class UseCase
{
split_in_pairs_t<Args...> _tupleOfPairs;
};
A non-recursive solution would be preferable.
| Make an index sequence of half the size, and pair elements 2*i, 2*i+1 together:
template <class...> struct pairwise_impl;
template <class... Args, size_t... Is>
struct pairwise_impl<std::tuple<Args...>, std::index_sequence<Is...>>
{
using full_tuple_t = std::tuple<Args...>;
using type = std::tuple<std::pair<
std::tuple_element_t<2*Is, full_tuple_t>,
std::tuple_element_t<2*Is+1, full_tuple_t>
>...>;
};
template <class... Args> struct pairwise
{
static_assert(sizeof...(Args) % 2 == 0,
"Only even typelists can be split to pairs");
using type = typename pairwise_impl<
std::tuple<Args...>,
std::make_index_sequence<sizeof...(Args) / 2>
>::type;
};
template <class... Args>
using pairwise_t = typename pairwise<Args...>::type;
Demo
|
72,668,474 | 72,668,531 | How change the second letter in char *name = "exemple"; with char *name | I am studying c++ to get a good understanding of memory.
char *name = "example";
*(&name+1) = (char*)'A';
std::cout << name << std::endl;
is returning example not eAample.
My idea is to get the memory address of 'x' and changed it.
Is not a const so I should be able to change the value of the address right?
obs: I know how do it in other ways, I am curious to make this way.
| This declaration
char *name = "example";
is invalid.
In C++ string literals have types of constant character arrays. It means that you have to write
const char *name = "example";
and you may not change the string literal.
Even in C where string literals have types of non-constant character arrays you may not change a string literal. Any attempt to change a string literal results in undefined behavior.
This expression
&name+1
points outside the pointer name. So dereferencing the pointer expression *(&name+1) invokes undefined behavior.
Also this expression (char*)'A' does not make a sense. It denotes that you are trying to use the value of the code of the character 'A' (that for example in ASCII is equal to 65) as an address of memory.
What you could do is the following
char name[] = "example";
*(name+1) = 'A';
std::cout << name << std::endl;
Or if you want to deal with pointer expressions then instead of
*(name+1) = 'A';
you could write
*(name+1) = *"A";
Here is a demonstration program that is based on your idea. The first range-based for loop will be compiled by a compiler that supports C++ 20. Otherwise you can rewrite it like
const char **p = name;
for ( const auto &letter : "example")
Here you are.
#include <iostream>
int main()
{
const char *name[sizeof( "example" )];
for ( const char **p = name; const auto &letter : "example")
{
*p++ = &letter;
}
*( name + 1 ) = &"A"[0];
for ( const char **p = name; **p; ++p )
{
std::cout << **p;
}
std::cout << '\n';
}
The program output is
eAample
|
72,668,537 | 72,668,799 | PushButton is opened in different window | i am new at QT
i created a window and i want to add a button on this window but the button is opened in different window.
How to add this button to default window
Here is my code;
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QPushButton"
#include "QDesktopWidget"
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QPushButton* buton1 = new QPushButton("Hello");
buton1 -> setGeometry(QRect(QPoint(100,100),QSize(200,50)));
connect(buton1, &QPushButton::released, this, &MainWindow::buton_fonk);
buton1 -> show();
ui->setupUi(this);
}
void MainWindow::buton_fonk()
{
cout << "here" << endl;
}
MainWindow::~MainWindow()
{
delete ui;
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QDesktopWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowState(Qt::WindowMaximized);
w.showFullScreen();
return a.exec();
}
| You need to make QPushButton a child of the main window for it to be rendered inside the main window, otherwise QPushButton will be an independent widget.
Usually all Qt Widgets accept a pointer to parent widget, QPushButton also accept a pointer to parent widtet.
QPushButton(const QString &text, QWidget *parent = nullptr)
To make QPushButton child of MainWindow, add this as second parameter to QPushButotn constructor.
QPushButton* buton1 = new QPushButton("Hello", this); // Make MainWindow as parent of QPushButton
Ideally you should create a layout and add all your widgets to this layout and then set the central widget of MainWindow to this layout.
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(button1);
// Add anyother widget to your layout
this->setCentralWidget(mainLayout);
Hope this helps.
|
72,669,120 | 72,671,083 | CMake isn't able to include header file into my source file | I'm learning CMake and got to the part where I learn how to include header files. The problem is that I get an error, saying that the header file has not been found.
I'm on Windows 10, by the way.
All I have as of right now is a src and include directories along with the CMakeLists.txt file. In source, I only have a single file and I also only have a single file in include.
This is my main.cpp file:
#include <iostream>
#include "include/main.h"
int main() {
std::cout << "Hello, World!\n";
sayHi("Joshua");
return 0;
}
And this is my CMakeLists.txt file.
cmake_minimum_required(VERSION 3.10)
set(CXX_STANDARD 17)
set(CXX_STANDARD_REQUIRED ON)
project(hello VERSION 1.0)
add_executable(hello ../src/main.cpp)
target_include_directories(hello PUBLIC ${CMAKE_CURRENT_SRC_DIR}/include)
EDIT: I fixed the source code so that I includes main.h, rather than include/main.h, but I still end up with the same error:
"C:\Users\HP\desktop\test\4\build\hello.sln" (destino padrΓ£o) (1) ->
"C:\Users\HP\desktop\test\4\build\hello.vcxproj.metaproj" (destino padrΓ£o) (3) ->
"C:\Users\HP\desktop\test\4\build\hello.vcxproj" (destino padrΓ£o) (4) ->
(ClCompile destino) ->
C:\Users\HP\Desktop\test\4\src\main.cpp(3,10): fatal error C1083: Cannot open include file: 'main.h
': No such file or directory [C:\Users\HP\desktop\test\4\build\hello.vcxproj]
0 Aviso(s)
1 Erro(s)
```
What is going on?
| It's ${CMAKE_CURRENT_SOURCE_DIR}, not ${CMAKE_CURRENT_SRC_DIR}.
If you fix this then the compiler should see the correct include directory.
At the moment because the variable doesn't exist, the only directory it sees is /include which is not what you want.
|
72,669,278 | 72,669,308 | Coding own shell, error "exec: bad adress" | I'm trying to code my own shell in c++ and have stumbled upon an error, I don't know how to fix. You have to type in a command in the terminal, most of them work as well, but if I try to include more than one argument or spaces between letters (example: echo 1 2 3) the shell says "exec: bad adress". I'm coding the shell on kali linux in a virtual machine and use g++ to compile the programm, I've tried using cpp, but when I try to execute the file, it says "namespace: not found". Help would be greatly appreciated.
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <regex>
bool handleLogout()
{
std::cout<<"Are you sure you want to log out?<y/n>"<<std::endl;
char eingabe;
std::cin>>eingabe;
if(eingabe=='y'){
std::cout << "Bye";
exit(0);
return true;
}else {
return false;
}
}
void processArgs(std::string command, std::string delimiter, std::vector<std::string> &argsBefore)
{
size_t pos =0;
std::string teilWort;
while((pos= command.find(delimiter))!=std::string::npos){
teilWort=command.substr(0,pos);
command.erase(0,pos+delimiter.length());
argsBefore.push_back(teilWort);
}
argsBefore.push_back(command);
}
int main()
{
while(1){
while(waitpid(-1, 0, WNOHANG) > 0) {}
bool executeInBackground = false; //checks if command should be activated in background
std::vector<std::string> argsBefore;
std::string command;
std::string delimiter=(" "); //used to seperate the different arguments
std::cout << getlogin() << ":$ ";
std::getline(std::cin, command);
if(command.back() == '&') {
executeInBackground = true;
command.replace(command.length() - 1, 1, "");
command = std::regex_replace(command, std::regex(" +$"), ""); //trim trailing spaces
}
processArgs(command, delimiter, argsBefore);
char* args[argsBefore.size()];
for(size_t i =0; i<=(argsBefore.size());i++){
args[i]=(char*)argsBefore[i].c_str();
}
args[sizeof(args)+1]=NULL; // null terminated array for execvp
if(command=="logout"){
if(handleLogout())
break;
else
continue;
}
pid_t pid = fork();
pid_t w_pid;
// Error
if(pid<0){
std::cout<<"Error, fork failed!"<<std::endl;
return 1;
}
// Child
if(pid==0){
if(execvp(args[0], args)==-1){
perror("exec");
exit(0);
}
}
// Parent
if(pid>0){
if(executeInBackground==true){
std::cout<<"Child spwan with PID: " << pid << std::endl;
continue;
}
w_pid = waitpid(pid, 0, WUNTRACED | WCONTINUED);
if(w_pid == -1){
perror ("Wait");
}
}
}
return 0;
}
| char* args[argsBefore.size()];
for(size_t i =0; i<=(argsBefore.size());i++){
args[i]=(char*)argsBefore[i].c_str();
}
args[sizeof(args)+1]=NULL;
Firstly char* args[argsBefore.size()]; is not legal C++ (but g++ will accept it). In C++ array sizes must be compile time constants.
More importantly you have an array out of bound access. i<=(argsBefore.size()) should be i < argsBefore.size(). Array indexes go up to but do not include the array size. So use < not <=.
Also your attempt to null terminate the args array is incorrect. To do that you need to make the array one bigger.
char* args[argsBefore.size() + 1]; // +1 for NULL terminator
And then you can add the NULL like this
args[argsBefore.size()] = NULL;
|
72,669,579 | 72,669,632 | C++ how to set environment variable so OpenBLAS runs multithreaded | The author recommends the following:
https://github.com/xianyi/OpenBLAS
Setting the number of threads using environment variables
Environment variables are used to specify a maximum number of threads. For example,
export OPENBLAS_NUM_THREADS=4
export GOTO_NUM_THREADS=4
export OMP_NUM_THREADS=4
The priorities are OPENBLAS_NUM_THREADS > GOTO_NUM_THREADS > OMP_NUM_THREADS.
If you compile this library with USE_OPENMP=1, you should set the OMP_NUM_THREADS environment variable; OpenBLAS ignores OPENBLAS_NUM_THREADS and GOTO_NUM_THREADS when compiled with USE_OPENMP=1.
When I use "export OPENBLAS_NUM_THREADS=16" in my main.cpp, I get an error about templates.
So, I changed my CMakeList.txt file to include:
set($ENV{OPENBLAS_NUM_THREADS} 16)
This seemed to have no effect on the threading of my application. I only see 1 CPU core at 100%.
|
When I use "export OPENBLAS_NUM_THREADS=16" in my main.cpp, I get an error about templates.
OPENBLAS_NUM_THREADS is a runtime defined variable so it should not impact the build of an application unless the build scripts explicitly use this variable which is very unusual and a very bad idea (since the compile-time environment can be different from the run-time one).
Note that export OPENBLAS_NUM_THREADS=16 is a bash command and not something to put in a C++ file. Its purpose is to set the environment variable OPENBLAS_NUM_THREADS so it can be read at runtime by OpenBLAS when your application call a BLAS function. You should do something like:
# Build part
cmake # with the correct parameters
make
# Running part
export OPENBLAS_NUM_THREADS=4
./your_application # with the correct parameters
# Alternative solution:
# OPENBLAS_NUM_THREADS=4 ./your_application
So, I changed my CMakeList.txt file to include:
This should have not effect indeed because the variable should not be used at compile time.
I only see 1 CPU core at 100%
Note that setting OPENBLAS_NUM_THREADS may not be enough to use multiple threads in practice. If your matrices are small, then consider reading this very-recent post about how OpenBLAS works with multiple threads.
|
72,670,090 | 72,670,195 | Is shared_ptr::unique() indicative that only one thread owns it? | I have a worker thread giving my rendering thread a std::shared_ptr<Bitmap> as part of how I download texture data from the GPU. Both threads depend on std::shared_ptr<...>::unique() to determine if the other thread is done with the Bitmap. No other copies of this shared pointer are in play.
Here's a trimmed down chart of the behavior:
worker thread | rendering thread
----------------------------------- + -------------------------------------------------
std::shared_ptr<Bitmap> bitmap; | std::queue<std::shared_ptr<Bitmap>> copy;
{ | {
std::scoped_lock lock(mutex); | std::scoped_lock lock(mutex);
queue.push_back(bitmap); | std::swap(queue, copy);
} | }
... | for(auto it = copy.begin(); it != copy.end(); ++it)
| if (it->unique() == false)
if (bitmap.unique()) | fillBitmap(*it); // writing to the bitmap
bitmap->saveToDisk(); // reading
Is it safe to use unique() or use_count() == 1 to accomplish this?
edit:
Ah... since unique() is unsafe in this case, I think instead I'm going to try something like std::shared_ptr<std::pair<Bitmap, std::atomic<bool>>> bitmap; instead, flipping the atomic when it's filled.
| No, it is not safe. A call to unique (or to use_count) does not imply any synchronization.
If e.g. the worker thread observes bitmap.unique() as true, this does not imply any memory ordering on the accesses made by fillBitmap(*it); and those made by bitmap->saveToDisk();. The function call may be implemented as a relaxed load, which doesn't have the required acquire-release effect.
Without any memory ordering, you will likely have a data race and undefined behavior as consequence.
This is why std::shared_ptr::unique was deprecated with C++17 and removed with C++20, since it is so easy to misuse in this way. Just using use_count() == 1 doesn't work either. It has the exact same issues. I guess it wasn't removed as well, because there may be valid uses cases even in multi-threaded environments for use_count if you only need it to get a fuzzy idea of the number of current users and because there should still be a way of implementing unique for a single-threaded context (where it doesn't have any problems).
According to the proposal to remove std::shared_ptr::unique, many implementations do in fact use a relaxed load, implying that problems may actually happen on real implementations, see https://open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0521r0.html.
If you are on an architecture like x86 you may be saved by the fact that on the hardware level a relaxed load is automatically an acquire load.
However, the C++ memory model does not make any ordering guarantees here and I think (might be wrong here) for example ARM is an example for an architecture where normal (relaxed) loads don't automatically have acquire/release semantics.
And in any case, because there are no memory ordering guarantees, I think the compiler could still perform transformations that will cause issues in any case. For example, because unqiue doesn't imply any synchronization, the compiler could load data used in bitmap->saveToDisk(); before actually loading the reference counter. The load may be unnecessary if the condition on the reference counter turns out to not be fulfilled, but I don't see anything preventing the compiler from adding a superfluous load.
Inbetween these loads some stores from fillBitmap(*it); and the destruction of the rendering threads std::shared_ptr could happen, causing the worker thread to use data from before the stores in fillBitmap(*it);.
|
72,670,521 | 72,670,946 | Is openmp included in stdio.h in c/c++οΌ | I searched about openmp, and realised that some people includes omp.h and others do not. They just include stdio.h.
So my question is: Is openmp included in stdio.h so that we can use opemp if we only include it?
I think old openmp such as openmp2.0 need to be used with omp.h but openmp3.0 does not need to be so.
but I'm not sure...
| stdio.h does not contain omp.h.
Your confusion may be because to use #pragma omp ... directives you do not have to include omp.h, so it means that you can write an OpenMP program without including omp.h.
On the other hand, if you use any OpenMP runtime library function (e.g. omp_get_num_threads()) you have to include omp.h regardless of the version of OpenMP.
|
72,670,631 | 72,671,926 | openGL doesen't let me draw in a class | I am trying to create a text class witch has its own vertex array, vertex buffer, index buffer and draw them on a function call.
It looks like so:
class Text {
private:
std::string m_FontFilePath;
std::string m_Text;
Texture* m_FontTexture;
VertexBuffer* m_Vbo;
IndexBuffer* m_Ibo;
VertexArray* m_Va;
float* m_TextPos;
unsigned int* m_Index;
unsigned int m_IndexCount;
public:
Text(std::string fontFilePath, std::string text, float posX, float posY);
~Text();
void drawText();
};
void Text::drawText()
{
m_Va->Bind();
glDrawElements(GL_TRIANGLES, m_IndexCount, GL_UNSIGNED_INT, nullptr);
}
This is the constructor that creates everything:
Text::Text(std::string fontFilePath, std::string text, float posX, float posY)
: m_FontFilePath(fontFilePath), m_Text(text)
{
VertexArray va2;
va2.Bind();
m_TextPos = new float[m_Text.size() * 24];
std::cout << posX << " " << posY<<"\n";
float unitH = 0.1f, unitW = 0.1f;
int countNow = 0;
for (auto letter : m_Text)
{
addLetter(m_TextPos, {
// posX posY poZ TextureCoord, TextureIndex
posX, posY, 0, 0.0f, 0.0f, 0.0f,
posX + unitW, posY, 0, 1.0f, 0.0f, 0.0f,
posX + unitW, posY + unitH, 0, 1.0f, 1.0f, 0.0f,
posX, posY + unitH, 0, 0.0f, 1.0f, 0.0f
}, countNow);
posX += unitW;
countNow += 24;
}
// this creates a square for every letter of the word
VertexBuffer vb2(m_TextPos, sizeof(float) * 24 * m_Text.size());
VertexBufferLayout vbl2;
vbl2.Push<float>(3);
vbl2.Push<float>(2);
vbl2.Push<float>(1);
va2.AddBuffer(vb2, vbl2);
m_Index = new unsigned int[m_Text.size() * 6];
for (int i = 0; i < m_Text.size(); i++) {
m_Index[i * 6 + 0] = i * 4 + 0;
m_Index[i * 6 + 1] = i * 4 + 1;
m_Index[i * 6 + 2] = i * 4 + 2;
m_Index[i * 6 + 3] = i * 4 + 2;
m_Index[i * 6 + 4] = i * 4 + 3;
m_Index[i * 6 + 5] = i * 4 + 0;
}
// this creates the m_Index array
IndexBuffer ibo2(m_Index, m_Text.size() * 6);
m_Vbo = &vb2;
m_Ibo = &ibo2;
m_Va = &va2;
m_IndexCount = 6 * m_Text.size();
std::cout << "INDEXES:\n";
for (int i = 0; i < m_Text.size() * 6; i++) {
std::cout << m_Index[i] << " ";
if ((i + 1) % 6 == 0) std::cout << "\n";
}
std::cout << "\nINSIDE VBO:\n";
for (int i = 0; i < 24 * m_Text.size(); i++) {
std::cout << m_TextPos[i] << " ";
if ((i + 1) % 6 == 0)std::cout << "\n";
}
va2.Unbind();
}
The IndexBuffer and VertexBuffer have the right data in them(I checked both).
If I take all the data from this class and move it in main.cpp and draw it there it works fine witch I find weird.
The main loop looks like so:
Text test(filePath, "randomText", 0.1f, 0.1f);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1.0f, 1.0f, 0.0f, 1.0f);
// va = vertex array I created above this while loop, contains
va.Bind(); // 2 squares, it draws good
glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, nullptr);
test.drawText(); // nothing draws on screen
glfwSwapBuffers(window);
glfwPollEvents();
}
| Your buffers objects are local in scope of Text::Text. The attributes are dangling pointers. You have to create dynamic objects. Remove the local variables va2, vb2 and ibo2 but allocate dynamic memory and create the objects with the new operator:
Text::Text(std::string fontFilePath, std::string text, float posX, float posY)
: m_FontFilePath(fontFilePath), m_Text(text)
{
m_Va = new VertexArray();
m_Va->Bind();
// [...]
m_Vbo = new VertexBuffer(m_TextPos, sizeof(float) * 24 * m_Text.size());
// [...]
m_Ibo = new IndexBuffer(m_Index, m_Text.size() * 6);
// [...]
}
Don't forget to delete the objects in the class's destructor.
|
72,670,928 | 72,755,029 | Type punning between `pair<Key, Value>` and `pair<const Key, Value>` | A relative question, but I want a solution without any run-time overhead. (So constructing a new pair or using std::variant are not the answers)
Due to the potential template specialization, reference has said pair<K, V> and pair<const K, V> are not similar, that means a simple reinterpret_cast would trigger undefined behaviour.
auto p1 = pair<int, double>{ 1, 2.3 };
auto& p2 = reinterpret_cast<pair<const int, double>&>(p1); // UB!
Type-punning through union works fine in C, but not always legal in C++:
It's undefined behavior to read from the member of the union that wasn't most recently written.
If members of a union are classes with user-defined constructors and destructors, to switch the active member, explicit destructor and placement new are generally needed
But there's an exception (to be consistent with behaviours in C?):
If two union members are standard-layout types, it's well-defined to examine their common subsequence on any compiler.
Since Key and Value may not be standard-layout and may have non-trivial destructor, it seems type-punning here is impossible, though members of pair<Key, Value> and pair<const Key, Value> could share the same lifetime (of course with alignment assertion).
template <typename Key, typename Value>
union MapPair {
using TrueType = pair<Key, Value>;
using AccessType = pair<const Key, Value>;
static_assert(
offsetof(TrueType, first) == offsetof(AccessType, first)
&& offsetof(TrueType, second) == offsetof(AccessType, second)
&& sizeof(TrueType) == sizeof(AccessType)
);
TrueType truePair;
AccessType accessPair;
~MapPair() {
truePair.~pair();
}
// constructors for `truePair`
};
//...
auto mapPair = MapPair<NonTrivialKey, NonTrivialValue>{/*...*/};
// UB? Due to the lifetime of `truepair` is not terminated?
auto& accessPair = reinterpret_cast<pair<const NonTrivialKey, NonTrivialValue>&>(mapPair);
// still UB? Although objects on the buffer share the same constructor/destructor and lifetime
auto* accessPairPtr = std::launder(reinterpret_cast<pair<const NonTrivialKey, NonTrivialValue>*>(&mapPair));
I've noticed the guarantee that no elements are copied or moved when calling std::map::extract, and user-defined specilization of std::pair would cause UB when operating Node handle. So I trust some similar behaviours (type-punning or const_cast) really exist in the STL implementations relating to Node handle.
In libc++, it seems to depend on the characteristic of clang (doesn't optimize for data members), not the standard.
libstdc++ did the similar work as libc++, but no std::launder to refresh the type state.
MSVC is ... very surprising... and the commit history is too short that I can't find any reasons to support such a simple aliasing...
Is there a standard way here?
| This is impossible. The node_handle proposal mentioned this as a motivation for standardizing it:
One of the reasons the Standard Library exists is to write non-portable and magical code that the client canβt write in portable C++ (e.g. , , <type_traits>, etc.). This is just another such example.
Note that the key member function is the only place where such tricks are necessary, and that no changes to the containers or pair are required.
ref
|
72,670,980 | 72,671,682 | Call the notify_all method after store with release memory order on an atomic | I have the following code being executed on a single thread (written in C++20):
std::atomic_bool is_ready{};
void SetReady() {
is_ready.store(true, std::memory_order_release);
is_ready.notify_all();
}
Other threads execute the text listed below:
void Wait() {
is_ready.wait(false, std::memory_order_acquire);
}
As I know, release memory order doesn't ensure that the operations located after it will not be reordered by a compiler. So, can I place notify_all() after store() with release memory order? Is it safe? Just I have some thoughts that store() may be sequenced before notify_all() and hence may not be reordered.
| The memory orders are irrelevant here. They only affect ordering of memory access other than on the atomic itself and you have none.
The compiler cannot reorder the notify_all call before the store in any case, because notify_all is specified to wake up all waiting operations on the atomic which are eligible to be unblocked.
Which these are depends on whether, in the global modification order of the atomic, the last store which happens-before the call to notify_all is ordered after the store observed by the waiting thread when it blocked.
In your shown code the true store is sequenced-before the notify_all call (in the same thread), which implies that the store happens-before the call, but if the lines were switched, then that wouldn't be the case anymore.
Moving the notify_all before the store would thus potentially change the set of waiting operations which are eligible to be unblocked.
If the compiler was allowed to do that, then the waiting/notification mechanism would be pretty useless. This is also the same as for other operations on the same atomic in the same thread (or really any operations on the same storage location in the same thread). The compiler cannot reorder these either.
So yes, it is safe and the Wait thread will not wait forever. (I am assuming that the initialization std::atomic_bool is_ready{}; is happening before either of the shown thread functions start execution.)
|
72,671,139 | 72,677,166 | Exclude points in overlapping area of two circles in OpenGL | I want to draw tow circles with the same radii but exclude the overlapped area when drawing.
I want to draw or set dots on gray area.
I implement the mathematical aspect behind it and here is my code:
void draw_venn(){
float radian_to_degree_theta=2 * 3.14 / 360,
r = 0.5,
distance=0.3,
theta=0.0,
theta2=0.0,
xR=0.0,
yR=0.0,
xG=0.0,
yG=0.0,
sum_radii=0,
dis=0.0;
sum_radii=r+r;
for (r = 0.5; r >=0; r-=0.001)
{
for (float degree = 0; degree < 361; degree+=0.1)
{
theta =degree*radian_to_degree_theta;
xR=r*cos(theta)+distance;
yR=r*sin(theta);
xG=r*cos(theta)-distance;
yG=r*sin(theta);
dis=sqrt(pow(xR-xG,2) + pow(yR-yG,2));
if (dis <= sum_radii)
{
set_point(xR,yR,0.1,1,0,0);
set_point(xG,yG,0.1,0,1,0);
}
}
}
}
void set_point(float x,float y,float size,float R,float G,float B){
glPointSize(size);
glBegin (GL_POINTS);
glColor3f (R, G, B);
glVertex2f(x, y);
glEnd ();
}
void draw(void)
{
glClearColor (1, 1, 1, 0);
glClear (GL_COLOR_BUFFER_BIT);
glPushMatrix();
draw_ven();
glPopMatrix ();
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(1400, 1400);
glutInitWindowPosition(700, 500);
glutCreateWindow("GL Sample");
glutDisplayFunc(draw);
glutMainLoop();
return 0;
}
and here is the result:
How can I find if a point is inside the overlapping area?
| I reviewed and tested out your code. Trigonometry can get a bit tricky. Following is the "draw_venn" function with some refinements to produce an overlap effect.
void draw_venn()
{
float radian_to_degree_theta=2 * 3.141 / 360,
r = 0.5,
distance=0.3,
theta=0.0,
theta2 = 0.0,
xR=0.0,
yR=0.0,
xG=0.0,
yG=0.0,
dis=0.0;
glPointSize(1);
glColor3f(1,0,0);
glBegin(GL_POINTS);
for (r = 0.5; r >=0; r-=0.001)
{
for (float degree = 0; degree < 361; degree+=0.1)
{
theta =degree*radian_to_degree_theta;
theta2 = (180.0 - degree) * radian_to_degree_theta;
xR=r*cos(theta2)+distance;
yR=r*sin(theta2);
xG=r*cos(theta)-distance;
yG=r*sin(theta);
dis = sqrt(pow((distance - xG), 2) + pow(yG, 2));
if (dis < 0.5)
{
set_point(xR,yR,0.1,0,0,1); /* Color the overlap blue */
set_point(xG,yG,0.1,0,0,1); /* This works due to symmetry */
}
else
{
set_point(xR,yR,0.1,1,0,0); /* Set the symmetrical circle colors */
set_point(xG,yG,0.1,0,1,0);
}
}
}
glEnd();
}
Pointing out the two significant revisions, first I derive a mirror image value for "theta" and place that into variable "theta2". That is used to draw the red circle. This assures that the circle images are being built in equal but opposite directions so that the coordinates are symmetrical. Second, I revised the formula for checking if the green image coordinates fall within the red circle's outermost radius. Using the Pythagorean theorem calculation for the hypotenuse, the formula determines if the hypotenuse value is smaller than the outermost radius length (0.5). If it is smaller make that point for the green circle blue, and since the circle points are being built and colored symmetrically, also make the corresponding point for the red circle blue.
The result of those revisions is a Venn Diagram showing an overlap.
I hope that helps and gives you a springboard to proceed.
Regards.
|
72,671,541 | 72,671,778 | exploiting canary to buffer overflow in C | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include <random>
using namespace std;
void login1(char * input1, char * input2) {
struct {
char username[20];
int canary;
char password[20];
char good_username[20];
char good_password[20];
int goodcanary;
} v;
v.canary = rand()%10000+10000;
v.goodcanary = v.canary;
if(strlen(input1) > 20) {
printf("Username too long, existing.\n");
exit(-1);
}
//read correct username and password
FILE * fp = fopen("password.txt", "r");
fgets(v.good_username, 20, fp);
fgets(v.good_password, 20, fp);
fclose(fp);
//remove trailing newline
v.good_username[strlen(v.good_username)-1] = '\0';
v.good_password[strlen(v.good_password)-1] = '\0';
strcpy(v.username, input1);
strcpy(v.password, input2);
//terminate strings properly for strcmp
v.username[19] = '\0';
v.password[19] = '\0';
v.good_username[19] = '\0';
v.good_password[19] = '\0';
//check canary and login success
if (v.canary != v.goodcanary) {
printf("Stack overflow detected, exiting.\n");
exit(-1);
}
if (strcmp(v.username, v.good_username) == 0 && strcmp(v.password, v.good_password) == 0) printf("Login successful!\n");
else printf("Login denied.\n");}
I've tried various lengths of usernames and passwords with no luck. I assumed I had to overflow but it always gets detected. What input of username and password would get me "Login successful" even if it wasn't the correct username and password?
| In
struct {
char username[20];
int canary;
char password[20];// a 60 char password can overwrite the next two members
char good_username[20];
char good_password[20];
int goodcanary; // without touching this canary
}
The second canary is after the input password as well as the good user name and password. The length of the input password is not validated. This allows an attacker to provide an input2 of sufficient length to overwrite both the user name and password with strcpy(v.password, input2); without damaging the canary.
input2 must contain any password you want, then starting at character 20 the username provided as input1, and then starting at character 40 a repeat of the password you set.
It doesn't matter what you supply as input1 so long as it exactly matches what you put in the middle of input2, including padding, and doesn't overflow and damage the canary.
|
72,671,616 | 72,672,074 | Remove out excess spaces from string in C++ | I have written program for removing excess spaces from string.
#include <iostream>
#include <string>
void RemoveExcessSpaces(std::string &s) {
for (int i = 0; i < s.length(); i++) {
while (s[i] == ' ')s.erase(s.begin() + i);
while (s[i] != ' ' && i < s.length())i++;
}
if (s[s.length() - 1] == ' ')s.pop_back();
}
int main() {
std::string s(" this is string ");
RemoveExcessSpaces(s);
std::cout << "\"" << s << "\"";
return 0;
}
One thing is not clear to me. This while (s[i] == ' ')s.erase(s.begin() + i); should remove every space in string, so the output would be thisisstring, but I got correct output which is this is string.
Could you explain me why program didn't remove one space between this and is and why I got the correct output?
Note: I cannot use auxiliary strings.
| That is because when your last while loop finds the space between your characters (this is) control pass to increment part of your for loop which will increase the value of int i then it will point to next character of given string that is i(this is string) that's why there is space between (this is).
|
72,671,703 | 72,671,868 | Weight choices based on the most common number in an array | I'm trying to find out how to calculate the 'weight choices' based on the most frequent number in an array for AI to choose a particular number.
For instance, I have this function which calculates the most common number in an array and allows the AI to choose a particular option to make the player lose.
As it stands now, if the most frequent number is 1, there will be a 50% chance that 2 will be chosen. Ideally, it should only have a 50% chance to occur if the array is full of 1s.
Does anyone have any solutions for this? I haven't been able to work it out. Appreciate the help.
P.S: I know the function is probably written very badly, just trying to get something as a prototype/skeleton function.
| This looks like the perfect place for a std::discrete_distribution.
Walkthrough:
#include <algorithm>
#include <iostream>
#include <map>
#include <random>
#include <vector>
// A seeded pseudo random number generator:
static std::mt19937 gen(std::random_device{}());
int main() {
Say you have all the player choices in a vector. You seem to have them in an array, but I'll use a vector since it's easier to handle.
// filled with some example choices:
std::vector<int> m_playerChoices{10,10,11,10,22,22,10};
I'd start by making a histogram so that you get the count of each choice:
std::map<int, int> hist;
for(int choice : m_playerChoices) {
++hist[choice];
}
Then we extract the choices and counts from the histogram and put in two separate vectors. One containing all the unique choices and a corresponding one containing the count of each, called weights.
std::vector<int> unique_choices;
std::vector<int> weights;
for(auto[choice, count] : hist) {
unique_choices.push_back(choice);
weights.push_back(count);
}
The weights are then used to create a discrete_distribution:
std::discrete_distribution<int> dist(weights.begin(), weights.end());
You can now call the pseudo random number generator and use this discrete distribution to get one of the unique numbers and the probability for each will be exactly according to the count of each choice that you started out with:
for(int i = 0; i < 100; ++i) {
std::cout << unique_choices[dist(gen)] << '\n';
}
}
Demo
|
72,671,742 | 72,671,991 | Why is this function call didn't reject the unsuitable overload? | Consider the following code:
#include<vector>
#include<ranges>
#include<algorithm>
//using namespace std;
using namespace std::ranges;
int main()
{
std::vector<int> a = {};
sort(a);
return 0;
}
It's running properly.
Obviously, it called this overload function(functor, strictly speaking):
template<random_access_range _Range,
typename _Comp = ranges::less, typename _Proj = identity>
requires sortable<iterator_t<_Range>, _Comp, _Proj>
constexpr borrowed_iterator_t<_Range>
operator()(_Range&& __r, _Comp __comp = {}, _Proj __proj = {}) const
{
return (*this)(ranges::begin(__r), ranges::end(__r),
std::move(__comp), std::move(__proj));
}
But after we introducing the namespace std, the function call became ambiguous(got compilation errors):
#include<vector>
#include<ranges>
#include<algorithm>
using namespace std;
using namespace std::ranges;
int main()
{
std::vector<int> a = {};
sort(a);
return 0;
}
In addition to the previous reloads
2045 | inline constexpr __sort_fn sort{};
, there are many other overload functions found in namespace std like:
template<class _ExecutionPolicy, class _RandomAccessIterator> __pstl::__internal::__enable_if_execution_policy<_ExecutionPolicy, void> std::sort(_ExecutionPolicy&&, _RandomAccessIterator, _RandomAccessIterator)
and
template<class _RAIter, class _Compare> constexpr void std::sort(_RAIter, _RAIter, _Compare)
So my questions are:
The call of sort functor in std::ranges is the best match function, isn't it? Why do these functions later found in std cause ambiguity, rather than being abandoned due to the SFINAE principle?
If the functions in std are visible for sort(a) after we introduced the namespace std, shouldn't it be equally visible in the first code according to the ADL of a?
| The problem is that std::ranges::sort is implemented as function object and not a function. From name lookup rules:
For function and function template names, name lookup can associate multiple declarations with the same name, and may obtain additional declarations from argument-dependent lookup. [...]
For all other names (variables, namespaces, classes, etc), name lookup must produce a single declaration in order for the program to compile.
std::ranges::sort is a variable, and thus name lookup fails (because there is more than one declaration matching name sort). And std::ranges algorithms are explicitly allowed to be implemented as function objects (quote from std::ranges::sort cppreference):
The function-like entities described on this page are niebloids, that is: [...]
In practice, they may be implemented as function objects, or with special compiler extensions.
So, as long as standard library implements std::ranges::sort as function object (and both libstdc++ and libc++ seem to do that), there is no way to make sort name lookup work if you introduce both std::ranges and std in global namespace.
|
72,671,882 | 72,672,265 | How to build and run OpenSubdiv Tutorials/examples | I'm trying to experiment with the OpenSubdiv C++ library. I'm not an experienced C++ programmer.
The OpenSubdiv library has some tutorials that I'd like to get working, but I can't figure out how.
So far, I have installed OpenSubD and dependencies (GLFW) to the best of my extremely limited abilities, by doing the following (I'm on Ubuntu, for reference).
sudo apt-get install doxygen # (GLFW Dependency?)
sudo apt-get install xorg-dev # (GLFW Dependency?)
sudo apt-get install libglfw3 # (GLFW Dependency?)
sudo apt-get install libglfw3-dev # (GLFW Dependency?)
git clone git@github.com:PixarAnimationStudios/OpenSubdiv.git
cd OpenSubdiv
mkdir build
cd build
cmake -D NO_PTEX=1 -D NO_DOC=1 -D NO_OMP=1 -D NO_TBB=1 -D NO_CUDA=1 -D NO_OPENCL=1 -D NO_CLEW=1 -D GLFW_LOCATION="/usr/" ..
cmake --build . --config Release --target install
Note this roughly follows the instructions given in the OpenSubdiv repo README.
The code I am trying to compile is
#include <GLFW/glfw3.h>
#include <opensubdiv/far/topologyDescriptor.h>
#include <opensubdiv/far/primvarRefiner.h>
#include <cstdio>
using namespace OpenSubdiv;
int main(int, char **){
typedef Far::TopologyDescriptor Descriptor;
Sdc::SchemeType type = OpenSubdiv::Sdc::SCHEME_CATMARK;
Sdc::Options options;
options.SetVtxBoundaryInterpolation(Sdc::Options::VTX_BOUNDARY_EDGE_ONLY);
// Compiles fine up to this point.
Descriptor desc; //Fails here, trying to instantiate a "Descriptor" object, which lives in OpenSubdiv
desc.numVertices = g_nverts;
desc.numFaces = g_nfaces;
desc.numVertsPerFace = g_vertsperface;
desc.vertIndicesPerFace = g_vertIndices;
return 0;
}
The error I get is
g++ opensubd_minimal_example.cpp -o opensubd_minimal_example
/usr/bin/ld: /tmp/cc4WQ9jc.o: in function `main':
opensubd_minimal_example.cpp:(.text+0x57): undefined reference to `OpenSubdiv::v3_4_4::Far::TopologyDescriptor::TopologyDescriptor()'
collect2: error: ld returned 1 exit status
I'm guessing that there is some linking that needs to happen that I'm missing, but I don't know what, and I can't figure it out from looking at the cmake files used by OpenSubd, because I don't know how to use cmake.
I could use some guidance. Thanks.
| Please refer to the last section of OpenSubDiv: building with cmake.
The linker needs to know where to find the library to link. Set the OPENSUBDIV variable to the directory of OpenSubDiv, then compile and link your app.
g++ -I$OPENSUBDIV/include -c myapp.cpp
g++ myapp.o -L$OPENSUBDIV/lib -losdGPU -losdCPU -o myapp
|
72,672,694 | 72,682,511 | Eigen replace first row in matrix error: mismatched types βconst Eigen::ArrayBase<ExponentDerived>β and βintβ | Trying to replace the first row of a matrix with some expression, similar to my MATLAB code:
%Matrix A defined and Ny
A(1,:) = (-1).^(1:Ny+1).*(0:Ny).^2;
A(Ny+1,:) = (0:Ny).^2;
The C++ code I wrote is:
static const int ny = 10;
Eigen::VectorXd i = VectorXd(ny+1);
std::iota(i.begin(), i.end(), 0);
//matrix A is also defined correctly here
A.row(0) = pow(-1,(i))*(pow(i,2)); //error here
std::cout << A.row(0) << "\n";
can I get this done without having to rewrite it in a for loop, I am guessing that would require me changing the initialization of i
The full error message:
Test.cpp:329:25: error: no matching function for call to βpow(int, Eigen::VectorXd&)β
329 | dv1.row(0) = pow(-1,(a))*(pow(a,2));
| ^~~
/usr/include/c++/9/complex:1885:5: note: template argument deduction/substitution failed:
Test.cpp:329:25: note: βEigen::VectorXdβ {aka βEigen::Matrix<double, -1, 1>β} is not derived from βconst std::complex<_Up>β
329 | dv1.row(0) = pow(-1,(a))*(pow(a,2));
/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/GlobalFunctions.h:175:3: note: template argument deduction/substitution failed:
Test.cpp:329:35: note: mismatched types βconst Eigen::ArrayBase<ExponentDerived>β and βintβ
329 | dv1.row(0) = pow(-1,(a))*(pow(a,2));
And it keeps repeating similar errors. I tried initializing i with Eigen::Matrix< double, 1, ny+1> instead but I get the same error.
%%%%%%%%%%%%%%%%%%%%%
Edit:
Currently I have this C++ code working, but I would like to make use of the operators .row() and .col() :
for (int i = 0; i < ny+1; i++){
for (int j = 0; j < ny+1; j++){
A(0,j) = -1. * pow(-1,(j))*(pow(j,2));
A((ny),j) = 1. * pow(j,2);
}
}
std::cout << A << "\n";
This replaces the first and last rows of the matrix A
| This is how I fixed the problem with help from @Sedenion in the comments:
Eigen::ArrayXi exponents((ny+1));
exponents = Eigen::ArrayXi::LinSpaced((ny+1), 0, (ny+1));
A.row(0) = -1. * (Eigen::pow(-1., exponents.cast<double>())) * (Eigen::pow(exponents.cast<double>(),2)) ; //first row
A.row((ny)) = 1. * (Eigen::pow(exponents.cast<double>(),2)) ; //last row
|
72,672,723 | 72,673,061 | What is the fastest way to see if the values from a 2 dimensional array are present in 3 other two dimensional arrays | I have 4 integer two dimensional arrays of the form:
{{1,2,3},{1,2,3},{1,2,3}}
The first 3(A,B,C) are of size/shape [1000][3] and the 4th(D) [57100][3].
The combination of integers in the 3 elements sub-arrays in A,B,C are all unique, while combinations of integers in the 3 elements sub-arrays in D are not.
What I have to do is to find in what array from A,B or C a sub-array from D is present and do something with it after, depending in which array I find it.
I tried using nested for loops with if statements and check each array one at a time (A->B->C) and break out when I find it but it takes to long.
Thank you
| As suggested by my comments, let's assume your approach is a naive, look at one item at a time in a for loop to see if a match is found.
Instead of doing that, another approach is to store the arrays as a std::set<std::tuple<int, int, int>> and do a lookup on the sets. Doing this reduces the time complexity from linear to logarithmic. For example, a 1000 item set will have at most 10 tests to finally determine if the item exists instead of having to go through all 1000 items.
Here is a somewhat untested example. Note that the data in the arrays has not been populated (the assumption is that the data has been populated into the arrays):
#include <tuple>
#include <set>
#include <array>
#include <iostream>
using TupleSet = std::set<std::tuple<int, int, int>>;
int A[1000][3];
int B[1000][3];
int C[1000][3];
int D[57100][3];
void printTuple(const std::tuple<int,int,int>& ts)
{
std::cout << std::get<0>(ts) << "," <<
std::get<1>(ts) << "," <<
std::get<2>(ts) << "\n";
}
// Initialize the tuple set with the 3 column 2D array of items
void initializeTuple(int pArray[][3], int numItems, TupleSet& ts)
{
for (int i = 0; i < numItems; ++i)
ts.insert({pArray[i][0], pArray[i][1], pArray[i][2]});
}
int main()
{
// Assume that A, B, C, and D have been filled in with data
//...
static constexpr char *arrayName = "ABC";
// Declare an array of 3 tuple sets that represent A,B,C
std::array<TupleSet, 3> allTuples;
// This is for the "special" D Array
TupleSet tD;
//Store the data in the tuples
initializeTuple(A, 1000, allTuples[0]);
initializeTuple(B, 1000, allTuples[1]);
initializeTuple(C, 1000, allTuples[2]);
initializeTuple(D, 57100, tD);
// Now go through each tuple in D to see if it's
// in A, B, or C
for (auto& t : tD)
{
// print the tuple we're searching for
printTuple(t);
// Now see if it's in A, B, or C
for (int i = 0; i < 3; ++i)
{
auto iter = allTuples[i].find(t);
if ( iter != allTuples[i].end() )
{
std::cout << "Found a match in Array " <<
arrayName[i] << "\n";
break;
}
}
}
}
Note how each 2D array is placed in a tuple set. Also, since a std::set does not store duplicates, the D array will have all of its duplicates removed when placed in the tuple set tD. Thus right there, the number of items that D represents will be minimized.
However, there are some issues you should be aware of:
The initial setup time of the tuples is part of this solution. However the setup time is done only once.
It may be even faster to use a std::unordered_set, but that would require you to write a hash function, and I leave that as an exercise to you.
|
72,672,761 | 72,672,802 | C++ Pass a string as a value or const string& | Say I have such simple functions:
struct Data {
string name;
string value; // Can be very long
};
// Use Data directly to avoid copy. (Not Data*)
unordered_map<size_t, Data> g_data;
// Should I use "const string& name, const string& value"?
void addData(string name, string value) {
// Should I use any std::move? Like:
// ... = {std::move(name), std::move(value)};
g_data[hash(name, value)] = {name, value};
}
// Returning as string seems obvious.
string generateData() {
// Some computation...
return value;
}
void test() {
addData(generateName(), generateDatA());
}
I know that the above code works. But I'm wondering whether I should use const string& in addData? I also wonder std::move can make it more efficient?
I'm using at least C++14, and C++17 is also enabled.
| Yes, you should use std::move, but not like this. The proposed piece of code would try to hash moved-from strings (pre-C++17 it was unspecified if the strings would be already moved from at that point, see rule #20 here).
You should pre-calculate the hash and store it in a variable:
auto h = hash(name, value);
g_data[h] = {std::move(name), std::move(value)};
You should NOT pass string name, string value by const reference, since it would prevent you from moving them.
|
72,672,775 | 72,674,201 | can't open file using c++ | I am using linux g++ compiler and also visual studio code to compile and run the code below and each time I run it, it returns with could't open file. i have put the text file in the same folder as the c++ program but still to no avail.
Can anyone point out where I have gone wrong?
The code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]) {
if (argc < 1) {
cerr << "Usage: " << argv[0] << "filename.txt" << endl;
}
ifstream ifile(argv[1]);
if (ifile.fail()) {
cerr << "Could not open file." << endl;
return 1;
}
return 0;
}
|
Make sure that you have given the filename to the program as an
argument.
After being compiled by g++, you should run the program like this:
./program filename.txt
argv[1] is the first program argument, in this case
"filename.txt".
Make sure that whatever launches the program is in the same working directory
Make sure that the file program has sufficient permissions to read the file. This can be changed with chmod.
|
72,673,067 | 72,679,309 | Running parameterized queries in QSqlTableModel | I have a QTableView and I am using a derived class SqlTableModel of QSqlTableModel to fetch data from a MySQL database. I want to prevent injection. I ran a union injection and it was easier than taking candy from a baby. The SQL query utilizes the LIKE keyword.
Attempt 1 (injectable):
QString query = QString("select * from table where col like '%%1%'").arg(edit->text());
QSqlQuery q(query);
SqlTableModel *model = new SqlTableModel();
model->setQuery(q);
model->select();
tableView->setModel(model);
Attempt 2 (no data is returned, no errors):
QString query = "select * from table";
QSqlQuery q(query);
SqlTableModel *model = new SqlTableModel();
model->setQuery(q);
model->setFilter(QString("col like '%%1%'").arg(edit->text()));
model->select();
tableView->setModel(model);
Attempt 3 (no data is returned, no errors):
QString query = "select * from table where col like :param";
QSqlQuery q(query);
q.prepare(query);
q.bindValue(":param", QString("%%1%").arg(edit->text()));
SqlTableModel *model = new SqlTableModel();
model->setQuery(q);
model->select();
tableView->setModel(model);
| It looks like you are using QSqlTableModel in wrong way. The common usage is to setTable with subsequent select call, according to docs
model->setTable("table");
model->select()
Filter can be set using setFilter
model->setFilter(QString("col like '%%1%'").arg(edit->text()));
Meanwhile you use a QSqlTableModel like it's a QSqlQueryModel with setQuery call. Even if it should work, then according to docs query should be active, i.e. QSqlQuery::exec should be called before setQuery call.
So, finally, you should use QSqlTableModel in the way as it assumed, like
SqlTableModel *model = new SqlTableModel();
model->setTable("table");
model->setFilter(QString("col like '%%1%'").arg(edit->text()));
model->select();
tableView->setModel(model);
If you want to build a query yourself, then you should use a QSqlQueryModel based class, like
QString query = "select * from table where col like '%%1%'";
QSqlQuery q(query);
q.prepare();
q.addBindValue(edit->text());
q.exec();
QSqlQueryModel *model = new QSqlQueryModel();
model->setQuery(std::move(q));
tableView->setModel(model)
|
72,673,531 | 72,673,605 | How to separate strings into 2D vector? | This is the file with data that I'm reading from:
MATH201,Discrete Mathematics
CSCI300,Introduction to Algorithms,CSCI200,MATH201
CSCI350,Operating Systems,CSCI300
CSCI101,Introduction to Programming in C++,CSCI100
CSCI100,Introduction to Computer Science
CSCI301,Advanced Programming in C++,CSCI101
CSCI400,Large Software Development,CSCI301,CSCI350
CSCI200,Data Structures,CSCI101
I have successfully read from the file and stored this information in a 2D Vector, but when I check the size of specific rows using course.info[x].size() it appears that its only counting the strings that have spaces between them. So for example, course.info[2].size() returns 2, whereas I would rather it would return 3. Essentially I want it to count each bit of information that is separated by a comma instead of a space. If I use while (getline(courses, line, ',') it puts the information separated by a comma in their own row, which is not what I want.
void LoadFile() {
vector<vector<string>> courseInfo;
ifstream courses;
courses.open("CourseInfo.txt");
if (!courses.is_open()) {
cout << "Error opening file";
}
if (courses) {
string line;
while (getline(courses, line)) {
courseInfo.push_back(vector<string>());
stringstream split(line);
string value;
while (split >> value) {
courseInfo.back().push_back(value);
}
}
}
for (int i = 0; i < courseInfo.size(); i++) {
for (int j = 0; j < courseInfo[i].size(); j++)
std::cout << courseInfo[i][j] << ' ';
std::cout << '\n';
}
| getline(.., .., ',') is the tool for the job, but you need to use it in a different place.
Replace while (split >> value) with while (getline(split, value, ',').
|
72,673,535 | 72,683,207 | Will built-in `operator->` be used if I don't overload it? | The builtin operator-> is defined as (*p).m, which is just fine for my iterator, so overloading it would just waste my time and the maintainer's eyes.
Just trying it wouldn't guarantee portability, and I haven't been able to find an answer, though I fear that it is no, because apparently nobody has even considered it before.
Update:
I made a minimal test program to actually try this:
struct S { int m;};
struct P
{ auto& operator*() const { return s;}
auto operator->() const =default;// { return &s;}
S s;
};
int main()
{ P p;
p->m;
}
g++ (Debian 8.3.0-6) compiles this only without =default;//, so seems like defaulting or omitting the overload won't be portable for years at least.
|
Will built-in operator-> be used if I don't overload it?
No, only certain special member functions are implicitly declared for a given class-type(and that too under certain circumstances). And operator-> is not one of them. This can be seen from special members which states:
The six special members functions described above are members implicitly declared on classes under certain circumstances:
Default ctor
Dtor
Copy ctor
Copy assignment
Move ctor
Move assignment
(emphasis mine)
Note in the above list, there is no mention of operator->. This means that if you want to use -> with an object of your class-type then you must overload it explicitly.
Now, coming to your question about the error that you're getting.
compiles this only with the commented out definition, so seems like defaulting or omitting the overload won't be portable for years at least.
You're getting the error because operator-> cannot be defaulted. This can be seen from the same special members documentation which says:
each class can select explicitly which of these members exist with their default definition or which are deleted by using the keywords default and delete, respectively.
(emphasis mine)
Note the emphasis on "these members" above. In particular, only the six special members listed above can be defaulted. And again since operator-> is not one of them, it can't be defaulted using default.
|
72,673,802 | 72,673,819 | Inserting elements to vector in c++ | I need to insert for every element of vector it's opposite.
#include <iostream>
#include <vector>
int main() {
std::vector < int > vek {1,2,3};
std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl;
for (int i = 0; i < 3; i++) {
std::cout << i << " " << vek[i] << std::endl;
vek.insert(vek.begin() + i + 1, -vek[i]);
}
std::cout << std::endl;
for (int i: vek) std::cout << i << " ";
return 0;
}
OUTPUT:
1 2 3
0 1 // it should be 0 1 (because vek[0]=1)
1 -1 // it should be 1 2 (because vek[1]=2)
2 1 // it should be 2 3 (because vek[2]=3)
1 -1 1 -1 2 3 // it should be 1 -1 2 -2 3 -3
Could you explain me why function insert doesn't insert the correct value of vector? What is happening here?
Note: Auxiliary vectors (and other data types) are not allowed
| During the for loop, you are modifying the vector:
After the first iteration which inserts -1, the vector becomes [1, -1, 2, 3]. Therefore, vec[1] becomes -1 rather than 2. The index of 2 becomes 2. And after inserting -2 into the vector, the index of the original value 3 becomes 4.
In the for loop condition, you need to add index i by 2, instead of 1:
#include <iostream>
#include <vector>
int main() {
std::vector < int > vek {1,2,3};
std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl;
for (int i = 0; i < 3 * 2; i+=2) {
std::cout << i << " " << vek[i] << std::endl;
vek.insert(vek.begin() + i + 1, -vek[i]);
}
std::cout << std::endl;
for (int i: vek) std::cout << i << " ";
return 0;
}
|
72,673,837 | 72,674,114 | C++11: how to use lambda as type parameter, where it requires a "functor type" like std::less/std::greater? | I'm trying to pass a type parameter to priority_queue, just like std::less or std::greater, like this:
priority_queue<int, vector<int>, [](int x, int y){return x>y;})> q;
It doesn't compile, then I added decltype, still fails:
priority_queue<int, vector<int>, decltype([](int x, int y){return x>y;}))> q;
Question is, can we use lambda in this case, how to achieve it?
| There are multiple ways:
Let the compiler deduce the type of lamabda by using decltype(lambda). But one thing you need to keep in mind: Prior to C++20, lambda type does not have a default constructor. As of C++20, ONLY stateless lambda (lambda without captures) has a default constructor, while stateful lambda (i.e., lambda with captures) has no default constructor (This is clearly documented on cppreference.com). Why does the default constructor matter here? The answer is that if a default constructor exists, you don't have to pass a compare function (cmp) to the priority_queue constructor as long as you specified the lambda type as the template argument. Since the default constructor exists only for stateless lambda starting from C++20, you'd better explicitly pass a cmp argument to the constructor:
auto cmp = [](int x, int y){return x>y;};
priority_queue<int, vector<int>, decltype(cmp)> q(cmp);
Use the <functional> header to explicitly specify the lambda type:
#include <functional>
...
priority_queue<int, vector<int>, function<bool(int, int)>> q(cmp);
Use a function-obejct class. In this case, you only need to specify the function-object class as a template type argument, and you don't need to pass the cmp argument to the constructor, because your own defined function-object class has a default (synthesized) constructor.
struct Cmp {
bool operator()(int x, int y) {return x > y;}
};
priority_queue<int, vector<int>, Cmp> q;
Use the library-defined function objects whenever possible.
priority_queue<int, vector<int>, std::greater<int>> q;
|
72,673,961 | 72,674,021 | Visual Studio Code - C/C++ Extension commands don't exist | I've been using WSL2 with the C/C++ Extension on Visual Studio Code for quite a while now, but recently, it stopped working. Whenever I try to run a command, such as Edit Configurations, this error pops up:
Text version:
Command 'C/C++: Edit Configurations (UI)' resulted in an error (command 'C_Cpp.ConfigurationEditUI' not found)
Note that this happens for every command from that extension, and other commands work perfectly fine (including from other extensions). My IntelliSense has also stopped working properly (nothing appears when I click CTRL+SPACE, etc).
I tried reinstalling the extension multiple times, including going to previous versions, deleting the folder, restarting my computer, etc., but nothing ever helped. There seem to be no errors in the console either.
This happened right after I installed the PROS Extension for VSCode which happens to have a dependency for clangd, which I believe is the problem (I'm on Windows Subsystem for Linux, meaning the extension is installed on Ubuntu, and I use the GNU GCC/G++ compiler). Does anyone know how I can fix this? (I don't want to reinstall Visual Studio Code or do anything drastic as I have a lot of extensions with lots of configurations that would be lost if I do so).
| This is an issue because clangd and intellisense do not work together. If you disabled intellisense in favor of clangd then the c/c++ configuration json/ui commands will not work. Instead of the configuration for the c/c++ extension you must generate a compile_commands.json for clangd using CMAKE. The fix that worked for me in order to revert back to the c/c++ configuration was to completely uninstall vscode and re-intall a clean version (attempted to uninstall all extensions). Though, I'm sure there is a solution that does not require a clean install.
Edit: fix avoiding clean install :
uninstall clangd from the extensions
Go to File->Preferences->Parameters
In the search box at the top, type "Intellisense engine"
Look for C_Cpp: IntelliSense Engine and set the value to "Default"
side note:
In my opinion, Clangd is faster than intellisense at syntax highlighting which was the main incentive for me to install clangd in the first place. So if that is ever an issue for you it may be worth diving in.
|
72,673,966 | 72,673,976 | Using data from 2D vector at runtime in C++ | I have a function that takes the arguments of a 2D vector and writes the information from a file to that vector. But after I call the function and the data has been written to the vector, it acts as if the vector is empty, despite the vector being a accessible from anywhere in main. If do the printing within the load function it works just fine though.
This is my Load Function:
void LoadFile(vector<vector<string>> courseInfo) {
ifstream courses;
courses.open("CourseInfo.txt");
if (!courses.is_open()) {
cout << "Error opening file";
}
if (courses) {
string line;
while (getline(courses, line)) {
courseInfo.push_back(vector<string>());
stringstream split(line);
string value;
while (getline(split, value, ',')) {
courseInfo.back().push_back(value);
}
}
}
}
This is main:
int main(){
vector<vector<string>> courseInfo;
int choice = 0;
while (choice != 9) {
cout << "Menu:" << endl;
cout << " 1. Load Data Structure" << endl;
cout << " 2. Print Course List" << endl;
cout << " 3. Print Course" << endl;
cout << " 9. Exit" << endl;
cout << "What would you like to do? ";
cin >> choice;
switch (choice) {
case 1:
//load data
LoadFile(courseInfo);
break;
case 2:
//print course list
for (int i = 0; i < courseInfo.size(); i++) {
for (int j = 0; j < courseInfo[i].size(); j++)
std::cout << courseInfo[i][j] << ' ';
std::cout << '\n';
}
break;
case 3:
//print course
break;
default:
cout << choice << " Goodbye" << endl;
}
}
}
If I try to print the information after loading it, nothing gets printed. I tried returning the vector with the function, but that made no difference.
| void LoadFile(vector<vector<string>> courseInfo) { ... }
This creates a copy of the vector because you pass it by value. You then store all the data in the copy and at the end of the function the copy is destroyed. At no point do you modify the original vector. Change it to
void LoadFile(vector<vector<string>> &courseInfo) { ... }
|
72,674,069 | 72,678,218 | How can a WOW64 program overwrite its command-line arguments, as seen by WMI? | I'm trying to write a program that can mask its command line arguments after it reads them. I know this is stored in the PEB, so I tried using the answer to "How to get the Process Environment Block (PEB) address using assembler (x64 OS)?" by Sirmabus to get that and modify it there. Here's a minimal program that does that:
#include <wchar.h>
#include <windows.h>
#include <winnt.h>
#include <winternl.h>
// Thread Environment Block (TEB)
#if defined(_M_X64) // x64
PTEB tebPtr = reinterpret_cast<PTEB>(__readgsqword(reinterpret_cast<DWORD_PTR>(&static_cast<NT_TIB*>(nullptr)->Self)));
#else // x86
PTEB tebPtr = reinterpret_cast<PTEB>(__readfsdword(reinterpret_cast<DWORD_PTR>(&static_cast<NT_TIB*>(nullptr)->Self)));
#endif
// Process Environment Block (PEB)
PPEB pebPtr = tebPtr->ProcessEnvironmentBlock;
int main() {
UNICODE_STRING *s = &pebPtr->ProcessParameters->CommandLine;
wmemset(s->Buffer, 'x', s->Length / sizeof *s->Buffer);
getwchar();
}
I compiled this both as 32-bit and 64-bit, and tested it on both 32-bit and 64-bit versions of Windows. I looked for the command line using Process Explorer, and also by using this PowerShell command to fetch it via WMI:
Get-WmiObject Win32_Process -Filter "name = 'overwrite.exe'" | Select-Object CommandLine
I've found that this works in every combination I tested it in, except for using WMI on a WOW64 process. Summarizing my test results in a table:
Architecture
Process Explorer
WMI
64-bit executable on 64-bit OS (native)
βοΈ xxxxxxxxxxxxx
βοΈ xxxxxxxxxxxxx
32-bit executable on 64-bit OS (WOW64)
βοΈ xxxxxxxxxxxxx
β overwrite.exe
32-bit executable on 32-bit OS (native)
βοΈ xxxxxxxxxxxxx
βοΈ xxxxxxxxxxxxx
How can I modify my code to make this work in the WMI WOW64 case too?
| wow64 processes have 2 PEB (32 and 64 bit) and 2 different ProcessEnvironmentBlock (again 32 and 64). the command line exist in both. some tools take command line correct (from 32 ProcessEnvironmentBlock for 32bit processes) and some unconditional from 64bit ProcessEnvironmentBlock (on 64 bit os). so you want zero (all or first char) of command line in both blocks. for do this in "native" block we not need access TEB/PEB/ProcessEnvironmentBlock - the GetCommandLineW return the direct pointer to the command-line string in ProcessEnvironmentBlock. so next code is enough:
PWSTR psz = GetCommandLineW();
while (*psz) *psz++ = 0;
or simply
*GetCommandLineW() = 0;
is enough
as side note, for get TEB pointer not need write own macro - NtCurrentTeb() macro already exist in winnt.h
access 64 bit ProcessEnvironmentBlock from 32 bit process already not trivial.
one way suggested in comment.
another way more simply, but not documented - call NtQueryInformationProcess with ProcessWow64Information
When the ProcessInformationClass parameter is ProcessWow64Information, the buffer pointed to by the
ProcessInformation parameter should be large enough to hold a
ULONG_PTR. If this value is nonzero, the process is running in a WOW64
environment. Otherwise, the process is not running in a WOW64
environment.
so this value receive some pointer. but msdn not say for what he point . in reality this pointer to 64 PEB of process in wow64 process.
so code can be next:
#ifndef _WIN64
PEB64* peb64;
if (0 <= NtQueryInformationProcess(NtCurrentProcess(),
ProcessWow64Information, &peb64, sizeof(peb64), 0) && peb64)
{
// ...
}
#endif
but declare and use 64 bit structures in 32bit process very not comfortable (need all time check that pointer < 0x100000000 )
another original way - execute small 64bit shellcode which do the task.
the code doing approximately the following:
#include <winternl.h>
#include <intrin.h>
void ZeroCmdLine()
{
PUNICODE_STRING CommandLine =
&NtCurrentTeb()->ProcessEnvironmentBlock->ProcessParameters->CommandLine;
if (USHORT Length = CommandLine->Length)
{
//*CommandLine->Buffer = 0;
__stosw((PUSHORT)CommandLine->Buffer, 0, Length / sizeof(WCHAR));
}
}
you need create asm, file (if yet not have it in project) with the next code
.686
.MODEL FLAT
.code
@ZeroCmdLine@0 proc
push ebp
mov ebp,esp
and esp,not 15
push 33h
call @@1
;++++++++ x64 +++++++++
sub esp,20h
call @@0
add esp,20h
retf
@@0:
DQ 000003025048b4865h
DQ 0408b4860408b4800h
DQ 00de3677048b70f20h
DQ 033e9d178788b4857h
DQ 0ccccc35fab66f3c0h
;-------- x64 ---------
@@1:
call fword ptr [esp]
leave
ret
@ZeroCmdLine@0 endp
end
the code in the DQs came from this:
mov rax,gs:30h
mov rax,[rax+60h]
mov rax,[rax+20h]
movzx ecx,word ptr [rax+70h]
jecxz @@2
push rdi
mov rdi,[rax+78h]
shr ecx,1
xor eax,eax
rep stosw
pop rdi
@@2:
ret
int3
int3
custom build: ml /c /Cp $(InputFileName) -> $(InputName).obj
declare in c++
#ifdef __cplusplus
extern "C"
#endif
void FASTCALL ZeroCmdLine(void);
and call it.
#ifndef _WIN64
BOOL bWow;
if (IsWow64Process(GetCurrentProcess(), &bWow) && bWow)
{
ZeroCmdLine();
}
#endif
|
72,674,071 | 72,674,795 | Visual Studio C++ How to Specify Relative Resource Path For Final Build | I already know how to set a relative working directory path and access resources inside of visual studio. However, when I build my solution and move the exe to a separate file I have to include all the resources in the same directory as the exe. I'd prefer to have a folder with said resources alongside the exe to keep things clean. Is there a macro I need to use? Is the working directory the right setting to change for this?
example
Sorry for this incredibly basic question, but I think I lack the vocabulary to accurately describe the issue.
| For a Windows solution, GetModuleFileName to find the exact path of your EXE. Then a simple string manipulation to make a resource path string.
When you program starts, you can use this to ascertain the full path of your EXE.
std::string pathToExe(MAX_PATH, '\0');
GetModuleFileName(nullptr, szPathToExe.data(), MAX_PATH); // #include <windows.h> to get this function declared
On return, szPathToExe will be something like "C:\\Path\\To\\Your\\Program\\Circle.exe"
Then strip off the file name to get the absolute path
std::string resourceFolderPath = szPathToExe;
size_t pos = strPath.find_last_of("\\");
strPath = strPath.substr(0, pos+1); //+1 to include the backslash
Then append your resource folder name and optionally another trailing backslash.
resourceFolderPath += "res\\";
Then change all your I/O calls to open files relative to resourceFolderPath
You should probably add reasonable error checking to the above code such as validating the return code from GetModuleFileName and find_last_of calls.
|
72,674,420 | 72,674,511 | How do I properly derive from a nested struct? | I have an abstract (templated) class that I want to have its own return type InferenceData.
template <typename StateType>
class Model {
public:
struct InferenceData;
virtual InferenceData inference () = 0;
};
Now below is an attempt to derive from it
template <typename StateType>
class MonteCarlo : public Model<StateType> {
public:
// struct InferenceData {};
typename MonteCarlo::InferenceData inference () {
typename MonteCarlo::InferenceData x;
return x;
}
};
This works, but only because the definition of MonteCarlo::InferenceData is commented out. If it is not commented, I get invalid covariant return type error. I want each ModelDerivation<StateType>::InferenceData
to be its own type and have its own implementation as a struct. How do I achieve this?
| You cannot change the return type of a derived virtual method.
This is why your compilation failed when you try to return your derived InferenceData from MonteCarlo::inference().
In order to achieve what you need, you need to use a polymorphic return type, which requires pointer/reference semantics.
For this your derived InferenceData will have to inherit the base InferenceData, and inference() should return a pointer/reference to the base InferenceData.
One way to do it is with a smart pointer - e.g. a std::unique_ptr - see the code below:
#include <memory>
template <typename StateType>
class Model {
public:
struct InferenceData {};
virtual std::unique_ptr<InferenceData> inference() = 0;
};
template <typename StateType>
class MonteCarlo : public Model<StateType> {
public:
struct InferenceDataSpecific : public Model<StateType>::InferenceData {};
virtual std::unique_ptr<Model::InferenceData> inference() {
return std::make_unique<InferenceDataSpecific>();
}
};
int main()
{
MonteCarlo<int> m;
auto d = m.inference();
return 0;
}
Note: if you need to share the data, you can use a std::shared_ptr.
|
72,674,454 | 72,674,670 | LineTo() draw line in wrong place | I want to add a line to my text in notepad when printing a pdf, for these purpose I hook Enddoc function and use GDILineTo(). but when I print my text, the LineTo()creates new page at the end of pdf and draws Line in it. does any body knows how can I draw line in all pdf pages without create new page ?
here is my code:
int StopPrint::hookFunction(HDC hdc, const DOCINFOW *lpdi)
{
HPEN hPen1 = CreatePen(PS_SOLID, 1, BLACK_PEN);
HGDIOBJ l = hPen1;
HPEN holdPen = (HPEN)SelectObject(hdc, l);
SelectObject(hdc, hPen1);
MoveToEx(hdc, 500, 500, NULL);
LineTo(hdc, 2000, 2000);
return getOriginalFunction()(hdc, lpdi);
}
| I've no idea if this will work or quite what you're up to, but I think you need to 'hook' EndPage rather than EndDoc. Also, your hook function is broken in various ways so try this:
int StopPrint::EndPageHook(HDC hdc)
{
HPEN holdPen = (HPEN) SelectObject(hdc, GetStockObject (BLACK_PEN));
POINT old_pos;
MoveToEx(hdc, 500, 500, &old_pos);
LineTo(hdc, 2000, 2000);
MoveToEx(hdc, old_pos.x, old_pos,y, NULL);
SelectObject(hdc, holdPen);
return getOriginalEndPage()(hdc);
}
Pretty weird line BTW, that looks wrong to me. Might want to start from (something derived from) the current position, see what you get.
|
72,674,526 | 72,674,608 | c++ std::map compare function leads to runtime "bad_function_call" | I'm declaring my std::map and use it below:
map<int, int, function<bool (int, int)>> m;
m.insert(make_pair(12,3));
m.insert(make_pair(3,4));
for(auto & p : m){
cout << p.first << "," << p.second << endl;
}
g++ compiles, no error.
Template parameter only requires a type, but no function body is required, passes compilation. I was wondering how this empty comparer would behave. On running it:
terminate called after throwing an instance of 'std::bad_function_call'
what(): bad_function_call
I only see this error in calling pure virtual function. But my code is using stl template, no polymorphism is in place.
So is this a c++ design issue, that compilation doesn't check if a function only has declaration but no function body to run? Plus, how would c++ standard deal with this?
Appreciate your explanations.
| The problem is not related to the template argument, but that you did not provide an actual value for it when constructing the map.
Note that in the documentation for the map constructor, there is a const Compare& parameter. It is via this parameter that you must give a value for your comparator which in this case is a lambda.
explicit map( const Compare& comp,
const Allocator& alloc = Allocator() );
For example:
#include <functional>
#include <iostream>
#include <map>
using namespace std;
int main()
{
auto comp = [](int a, int b) { return a > b; };
map<int, int, function<bool (int, int)>> m(comp);
m.insert(make_pair(12,3));
m.insert(make_pair(3,4));
for(auto & p : m){
cout << p.first << "," << p.second << endl;
}
}
Outputs:
12,3
3,4
|
72,674,869 | 72,674,894 | C++ pure virtual function call doesn't throw run-time exception? | It's said that in C++ constructor function, as long as the object has not finished construction, shouldn't call virtual function, or else there'll be "pure virtual function call error" thrown out. So I tried this:
#include<stdio.h>
class A{
virtual void f() = 0;
};
class A1 : public A{
public:
void f(){printf("virtual function");}
A1(){f();}
};
int main(int argc, char const *argv[]){
A1 a;
return 0;
}
compile it with g++ on windows, it works and prints
virtual function
So how to make my program throw out "pure virtual function call" exception?
Thanks!
| You are not getting the "pure virtual method call" exception because A::f() is not being called.
A1's constructor is calling its own A1::f() method, which is perfectly safe to do during A1's construction.
The issue with calling a virtual method in a constructor has to do with a base class constructor calling a derived class method, which doesn't work since the derived portion of the object being constructed doesn't exist yet.
So, to get the exception you want, you need to call f() in A's constructor rather than in A1's constructor.
|
72,676,233 | 72,676,311 | loop as long an user input is given | I don't know how to write correct condition in my while loop. I want my program to loop as long as user will give an input value. So user gives values, program prints result and asks the same thing again. When user does not give any input and just presses enter i want my program to finish. Here is my code:
#include <iostream>
using namespace std;
int main(){
int a,b;
string symbol;
while(true){
cin>>symbol;
if(symbol=="+"){
cin>>a;
cin>>b;
cout<<a+b<<endl;
}
else if(symbol=="-"){
cin>>a;
cin>>b;
cout<<a-b<<endl;
}
else if(symbol=="*"){
cin>>a;
cin>>b;
cout<<a*b<<endl;
}
else if(symbol=="/"){
cin>>a;
cin>>b;
cout<<a/b<<endl;
}
else if(symbol=="%"){
cin>>a;
cin>>b;
cout<<a%b<<endl;
}
}
}
I know that this code is probably poorly written but i just want it to work.
| You are asking for line based input, you said When user does not give any input and just presses enter i want my program to finish. But the input method you are using cin >> symbol; skips all spaces and newlines. So it cannot meet your requirements.
Since you want to read lines of input you should use something that does read lines of input. That function is getline.
string line;
getline(cin, line);
But now you have another problem, how do you read the symbols and numbers from the string line?
For that you need to use an istringstream. A string stream is an object which reads from a string, instead of reading from the console like cin. Here's how to use it
#include <sstream>
string line;
getline(cin, line);
if (line.empty()) // check if any input
break; // and quit if not
istringstream buffer(line); // create the string stream
buffer>>symbol; // and read the symbol from it
if(symbol=="+"){
buffer>>a;
buffer>>b;
cout<<a+b<<endl;
}
...
See how buffer is created from the line string, and then buffer>>symbol and buffer>>a; etc are used to read from the buffer.
|
72,676,527 | 72,676,660 | Failed to show `` (UTF-16 character) in wxWidgets (C++) | I am using wxWidgets with Visual Studio 2022 (C++) to develop Windows application. I wish to display in the window, but as I tried using various fonts with the following code:
std::string fonts_name[8] = {"Calibri Light", "Calibri", "Cambria Math", "Cambria", "Candara Light", "Candara", "Consolas", "DFKai-SB"};
// ...
stat_txt_test = new wxStaticText*[8];
for (long long i = 0; i != 8; ++i) {
stat_txt_test[i] = new wxStaticText(this, (long long)1000 + i, "", wxPoint(i * 15, i * 15), wxSize(10, 10), wxTE_READONLY);
stat_txt_test[i]->SetFont(fonts[i]);
}
I only got .
However, if I use "a" (ascii character) instead, the result is , which is as expected.
Now I am guessing that UTF-16 does not work well in my code. However, Chinese characters worked very well. This is the unicode of .
How should I modify my code in order to get this job done?
My attempts
"\x1D465" does not work and I got the following message and failure to build:
error C2022: '119909': too big for character
"\xD835\xDC65" does not work (just a wild guess to use two characters to represent this character).
Any help will be appreciated. Thank you!
| As shown in the wxWidget's documentation, the correct way would be as shown below:
//---------------------------------------vvvvvvvvv---->changed to u instead of x
label = new wxStaticText(this, wxID_ANY, L"\u0078");
or
label = new wxStaticText(this, wxID_ANY, L"\U0001D465");
|
72,677,645 | 72,677,698 | When and how should I use std::predicate | I am trying to constrain a Callable to return a boolean when evaluated. I have been trying to use the concept std::predicate, but it does not seem to do what I want it to do.
So I defined my own concept, that is invokable and returns something convertible to a boolean. But again, I struggle understanding what I can or can not do with it, and I wonder what are the actual use cases of std::predicate?
#include<concepts>
#include<string>
template<class F, class... Args>
concept Predicate = std::invocable<F, Args...> &&
std::convertible_to<std::invoke_result_t<F, Args...>, bool>;
int main(int argc, char *argv[])
{
constexpr Predicate auto f1 = [](){return true;}; // ok
constexpr std::predicate auto f2 = [](){return true;}; // ok
constexpr int x = 34;
constexpr Predicate auto f3 = [x](){ return x==42;}; // ok
// Pas ok: error: deduced initializer does not satisfy placeholder constraints
//constexpr Predicate auto f4 = [](auto x){ return x==42;};
//constexpr std::predicate auto f5 = [](auto x){ return x==42;};
}
| You cannot have a function that takes a "thing that can be called". It must be a "thing that can be called with some set of arguments of known (at the time of the declaration) types". That's why std::predicate takes a set of arguments in addition to the potential callable type.
Your first examples work because you didn't give the predicate concept any arguments and your functions also didn't take any parameters. So an empty argument list matches the empty parameter list.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.