vendredi 31 août 2018

Optimizations are killing my integer overflow checks in clang 6

I have a fixed-point implementation for some financial application. It's basically an integer wrapped in a class that is based on the number of decimals given Ntreated as a decimal number. The class is paranoid and checks for overflows, but when I ran my tests in release mode, and they failed, and finally I created this minimal example that demonstrates the problem:

#include <iostream>
#include <sstream>

template <typename T, typename U>
typename std::enable_if<std::is_convertible<U, std::string>::value, T>::type 
FromString(U&& str)
{
    std::stringstream ss;
    ss << str;
    T ret;
    ss >> ret;
    return ret;
}

int main()
{
    int NewAccu=32;
    int N=10;

    using T = int64_t;

    T l = 10;
    T r = FromString<T>("1" + std::string(NewAccu - N, '0'));
    if (l == 0 || r == 0) {
        return 0;
    }
    T res = l * r;
    std::cout << l << std::endl;
    std::cout << r << std::endl;
    std::cout << res << std::endl;
    std::cout << (res / l) << std::endl;
    std::cout << std::endl;
    if ((res / l) != r) {
        throw std::runtime_error(
                   "FixedPoint Multiplication Overflow while upscaling [:" + std::to_string(l) + ", " + std::to_string(r) + "]");
    }

    return 0;
}

This happens with Clang 6, my version is:

$ clang++ --version
clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

It's funny because it's an impressive optimization, but this ruins my application and prevents me from detecting overflows. I was able to reproduce this problem in g++ here. It doesn't throw an exception there.

Is it possible to define a template parameter pack array

Possible duplicate: Is it possible to "store" a template parameter pack without expanding it?

Similar to the question above, I'd like to explore this more and store a variadic array.

template<size_t N, typename... Args>
void foo(Args(&...args)[N]) {
  Args[N]... args2; // compilation error
}

Is this possible to be accomplished?

The end goal is to be able to call foo, mutate a copy of its variadic array inputs, and execute some function on the mutations. So, something like:

template<typename F, size_t N, typename... Args>
void applyAsDoubled(F f, Args(&...args)[N]) {
  Args[N]... args2;
  doublerMutation(args2...); // doubles each argument; external function, assume it cannot avoid having a side-effect on its parameters

  for (int i = 0; i < N; i++)
    f(args2[i]...);
}

will be call and suffer no side-effects:

int A[N] = { 1, 2, 3, 4, 5 };
int B[N] = { 2, 2, 2, 2, 2 };

applyAsDoubled(printAdded, A, B);

will print 6, 8, 10, 12, 14 where A and B are not mutated. Just to clarify, the function doublerMutation is a dummy function to represent a function that will cause mutations for arguments and cannot be rewritten.

Getting input X/X/etc with char X and separating it with slash /

I make program build with C++. My program is convert binary to decimal and the decimal convert to alphabet. The input is separated with slash "/"

input example :

input : 00001/00010/00011

output : abc

this is my code

#include <iostream>
#include <conio.h>
#include <cstring>

using namespace std;
int main()
{
char X[64];
int T,d=0,i=0,j;
scanf("%[^/]/%d", X);
while(X[i]!=0)
{    if(X[i]=='0'||X[i]=='1')
    {
        d=d*2+X[i]-48;
    }i++;
}
switch (d)
{
    case 1:
        cout<<"a";
        break;
    case 2:
        cout<<"b";
        break;
    case 3:
        cout<<"c";
        break;
    case 4:
        cout<<"d";
        break;
    case 5:
        cout<<"e";
        break;
    case 6:
        cout<<"f";
        break;
    case 7:
        cout<<"g";
        break;
    case 8:
        cout<<"h";
        break;
    case 9:
        cout<<"i";
        break;
    case 10:
        cout<<"j";
        break;
    case 11:
        cout<<"k";
        break;
    case 12:
        cout<<"l";
        break;
    case 13:
        cout<<"m";
        break;
    case 14:
        cout<<"n";
        break;
    case 15:
        cout<<"o";
        break;
    case 16:
        cout<<"p";
        break;
    case 17:
        cout<<"q";
        break;
    case 18:
        cout<<"r";
        break;
    case 19:
        cout<<"s";
        break;
    case 20:
        cout<<"t";
        break;
    case 21:
        cout<<"u";
        break;
    case 22:
        cout<<"v";
        break;
    case 23:
        cout<<"w";
        break;
    case 24:
        cout<<"x";
        break;
    case 25:
        cout<<"y";
        break;
    case 26:
        cout<<"z";
        break;
}
cout << endl;
}

I have used a number of ways that are still unable, and only the front binary can be read. Sorry for my bad english

C++: Parameter type that requires inheritance from few interface-like classes

I want to be able to create non-template function that requires type of class to be inherited from few another classes.

Something like that

class A1
{};

class A2
{};

class A3
{};

class B: public A1, public A2, public A3
{};

class C: public A1, public A3
{};

void Foo(const C&)
{}

int main(void)
{
    B b;
    C c;

    Foo(b); // error. But B inherited from A1 and A3, so I want to be able pass it
    Foo(c); // ok

    return 0;
}

I will glad to hear any suggestions to solve the problem.

Note: some languages like Swift and Objective-C have this functionality as part of the language calling 'conforming protocols'

error: call of overloaded distance is ambiguous

I have a bit of code (which I didn't write, but am trying to compile) -- iostream_combo.cc--, and doing so gives me the following error:

./moses/moses/comboreduct/combo/iostream_combo.cc: In function ‘std::__cxx11::string opencog::combo::l2ph(const string&, const std::vector >&)’: ./moses/moses/comboreduct/combo/iostream_combo.cc:543:64: error: call of overloaded ‘distance(std::vector

::const_iterator, __gnu_cxx::__normal_iterator*, std::vector > >&)’ is ambiguous arity_t idx = distance(labels.begin(), found_it) + 1; ^ In file included from /usr/include/c++/8/bits/stl_algobase.h:66, from /usr/include/c++/8/bits/char_traits.h:39, from /usr/include/c++/8/ios:40, from /usr/include/c++/8/ostream:38, from /usr/include/c++/8/iostream:39, from ./moses/moses/comboreduct/combo/iostream_combo.h:28, from ./moses/moses/comboreduct/combo/iostream_combo.cc:24: /usr/include/c++/8/bits/stl_iterator_base_funcs.h:138:5: note: candidate: ‘typename std::iterator_traits<_Iterator>::difference_type std::distance(_InputIterator, _InputIterator) [with _InputIterator = __gnu_cxx::__normal_iterator*, std::vector > >; typename std::iterator_traits<_Iterator>::difference_type = long int]’ distance(_InputIterator __first, _InputIterator __last) ^~~~~~~~ In file included from /usr/local/include/boost/range/distance.hpp:18, from /usr/local/include/boost/range/functions.hpp:21, from /usr/local/include/boost/range/iterator_range_core.hpp:38, from /usr/local/include/boost/lexical_cast.hpp:30, from ./moses/moses/comboreduct/combo/iostream_combo.h:30, from ./moses/moses/comboreduct/combo/iostream_combo.cc:24: /usr/local/include/boost/iterator/distance.hpp:49:9: note: candidate: ‘constexpr typename boost::iterators::iterator_difference::type boost::iterators::distance_adl_barrier::distance(SinglePassIterator, SinglePassIterator) [with SinglePassIterator = __gnu_cxx::__normal_iterator*, std::vector > >; typename boost::iterators::iterator_difference::type = long int]’ distance(SinglePassIterator first, SinglePassIterator last) ^~~~~~~~

I'm using Ubuntu 16.04 x64, Boost 1.68 and gcc 8.2.

I understand C++ enough (I think) that I can see that the call to std::distance is overloaded. What I don't see is the way to disambiguate it, although I guess it must include some re-writing of found_it or some explicit castings instead of auto.

Can we use conventional pointer arithmetic with std::array?

I want to work out how to use old style pointer arithmetic on pointers to elements of the std::array class. The following code (unsurprisingly perhaps) does not compile:

int main(int argc, char *argv[])
{
    double* data1 = new double[2];
    std::cout << *data1 << " " << (data1 +1)* << std::endl;
    delete data1;
    data1 = NULL;

    double* data2 = new std::array<double, 2>;
    std::cout << data2* << " " << (data2 +1)* << std::endl;
    delete data2;
    data2 = NULL;

    return 0;
}

As an exercise, I want to use all the conventional pointer arithmetic, but instead of pointing at an old style double array, I want it to point to the elements of a std::array. My thinking with this line:

    double* data2 = new std::array<double, 2>;

is to instruct the compiler that data2 is a pointer to the first element of the heap allocated std::array<double,2>.

I have been taught that the double* name = new double[size]; means EXACTLY the following: «Stack allocate memory for a pointer to ONE double and name the pointer name, then heap allocate an array of doubles of size size, then set the pointer to point to the first element of the array.» Since the above code does not compile, I must have been taught something incorrect since the same syntax doesnt work for std::arrays.

This raises a couple of questions:

  1. What is the actual meaning of the statement type* name = new othertype[size];?
  2. How can I achieve what I want using std::array?
  3. Finally, how can I achieve the same using std::unqiue_ptr and std::make_unique?

What is the lock state after CondVar.notify_all(); instruction?

I encountered this snippet of code in a book and it looks very strange to me since the convention is to release always the lock but when notify_all() gets called it is not.

My question is whether the lock called from unique_lock gets released automatically after the block gets exited? I know this is released by using RAII lock_guard but that is not my concerned.

class Logger
{
    public:
    // Starts a background thread writing log entries to a file.
    Logger();
    // Prevent copy construction and assignment.
    Logger(const Logger& src) = delete;
    Logger& operator=(const Logger& rhs) = delete;
    // Add log entry to the queue.
    void log(const std::string& entry);

    // Gracefully shut down background thread.
    virtual ~Logger();

    private:
    // The function running in the background thread.

    void processEntries();
    // Mutex and condition variable to protect access to the queue.
    std::mutex mMutex;
    std::condition_variable mCondVar;
    std::queue<std::string> mQueue;
    // The background thread.
    std::thread mThread;

    std::atomic<bool> mExit;
    // Other members omitted for brevity.
};

Logger::Logger()
{
    // Start background thread.
    mThread  = thread{ &Logger::processEntries, this};


}

void Logger::log(const std::string& entry)
{
    // Lock mutex and add entry to the queue.
    unique_lock<mutex> lock(mMutex);
    mQueue.push(entry);
    // Notify condition variable to wake up thread.
    mCondVar.Notify_all();

    // the lock should be released?
}

void Logger::processEntries() 
{
    // Open log file.
    ofstream ofs("log.txt");
    if (ofs.fail()){
        cerr << "Failed to open logfile." << endl;
        return;
    }

    // Start processing loop.
    unique_lock<mutex> lock(mMutex);

    while (true){
        // Wait for a notification.
        mCondVar.wait(lock)
        // Condition variable is notified, so something might be in the queue.
        lock.unlock();

// I am pretty sure the moment lock.unlock() is called the other threads will acquire the lock and the instruction will not jump directly to while(true) which kind of defeats the purpose of the application.
// Code continues...
        while (true){
            lock.lock();
            if (mQueue.empty()) {
                break;
            } else {
                ofs << mQueue.front() << endl;
                mQueue.pop();
            }
            lock.unllock();
        }
    }
}


void logSomeMessages(int id, Logger& logger)
{
    for (int =0; i < 10; ++i){
        stringstream ss;
        ss << "Log entry " << i << " from thread " << id;
        logger.log(ss.str());
    }
}

int main()
{
    Logger logger;
    vector<thread> threads;
    // Create a few threads all working with the same Logger instance.
    for (int i=0; i <10; ++i){
        threads.emplace_back(logSomeMessages, i, ref(logger))
    }

}

What is the difference between "const auto" and "auto const" in range based for loop in C++?

In particular these two examples.

  1. for (const auto &ind : vec)
  2. for (auto const &ind :vec)

Does assert() act as the identity function in release mode?

This library uses assert() as if it's the identity function in release mode (when NDEBUG is defined). The problem is that some important code is wrapped with assert(), and my tests fired when executed in release mode, because these important parts were not called. An example of this can be found here, where the random bytes generator will not generate anything and will cause an infinite loop.

Personal anecdote: I dislike assert() and I personally don't use it because of these ambiguity issues. I heard of many projects that had serious bugs because of it, most recently EOS, when their unit tests didn't detect some out of range arrays because NDEBUG was defined in release mode and it didn't fire. The documentation doesn't seem to be clear on this point. Does assert() act as the identity at all?

This library (libbtc) seems to be used widely, and I don't understand why the developer did this. Is this a horrible mistake and I should fork and remove all these asserts? Or is this some C thing that's not C++ compatible? Could someone please explain the correct course of action here?

I use clang 6.

Image Processing Alorithim

I currently working on a processing algorithm based on this Image Processing

I am no sure what this algorithm is based, its partial Gaussian Filter and 2D FFT.

Can friends here can help me understand this algorithm please? I want to port this into naive C++ code.

Thanks Kumar

How to detect type of uint8_t in parameter pack

#include <iostream>
#include <type_traits>

template<class Head>
void print_args(std::ostream& s, Head&& head) {
    s << std::forward<Head>(head);
}

template<class Head, class... Tail>
void print_args(std::ostream& s, Head&& head, Tail&&... tail) {
    if (std::is_same<Head, uint8_t>::value)
        s << static_cast<int>(head) << ",";       // cast uint8_t so that the value of 1 or 0 can be displayed correctly in console
    else
        s << std::forward<Head>(head) << ",";
    print_args(s, std::forward<Tail>(tail)...);
}

template<class... Args>
void print_args(Args&&... args) {
    print_args(std::cout, std::forward<Args>(args)...);
}

int main()
{
    uint8_t val = 1;
    print_args(std::string("hello"), val); // error: invalid static_cast from type 'std::basic_string<char>' to type 'int'
    print_args("hello", val); // error: invalid static_cast from type 'const char [6]' to type 'int'
}

Question> I need to cast uint_8 to int so the value can be displayed correctly in console. However, the above code has build issue for either std::string or const char*.

What is the fix for the function?

destructor is called twice for std::vector with optimization level 0

I am trying to understand the assembly code generated for the std::vector and its emplace_back (or) push_back function using compiler explorer.

using emplace_back

Note: Optimization level is 0 i.e., -O0 is used

One thing that I couldn't understand is that why are there two destructors being called instead of one (As you can see only one vector is being created. If I assume that a temporary object is being created internally, then atlease I have to see a call to std::vector constructor.

This is same with clang compiler as well.

Can someone please explain what is happening here?

Data read from the file, but a core dumped error occurs

#include <iostream>
#include <fstream>
#include <vector>


class C{
    private:
        int work_loc, floor_no;
    public:
        C(){}
        void printC(){
            std::cout << "work Location: " << work_loc << "  floor_no: " << floor_no;
        }
        C(int work_loc1, int floor_no1): work_loc(work_loc1), floor_no(floor_no1){}
};

class B{
    private:
        int empid_;
        std::string name_;
        C obj_c;
    public:
        B(int empid, std::string name, int work_loc, int floor_no): empid_(empid), name_(name){
            obj_c = C(work_loc, floor_no);
        }
        void printB(){
            std::cout << empid_ << " " << name_ << "\n ";
            obj_c.printC(); 

        }


};

class A{
private:
    std::vector<B> calls;
public:
    void addToCalls(B b){
        calls.push_back(b);
    }
    void printAll(){

        for(size_t i = 0; static_cast<int>(i) < 3; i++){
            std::cout << "i is " << i << "\n";
           calls[i].printB(); 
        }

    }
    int callSize(){
        return calls.size();
    }


};


int main(){
    A a, c;

    a.addToCalls(B(1,"a1", 1, 33));
    a.addToCalls(B(2,"b2", 3 ,44));
    a.addToCalls(B(3,"c2", 4, 55));
    a.addToCalls(B(4,"d3", 5, 22));
    a.addToCalls(B(5,"e4", 3, 88));
    a.printAll();
    std::cout << "end of a\n";  
    // FILE* f;
    // FILE* f1;
    // f = std::fopen("serial.txt", "w+");
    std::cout << "begin another a \n  ";
    std::fstream  f;
    std::fstream  f2;
    f.open("class_data.txt", std::ios::out|std::ios::binary);
    f.write((char*)&a, sizeof(a));

    // fwrite(a, sizeof(a), sizeof(a), f);
    // fwrite(&n, sizeof(int), 1, f);
    f.close();
    // rewind(f);
    // f.open("class_data.txt", std::ios::out | std::ios::binary);
    f2.open("class_data.txt", std::ios::in | std::ios::binary);
    f2.read((char*)&c, sizeof(c));
    std::cout << "the size of C is " << c.callSize() << "\n"; 
    c.printAll();
    // f.close();
    f2.close();


}

Here I get the data gets copied into the object c, but it gives out an error. After the values are printed, the code gives the core dumped error. The value of the object is copied from the file, which is also written at the same time. Is it because of the 2 file pointers opening the same file? Here's the backtrace

Aborted (core dumped)

======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fae6020e7e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fae6021737a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fae6021b53c]
./a.out[0x4028ea]
./a.out[0x40276a]
./a.out[0x402564]
./a.out[0x4021e3]
./a.out[0x401c80]
./a.out[0x401ad6]
./a.out[0x401635]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fae601b7830]
./a.out[0x4010c9]

Using 'override' for a function that has been declared using 'typedef'

C++ 11 introduce the 'override' specifier for a function and I find it useful as it makes it explicit that a virtual function is being overridden. However, I can't seem to get it work for a function that has been declared using a typedef.

I understand that 'override' is not a keyword, has it got something to do with that?

The following code illustrates my point:

#include <iostream>

typedef char ReturnsChar();

class Basic
{
    public:
    virtual char get_a();
    virtual ReturnsChar get_z;
};

char Basic::get_a() { return 'a'; }
char Basic::get_z() { return 'z'; }

class Capitalized : public Basic
{
    public:
    // Can override explicitly if I use the normal definition
    char get_a() override;

    // Compiles if I use the typedef but not 'override'
    ReturnsChar get_z;

    // Will not compile, but would like to do this
    //ReturnsChar get_z override; 

};

char Capitalized::get_a() { return 'A'; }
char Capitalized::get_z() { return 'Z'; }

int main()
{
    Basic foo;
    Capitalized bar;

    std::cout << foo.get_a() << std::endl; // a
    std::cout << foo.get_z() << std::endl; // z
    std::cout << bar.get_a() << std::endl; // A
    std::cout << bar.get_z() << std::endl; // Z
}

I'm using GNU's g++ 8.2.0 and the error it gives me is

error: expected ';' at end of member declaration
ReturnsChar get_z override;
            ^~~~~
                      ;
error: ‘override’ does not name a type; did you mean ‘ctermid’?
     ReturnsChar get_z override;
                       ^~~~~~~~
                       ctermid

using unique_ptr in constructor

I am working on a school project and I cannot figure out unique_ptr usage.

class ClassName
{
private: 
    unique_ptr <bool[]> uniquePtr;

    void func(unique_ptr<bool[]>& refPtr) const
        {
            refPtr[0] = true;
            refPtr[1] = false; 
        }
public:
    //other things that will use the array uniquePtr
};

ClassName::ClassName()
{
    bool* boolName = new bool [someSize()];
    uniquePtr = unique_ptr<bool[]>(boolName);
    func(uniquePtr);
}

I understand that this does not work because uniquePtr is destroyed as func() finishes. I cannot figure out how to modify uniquePtr such that it will be accessible to my other functions. I do not have tried creating a new unique_ptr to pass into func() and then use move(uniquePtr) but that won't even compile.

Thanks for the help!

VS2017 - Error overloading function with different template template parameters with same argument

Error overloading function with different template template parameters with same argument

In VS2017 I am getting an error

error C2535: 'bool mv::conjoined_graph::make_node_(T_allocator::owner_ptr &,T_allocator::owner_ptr::node> &)': member function already defined or declared

However, the two fucntion declarations have different arguments, 'owner_ptr &new_node' and 'owner_ptr &new_node`

bool make_node_(owner_ptr<detail::base_node_class<T_node, T_size>> &b_node, owner_ptr<typename first_graph::node> &new_node)

bool make_node_(owner_ptr<detail::base_node_class<T_node, T_size>> &b_node, owner_ptr<typename second_graph::node> &new_node)

This code compiles fine on GCC.

I found a similar error here:

Error overloading function with different template template parameters with same argument

Could anybody suggest a solution as I want to code to be the same for linux and windows and compile with both GCC and MSVC.

Using ICP in ROS Kinetic

I have written a program using class in ROS to perform ICP using a stored PCD file and the data being streamed from the LiDAR sensor.

I am getting the following error:

/usr/include/boost/smart_ptr/shared_ptr.hpp:641: typename boost::detail::sp_dereference::type boost::shared_ptr::operator*() const [with T = pcl::PointCloud; typename boost::detail::sp_dereference::type = pcl::PointCloud&]: Assertion `px != 0' failed. Aborted (core dumped)

Here's my code below

#include "ros/ros.h"
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <icp.h>
#include <pcl/PCLPointCloud2.h>
#include <pcl/conversions.h>
#include <pcl_ros/transforms.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>

using namespace ros;
using namespace std;
using namespace pcl;

class icp
{
private:
    NodeHandle n;
    Subscriber sub;
    Publisher pub = n.advertise<sensor_msgs::PointCloud2>("icp_topic",1);
    PointCloud<PointXYZ> stream_cloud;
    PointCloud<PointXYZ> pcd_cloud;
    PointCloud<PointXYZ> :: Ptr stream_cloudPTR;
    PointCloud<PointXYZ> :: Ptr pcd_cloudPTR;

public:

    icp()
    {

        PointCloud<PointXYZ> :: Ptr pcd_cloudPTR (new PointCloud<PointXYZ>);
        PointCloud<PointXYZ> :: Ptr stream_cloudPTR (new PointCloud<PointXYZ>);
        if(io::loadPCDFile<PointXYZ> ("~/PCD/2.pcd", *pcd_cloudPTR) == -1)
        {
            PCL_ERROR ("Couldn't read file\n");
            ROS_ERROR("Couldn't read file\n");
            return;
        }

        sub = n.subscribe("/apollo/sensor/velodyne64/compensator/PointCloud2", 1, &icp::read_stream, this);
    }
    void read_stream(const sensor_msgs::PointCloud2ConstPtr& msg)
    {
        //conversion from pcl_ros to pcl
        fromROSMsg(*msg, *stream_cloudPTR);

        // Perform ICP
        IterativeClosestPoint<PointXYZ, PointXYZ> icp;
        icp.setInputSource(stream_cloudPTR);
        icp.setInputTarget(pcd_cloudPTR);

        PointCloud<PointXYZ> Final;
        icp.align(Final);

        sensor_msgs::PointCloud2 output;
        toROSMsg( *stream_cloudPTR, output );

        pub.publish(output);
    }

};
int main(int argc, char **argv)
{
    init(argc, argv, "icp_module");
    icp icp_object;
    //multithreaded spinner-use 10 threads
    MultiThreadedSpinner spinner(10);
    spinner.spin();
    return 0;
}

Kindly help me in this regard and oblige. Thanks in advance.

Generic code to align non-constant-width text on QLabel

I want to align text as follow on a QLabel:

name         : value
more         : other value
longer name  : value

It is easily done as follow

QString str;
str += "name\t\t: value\n";
str += "more\t\t: other value\n"
str += "longer name\t: value"

The question is, if I do not know the string pairs beforehand, is there a way in Qt to determine how many \t-chars must each string get so that they align on the : (if tabs are the only option)?

I can't use QString::arg() since the text is displayed on a GUI using non-constant-width-text. The issue here is that if I count the number of chars and set the fieldWidth the : does not align since the width of each char is not the same (changing the font is not an option)

I have tried some logic to count and then 'guess' the number of tabs to insert, which works in general but there might be some corner cases where it might not work.

virtual base classes initiailization

I am working on a test and I have hard time to understand this one:

#include <iostream>

struct Car
{
 Car() : price(20000) {}
 Car(double b) : price(b*1.1) {}
 double price;
};
struct Toyota : public virtual Car 
{
 Toyota(double b) : Car(b) {}
};

struct Prius : public Toyota
{
 Prius(double b) : Toyota(b)  {}
};

int main(int argc, char** argv)
{
 Prius p(30000);

 std::cout << p.price << std::endl;

 return 0;
}

The returned value is 20 000, but actually I do not not understand the why:

All sub-objects representing virtual base classes are initialized by the constructor of the most derived class. If the constructor of the most derived class does not specify a mem-initializer for a virtual base class V, then V's default construtor is called to initialize the virtual base class subobject.

And I tried different way to create a constructor in the derived class but I got errors from the compiler.

Does anyone provide an explnantion and how to creatse such constructor? Thank you very much for your help

jeudi 30 août 2018

Is the stack variable deallocated when it goes out of scope?

sample1.cpp

#include <iostream>

int main()
{
    int* aPtr = nullptr;

    {
        int a = 3;
        aPtr = &a;
    }

    std::cout << *aPtr << std::endl;

    return 0;
}

Output

3

I am able to access a through aPtr.

  1. Does that mean a is not deallocated even after it goes out of scope.
  2. Does that mean a is deallocated only after the function in which it is defined unwinds.
  3. Or is this an undefined behavior that currently outputs some value?

sampe2.cpp

#include <iostream>

struct Box
{
    Box(int a_)
        :a(a_)
    {}

    int getValue() const { return a;}

    ~Box()
    {
        std::cout << "Destructor called" << std::endl;
    }
private:
    int a;
};


int main()
{
    Box* boxPtr = nullptr;

    {
        Box box = 23;
        boxPtr = &box;
    }

    std::cout << boxPtr->getValue() << std::endl;

    return 0;
}

Output

Destructor called
23

I am able to access box through boxPtr even after destructor of box is called.

Decltype Bug Gcc wont compile

source code https://github.com/kennywakeland/Decltype-Bug/blob/master/main.cpp

Test compile https://coliru.stacked-crooked.com/a/443f03625728f00e

This code is to test the setters and getters, using macros. I want to pass in the variable name. decltype is not returning the right type to the HTestSet. Any idea why it is not returning the correct value type ?

Compiler error g++ -std=c++11 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

main.cpp: In function 'int main()':
main.cpp:26:72: error: no matching function for call to 'HTestSet(TestClass&, void (BaseClass::*)(int), int&)'
     if(HTestSet(OBGEC_ON, &decltype(OBGEC_ON)::SET_CALL, test_vall_stor)){
                                                                        ^

main.cpp:18:1: note: in expansion of macro 'H_TEST_VALUE_GET_SET'
 H_TEST_VALUE_GET_SET(H_GET_VALUE(OBGEC_ON, VAL_NAME), \
 ^~~~~~~~~~~~~~~~~~~~

main.cpp:92:5: note: in expansion of macro 'H_TEST_VALUE'
     H_TEST_VALUE(woo, Green, 3);
     ^~~~~~~~~~~~

Templating an object in main

I'm working on a project that is a templated linklist. I got all my helper functions done and templated, but what I'm struggling with is giving my object a type in my main. I'll include all the necessary parts of my program within this post and I can edit it to where my whole project is here as well.

Header:


template <class T>
struct node{
  T data;
  struct node<T> *m_next;
};

template<class T>
class linkedList{

private:
  node<T> *m_head;
  node<T> *m_tail;

public:
  linkedList();
  void insert(T);
  void deleteNode();
  void display();
  void getHead();
  void getTail();
};

Declaration of variables from main


int main() {

   int value;
   int option = 1;
   linkedList<int> object;
   int count = 0;

Sample from main


case 1:
       cout << "Enter node to be pushed: ";
       cin >> value;
       object<int>.insert(value);
       object<int>.display();
       count++;

       break;


I'm getting the error "expected expression before int"

Any help would be appreciated!!

uninitialized_fill_n not forwarding arguments

I am implementing a container, that following the example of std::vector, has a private unitialize_construct.

template<class... Args>
auto uninitialized_construct(Args&&... args){
    typename array::element_ptr cur = this->data();
    for(size_type n = this->num_elements(); n > 0; --n, ++cur)
            alloc_traits::construct(allocator_, std::addressof(*cur), std::forward<Args>(args)...);
    }catch(...){destroy(cur); throw;}
}

I though that, for generic programming purposes, it would be better to use an algorithm instead of a raw loop. It turns out that the standard has std::unitialized_fill_n that does a placement new and effectively it is very similar.

https://en.cppreference.com/w/cpp/memory/uninitialized_fill_n

However, there is a big problem, std::uninitialized_fill_n doesn't have a variadic argument, and therefore I cannot forward args....

a) Why is it so? Is there another variant of uninitialized_fill_n that can forward it construction arguments?

b) If not, am I supposed to call unitialized_fill_n(data, size, value_type(std::forward<Args>(args)...))?

To reiterate, I was expecting to be able to say unitialized_fill_n(data, size, std::forward<Args>(args)...).

How to best expose a C++ class to Python?

Suppose, I have a C++ class:

class Scenario {
public:
    Scenario() {};
    void setOne(double _one) { one = _one; };
    ...

protected:
    double one;
    int    two;
    float  three;
}

which I'd like to expose to Python scripts so as to automatically gain the direct access to the fields, serialization, and other conveniences.

According to the tutorial, any class/structure so exposed must begin with PyObject_HEAD.

Should I inherit my PyScenario from Scenario:

struct PyScenario : public Scenario {
    PyObject_HEAD
}

or enclose one in the other:

struct PyScenario {
    PyObject_HEAD
    Scenario scenario;
}

I think, the former would be easier to manipulate, but I'm worried, it will not work (or will not be portable), because the "head" part may not end up at the beginning of the structure.

Or is there a completely different "pattern" to follow in such cases?

Is it possible to set a deterministic seed for boost::random::uniform_int_distribution<>?

I'm using boost::random::uniform_int_distribution<boost::multiprecision::uint256_t> to generate some unit tests. Notice that I'm using multiprecision, which is why I need to use boost and not the standard library. For my periodic tests, I need to generate deterministic results from a nondeterministic seed, but in such a way where I can reproduce the results later in case the tests fail.

So, I would generate a true random number and use as a seed, and inject that to uniform_int_distribution. The purpose is that if this fails, I'll be able to reproduce the problem with the same seed that made the tests fail.

Does this part of boost support generating seed-based random numbers in its interface? If not, is there any other way to do this?

PS: Please be aware that the primary requirement is to support multiprecision. I require numbers that range from 16 bits to 512 bits. This is for tests, so performance is not really a requirement. I'm OK with generating large random numbers in other ways and converting them to boost::multiprecision.

C++11 rvalue reference vs const reference

This may be obvious but I think it is something difficult to me. Given this:

void test(std::string&& a) {
    std::cout << "&&" << std::endl;
}

I have read the rvalue reference topic almost 3 times in 2 different books and I came to this conclusion.

 //main
 std::string x{"test"};
 test(std::move(x));

 //output: 
 //&&

This code calls test() with a rvalue reference as parameter so the output is what I expect. Here I am moving around the original value because I use move everywhere. Now look at this:

void test(const std::string& a) {
    std::cout << "&&" << std::endl;
}

If I called the same code I get the same output

//main
std::string x{"test"};
test(std::move(x));

//output: 
//&&

and here I'm tilted.


I know that

int&& s = 5;
const int& s = 5;

is valid because in both cases I provide something that has not an lvalue, it has no addresses. Are && and const& equivalent? If no, are there differences?

Tell me if I am wrong:

  • test(std::string&& a): a is rvalue reference but actually it has an lvalue!

    test(std::string&& a) { something(a) //--> not moved because it has lvalue something(std::move(a)) //now it is moved! }

  • test(const std::string& a): a is const lvalue reference and like before I have lvalue and rvalue. And plus more, in this case if I called

    std::move(a)

where a is a const& the move works!

I am confused. Doesn't move work only for && types?

Advantage of using auto in function return value using C++11

What is the advantage of using auto in function return type definition in C++11? ( foo2() vs foo1() )

int foo1(){
    // ...
    return 1;    
}

auto foo2() ->int {
    // ...
    return 1;    
}

int main()
{
    foo1();
    foo2();
    return 0;
}

How to get pointer to string's data in a vector of strings?

I have a vector of strings as my primary data container. However, in order to interoperate with a C library, I need to be able to view these strings as character data pointers (i.e. const char*). This sounds simple enough, so I wrote a helper class like this:

class strvecAccessor {
  const std::vector<std::string>& names;

public:
  strvecAccessor(const std::vector<std::string>& a) : names(a) {}
  size_t size() const { 
    return names.size(); 
  }
  const char* item(size_t i) {
    auto name = names[i];
    return name.data();
  }
};

This accessor class is short-lived. It serves as a wrapper around an existing vector of strings, which is guaranteed to not be modified or go out-of-scope during the lifespan of this class. An example of how this class can be used is the following:

void test(strvecAccessor& arr) {
  for (size_t i = 0; i < arr.size(); ++i) {
    printf("%s\n", arr.item(i));
  }
}

But there is a bug in this code, which manifests itself only when I compile it in --coverage -O0 mode, and only on Unix machine (I compile with CLang 6.0.0 in C++11 compatibility mode). The bug is that the printed strings contain garbage.

I believe what happens is that the name variable in item() method is not a reference, but a copy of the i-th element of the array. It goes out-of-scope at the end of the item() function, at which point the pointer that was returned becomes dangling. Most of the time it is not noticeable since the pointer is used immediately, but in coverage mode it gets filled up with other data right after the call.

The problem disappears if I replace auto name = names[i]; with const std::string& name = names[i];. But I don't really understand why, and whether this actually solves the problem or just buries it deeper. So my question is: why the copy is being made in the original code; and how to protect myself against these kinds of errors in the future?

Vector of struct in c++, Not reading proper value

I have a loop which reads value and inserts them into a std::vector of structs.

Here's my code:

vector<PTNvalues> PTNdata;
PTNvalues pt;

struct PTNvalues
{
    string LowRangesValue_[15];
    //string LLowRangesValue_[15];
    string HighRangesValue_[15];
    string Service[15];
    int version;
    char key;
    string Desc;
    int Ranges;
    bool AllowAlphas;
};

for (size_t i = 0; i < 35; i++)
{
    //PTNdata.push_back(PTNvalues());
    if (i < 10)
    {
        FD = '0' + i;
        //FD = to_string(i);
    }
    else
    {
        FD = char(55 + i);
    }
    pt.key = FD;
    tempstr = MessageApp::App.Ini.ReadString(to_string(FD), "AllowAlphas", "N");
    ToUppercase(tempstr);
    if (tempstr == "T" || tempstr == "Y")
    {
        pt.AllowAlphas = true;
    }
    else
    {
        pt.AllowAlphas = false;
    }
    pt.Ranges = MessageApp::App.Ini.ReadInt(to_string(FD), "Ranges", 0);
    for (size_t t = 1; t <= pt.Ranges; t++)
    {


        pt.LowRangesValue_[t] = MessageApp::App.Ini.ReadString(to_string(FD), "LowRanges__" + to_string(t), "");
        pt.HighRangesValue_[t] = MessageApp::App.Ini.ReadString(to_string(FD), "HighRanges_" + to_string(t), "");
        pt.Service[t] = MessageApp::App.Ini.ReadString(to_string(FD), "Service____" + to_string(t), "");
        pt.Desc = MessageApp::App.Ini.ReadString(to_string(FD), "Desc_______" + to_string(t), "");

    }
    PTNdata.push_back(pt);

}

But when I read value from that vector I am not getting proper value.

Here's how I read values:

size_t ParseScanData2::keyToIdx(char k)
{
    if (k >= '0' and k <= '9') return k - '0';
    if (k >= 'A' and k <= 'Z') return k - 'A' + 10;
    throw runtime_error("invalid key");
}

string AA = PTNdata[keyToIdx('H')].LowRangesValue_[10];
string BB = PTNdata[keyToIdx('H')].HighRangesValue_[10];

Above my file has only 3 values for Low and High for 'H'. But I am getting different values for string AA and BB above which should be empty. Am I missing something?

C++: Almost Always Auto and for loops with counter

Herb Sutter states Almost Always Auto and I have the following code:

use count_t = int;
count_t get_count() { ... };

const auto count = get_count();
for (decltype(count) i = 0; i < count; i++) {
    // Do the stuff
}

Essentially, using decltype() allows me to write a for loop that may use any integer type (hoping that get_count() would never return floating point) without any modifications in a client code of get_count() function and avoid compilation warnings like "signed-unsigned" mismatch.

My question is: is this form acceptable at all in an assumption that count_t may be redefined in future?

what is the difference between &, *, && in c++ 11

I noted that in C++, there are several way to pass a variable to a function, here is a list:

struct A
{ 
   int a;
   void test()
   {
      std::cout<<"this is a test:"<<a<<std::endl
   }
}

void f0(A p)
{ 
    p.a=0;
    p.test();
}
void f1(A *p)
{
    p->a=1;
    p->test();
}

void f2(A &p)
{
    p->a=2;
    p->test();
}
void f3(A &&p)
{
    p->a=3;
    p->test();
}

what is the difference? I know about f0, f1 and f2 and present them here for completes.

What is the signification of f3 and how I can use it?

How to specify an templatized alias' generic type in a container

I have a class Task:

template <typename T>
class Task {

    Task(const std::function<T()>& func) 
        : m_func(func)
    {
        // some stuff here
    }

    std::shared_ptr<T> getValue() {
        return m_value;
    }

    void execute() {
        m_value = std::make_shared<T>(m_func());
    }


    std::shared_ptr<T> m_value;  
    std::function<T()> m_func;  
}

Now, I want to alias this Task class to a shared_ptr so I do the following...

template <typename T> using TaskPtr = std::shared_ptr<Task<T> >;

I have another class that will store a container of of TaskPtr, I would like for the consumer of the api to specify T when calling addTask as follows.

Class X {
    // some boiler plate code
    template <typename T> 
    addTask(TaskPtr<T> task) {
         m_queue.push(task);
    }

    void loop() {
        // do some stuff
        auto item = m_queue.front();
        item->execute();
        m_queue.pop();
        // continue looping
    }

 std::queue<TaskPtr<T> > m_queue; 
}

I was wondering what the best way to do this would be. This code gives me the error that T is undefined. Duh! I need to add template <tyepname T> above my m_queue definition, that makes sense. When I do that, I get that I am putting the keyword typedef in an incorrect location. When I remove the template declaration and the T to just have std::queue<Taskptr> m_queue;, it tells me I am missing a template argument. Which makes sense, except I don't understand where it should go.

I have searched for an answer and couldn't find anything. What is the correct syntactical implementation for what I am trying do?

create signals in a custom QSlider class

I'm new in Qt and I'm trying to create a custom QSlider class (it inherits from QSlider). This works perfectly but when I try to create new signals and slots, it doesn'ts work. Actually, I think it's the Q_OBJECT macro which doesn't work... Indeed, I get this message from the compiler :

erreur : 1 duplicate symbol for architecture x86_64 erreur : linker command failed with exit code 1 (use -v to see invocation)

If I remove Q_OBJECT it doesn't work either as the compilers tells me :

erreur : Error: Class declaration lacks Q_OBJECT macro.

Finally, if I make my class inherit from QWidget, all is working even the Q_OBJECT macro...

Here is my .h code :

#include <QWidget>
#include <QSlider>

class mySlider : public QSlider
{
    Q_OBJECT
public:
    explicit mySlider();

signals:
    void test();

public slots:
    void nTest();
};

Here is my .cpp code (there isn't much things, I'm only trying to make this simple code work for now) :

#include "myslider.h"

mySlider::mySlider()
{

}

void mySlider::test(){

}

void mySlider::nTest() {

}

Custom compare function for std::multimap when keys are equal

I would like to code a custom comparator for a std::multimap. What I would like to do is to compare the keys, in case they are equal, then compare the values. I'm trying to do it by overloading the operator() in a struct and passing the function object as a third parameter in the std::multimap constructor.

struct CustomComp {
    bool operator()(int key_lhs, int key_rhs){
        if (key_lhs < key_rhs) return true;
        if (key_lhs == key_rhs) //Check values;
        else return false;
    }
};

multimap<int, int, CustomComp> myMap;

How can I access the values, not only the keys, if both are int?

Unable to access file from C++ library through C# UWP

I have an application for which GUI is written in C# UWP and accessing the file logic is written in C++ DLL. The DLL should open a file to read data from it. I am trying to access the file from its location. When I call inFile.open("D:\\File\\readFile.txt", ios::in) the value returned is NULL.

To check if there is any problem with the file path, I have created a console application to access the file using the same way and it worked. What could be the problem?

fstream inFile;
inFile.open(filePath, ios::in);
if (!inFile.is_open()) 
{
    /* Display unable to read file*/
    return;
}

/* Perform operation on file */
inFile.close();

C++ regex library

I have this sample code

// regex_search example
#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("eritueriotu3498 \"pi656\" sdfs3646df");
  std::smatch m;
  std::string reg("\\(?<=pi\\)\\(\\d+\\)\\(?=\"\\)");
  std::regex e (reg);   

  std::cout << "Target sequence: " << s << std::endl;

  std::cout << "The following matches and submatches were found:" << std::endl;

  while (std::regex_search (s,m,e)) {
     for (auto x:m) std::cout << x << " ";
     std::cout << std::endl;
     s = m.suffix().str();
  }

  return 0;
}

I need to get number between pi and " -> (piMYNUMBER") In online regex service my regex works fine (?<=pi)(\d+)(?=") but c++ regex don't match anything.

Who knows what is wrong with my expression? Best regards

C++ Templates access a function with different types

So What I'm trying to do is something like this.

I have a template struct like this one:

template <typename T>
struct TemplateTest
{
    void test(T a)
    {
        switch (typeid(boost::any_cast<T>(a)))
        {
        case typeid(int):
            {
                std::cout << "INT";
                break;
            }
        case typeid(float):
            {
                std::cout << "FLOAT";
                break;
            }
        case typeid(double):
            {
                std::cout << "DOUBLE";
                break;
            }
        default:
            {
                std::cout << "OTHER";
                break;
            };
        }
    }
};

And I want to make a vector with different types of that struct and after just use a for-loop to iterate over all my elements and call this function form all of them.

What I would like to have will be something like this:

typedef boost::variant<TemplateTest<float>(), TemplateTest<double>(), TemplateTest<int>() > variant;
typedef std::vector<variant> TestVar;
TestVar d;
d.push_back(new TemplateTest<float>());
d.push_back(new TemplateTest<double>());
d.push_back(new TemplateTest<int>());
for (auto value : d)
{
    value.test(5);
}

Is out there any way to do this without using a specific cast of my type before my function call?

Can not return pointer array in the struct

I am new to C++. below is my code. I saw a correct array in "setValue", but in "main", I can not get the right array value on strC. where did I miss?

template <int N>
struct strA{
int *p;
};

template <int N>
strA<N> setValue(int n)
{
strA<N> strB;
int m[N];
// pointer initialization
strB.p=m;
for (int i=0; i<N;i++)
{
    strB.p[i]=i+n;
}
return strB;
}

int main(){
const int N=3;
strA<N> strC;
strC=setValue<N> (5);
for (int i=0; i<N;i++)
{
    cout<< strC.p[i]<<endl;
}
return 0;
}

Calling a function of an object instance using embedded Python

I want to be able to run Python scripts in my app to allow automating stuff and modifying existing objects/calling methods of existing objects.

In my application there is a BasicWindow class and MainWindow class that derives from the former. For now at application start I initialize one instance of MainWindow. This object has many functions, among them there is one that loads files (LoadFile()), and I will use it as example here.

Lets say that I want to call that particular function (but not limited to that function, it is just an example of the functionality that I want to achieve from Python) of that particular object instance.

This method is not a static one. For this I am using Boost.Python and I am creating a module this way:

BOOST_PYTHON_MODULE(MyModule)
{

    MainWindow::PythonExpose(); //not really sure how to operate here
    //more stuff
}

The idea is that I could call from Python something like:

MainWindow.LoadFile()

or even better, just:

LoadFile()

One solution could be to create static, application scoped functions and then just expose those functions. In C++ I could find the particular instance of MainWindow: (both methods are static)

void AppHelper::LoadFile()
{
    GetMainWindow()->LoadFile();
}


void AppHelper::PythonExposeGlobal()
{
    using namespace boost::python;
    def("LoadFile", &AppHelper::LoadFile);
}

Is it possible to achieve this? The general question would be: is it possible to call methods of existing objects (in C++) from Python? If so, how to do it? If not, what can I do to mimic this behavior?

For example, I could easily enable scripting capabilities in my C# application and sharing instances of existing objects. (But of course C# has reflection).

mercredi 29 août 2018

Perfect forwarding of C++ overloaded and templated functors and its arguments

Suppose we have a function that looks like:

template <typename F, typename... A>
inline void execute(F&& functor, A&& ... args) {
    std::forward<decltype(functor)>(functor)(std::forward<decltype(args)>(args)...);
}

This works for simple non-templated functions. However, I am trying to perfect-forward a templated function(a quite contrived one):

namespace detail {

template <typename CodecImpl>
class codec
{
public:
    //
    // Encoding

    // Convenient version, returns an std::string.
    static std::string encode(const uint8_t* binary, size_t binary_size);
    static std::string encode(const char* binary, size_t binary_size);
    ...
};

class base64_rfc4648
{
public:
    template <typename Codec> using codec_impl = stream_codec<Codec, base64_rfc4648>;

    static CPPCODEC_ALWAYS_INLINE constexpr size_t alphabet_size() {
        static_assert(sizeof(base64_rfc4648_alphabet) == 64, "base64 alphabet must have 64 values");
        return sizeof(base64_rfc4648_alphabet);
    }
    static CPPCODEC_ALWAYS_INLINE constexpr char symbol(alphabet_index_t idx)
    {
        return base64_rfc4648_alphabet[idx];
    }
    ...
};

} // namespace detail

using base64_rfc4648 = detail::codec<detail::base64<detail::base64_rfc4648>>;

Trying to forward the above:

std::string buf("hello world");
execute(base64_rfc4648::encode, buf.c_str(), buf.size());

Does not work. Template deduction fails:

note: couldn't deduce template parameter 'F'

and it also notes:

No matching function for call to 'execute(<unresolved overloaded function type>, const char*, std::__cxx11::basic_string<char>::size_type)'

How can I fix this?

NOTE: I kept the information short above for readability, but if more info is needed I can add.

Return r-val reference reason

I see a class defined like the following:

class Foo {
 public:
  template <typename T, typename... Args>
  Foo&& addElement(Args&&... args) {       <--- why do we return Foo&&
    elements_.emplace_back(
      std::make_unique<T>(std::forward<Args>(args)...));
    return std::move(*this);
  }

 private:
  std::vector<std::unique_ptr<Bar>> elements_;
};

I can't think of any good reasons for the returning type of function addElement(). Does it make sense to return r-val reference or it's not a good idea? If so, what's the potential reason for doing that?

Tensorflow v1.10.1 NewSession() error: Not found: No session factory registered for the given session options

  • Tensorflow version: 1.10.1
  • Language: C++
  • Compiled using: cmake

We have created a frozen_graph.pb and are using tensorflow C++ api to import. The error we run into every time we execute our code is the following: NewSession() error: Not found: No session factory registered for the given session options: {target: "" config: gpu_options { per_process_gpu_memory_fraction: 1 allow_growth: true }} Registered factories are {}.

In the following snippet:

// Declaring a tensorflow session
Session* session;
void* error = NULL;

// Declaring Session options
SessionOptions options;

//options.config.set_allow_soft_placement(true);
options.config.mutable_gpu_options()->set_allow_growth(true);

// To control fraction of GPU used
options.config.mutable_gpu_options()->set_per_process_gpu_memory_fraction(perProcessGpuMemoryFraction);

// Starting a new session and checking to see the session has been created without errors
Status status = NewSession(options, &session);
if (!status.ok()) {
    std::cout << "NewSession() error: " << status.ToString() << "\n";
    return error;
}

we have tried adding -Wl,-whole-archive libtensorflow_cc.so -Wl,--no-whole-archive, still getting the same error. Also tried -Wl,--allow-multiple-definition libtensorflow_cc.so -Wl,--no-whole-archive, still getting the same error.

Please suggest a solution.

Why isn't `std::unique_lock::owns_lock` called `owns_mutex`? [on hold]

Mutexes and scoped locks should not be confused, but somehow std::unique_lock::owns_lock "tests whether the lock owns its associated mutex" (quoting cppreference.com).

A lock on a mutex owning a lock doesn't make sense. Why hasn't the standard called this owns_mutex or is_locked?

Can assigning a name to a lambda impact performance?

What is the difference in terms of performance, if any, between using a lambda directly and defining a named lambda and then passing it as an argument?

For example this:

std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });

versus this:

auto a_greater_than_b = [](int a, int b) { return a > b; };
std::sort(v.begin(), v.end(), a_greater_than_b);

Qt cannot show property in designer

This is my class with the relevant code:

class TestClass: public QWidget {

    Q_OBJECT
    Q_PROPERTY(QColor color MEMBER m_color NOTIFY colorChanged)

public:
    public:
    explicit TestClass(QWidget *parent = nullptr): TestClass{parent} {};

private:
    QColor m_color;

signals:
    void colorChanged();
};

I am creating a plugin and I am able to get the dll file and load it with the designer. The problem is the following:

enter image description here

Where is the property? I'd expect here to have a TestClass header with the color property but it is not here. What am I missing?


I have Qt 5.11.1, the latest version of Qt Designer and I am using MinGW 5.3. I have created the entire project with File > New > Other projects > Custom Widget so it has the proper settings. The dll can be seen and loaded by the designer and it works well.

Duplicate variadic template parameter

Context:

I am a Jr. Software Engineer, hopefully I am not reinventing the wheel, please let me know. I'd like to create a template function which wraps and calls another function element wise. For example:

// returns a*x + y
__device__ float saxpy(float a, float x, float y) {
  return a*x + y;
}


int main() {
  int A[4] = { 1,2,3,4 };
  int X[4] = { 1,2,3,4 };
  int Y[4] = { 1,1,1,1 };

  // A*X   = 1,4,9,16
  // A*X+Y = 2,5,10,17
  float *C = cudaReduce(saxpy, A, X, Y);

  for (int i = 0; i < 4; i++)
    printf("%d, ", C[i]); // should print "2, 5, 10, 17, "

  std::cin.ignore();
  return 0;
}

Importantly, I want to create this wrapper so that cuda calls are nicely wrapped when I perform element-wise operations. Though very incomplete, here is my pseudo-code attempt at the function wrapper.

I'd like to provide a minimal example; however, I have very little idea how to go about certain aspects of C++, so please forgive the large amounts of commented pseudocode:

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <iostream>

// returns a*x + y
__device__ float saxpy(float a, float x, float y) {
  return a*x + y;
}

// finds return type of function pointer
template<typename R, typename... A>
R ret(R(*)(A...));
template<typename C, typename R, typename... A>
R ret(R(C::*)(A...));

template<typename F, size_t N, typename... Args>
auto cudaReduce(F &f, Args(&...argsarray)[N]) {
  cudaSetDevice(0);

  // ret is function f's return type
  typedef decltype(ret(f)) ret;
  ret d_out[N], h_out[N];
  // cudaMalloc((void**)&d_out, sizeof(d_out));
  sendToCuda(argsarray...); // allocates and copies all contents of argsarray to cuda

  // reduceKernel<<<1, N>>>(f, d_out, dev_argsarray...);

  // cudaDeviceSynchronize();
  // cudaMemcpy(h_out, d_out, sizeof(h_out), cudaMemcpyDeviceToHost);
  // cudaFree(d_out);

  // for d_args in d_argsarray
  //   cudaFree(d_args);

  return h_out;
}

template<typename F, size_t N, typename Out, typename... Args>
__global__ void cudaReduceKernel(F &f, Out(&out)[N], Args(&...argsarray)[N]) {
  int tid = threadIdx.x;
  int i = tid + blockIdx.x * blockDim.x;

  // Below is invalid syntax; however, the 'pseudo-code' is what I'd like to achieve.
  // out[i] = f(argsarray[i]...);
}

// cuda malloc and memcpy
template<typename Arg, size_t N>
void sendToCuda(Arg(&args)[N]) {
  size_t buffer = sizeof(args);
  //cudaMalloc((void**)&dev_arg[ ??? ], buffer);
  //cudaMemcpy((void**)&dev_arg[ ??? ], args, buffer, cudaMemcpyHostToDevice);
}
template<typename Arg, size_t N, typename... Args>
void sendToCuda(Arg(&args)[N], Args(&...argsarray)[N]) {
  sendToCuda(args);
  sendToCuda(argsarray...);
}

int main() {
  int A[4] = { 1,2,3,4 };
  int X[4] = { 1,2,3,4 };
  int Y[4] = { 1,1,1,1 };

  // A*X   = 1,4,9,16
  // A*X+Y = 2,5,10,17
  float *C = cudaReduce(saxpy, A, X, Y);

  for (int i = 0; i < 4; i++)
    printf("%d, ", C[i]); // should print "2, 5, 10, 17, ", currently prints undefined behaviour

  std::cin.ignore();
  return 0;
}

I realize not everyone has time to completely review the code, so I will boil down the key problems into several points:

1. Is it possible to duplicate variadic template inputs, if so how? EX (not real code):

template<typename... Args>
void foo(Args... args) {
  Args2... args;
}

This is needed so that I can duplicate my input parameters to input parameters for my cuda malloc() and memcpy().

2. How would I go about the ith tuple of a variadic array parameter, like zipping in python. EX (not real code):

template<typename... Args, size_t N>
void bar(Args(&...argsarray)[N]) {
  // (python) ithvariadic = zip(*argsarray)[i]
  auto ithvariadic = argsarray[i]...;
}

unique_ptr reference to deleted function when implementing interface

I have the following code, which is being built using the MSVC2013 toolchain, C++11 (Old stuff a function of work constraints):

template<class T>
class AbstractWrappedQueue {
public:
    virtual bool empty() = 0;
    virtual size_t size() = 0;
    virtual void push(T& value) = 0;
    virtual void push(T&& value) = 0;
    virtual T pop() = 0;
}

template<class T>
class WrappedQueue // : AbstractWrappedQueue<T>  -- UNCOMMENT FOR COMPILE FAILURE
{
private:
    std::queue<T> q;
public:
    WrappedQueue() {}
    ~WrappedQueue() {}
    bool empty() { return q.empty(); }
    size_t size() { return q.size(); }
    void push(T& p) { q.push(p); }
    void push(T&& p) { q.push(std::move(p)); }
    T pop() {
        T r = std::move(q.front());
        q.pop();
        return r;
    }
}

//Google Test excerpt
TEST(WrappedQueueTest, PtrDoesntDie) {
    WrappedQueue<unique_ptr<int>> ptr;
    //...rest of test is irrelevant.
}

As long as WrappedQueue stands alone, the class, and it's functionality, plays with unique_ptrs without a problem. However, should it implement the AbstractWrappedQueue interface (i.e., uncomment the : AbstractWrappedQueue<T> part of the class definition, then I get the following error:

error C2280: 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function.

I would not expect the application of my interface to cause a situation where an attempt to copy a unique_ptr might occur. Why is this occurring? What can be done to prevent it (aside from simply not using the interface)?

How to handle -nan output in c++

Let's say I have a function that calculates Euclidean distance between a pair of points. point and point_pair are two structs defined as:

struct point {
    int x, y;
}

and

struct point_pair {
    point a, b;
}

The following functions calculates the distance taking a pair of points as an input:

double calc_distance(point_pair pair)
{
  return (sqrt((pair.a.x - pair.b.x) * (pair.a.x - pair.b.x) + (pair.a.y - pair.b.y) * (pair.a.y - pair.b.y)));
}

The function works fine for small point pair values; but for a point pair such as:

651760491 595516649
716636914 955747792

The output is -nan

I'm not sure how to workaround this, is there something else I should be using in place of double?

Here is the entire code: https://pastebin.com/5XEr9bTD

How to pass a parameter to std::bind from a function

I am working on c++ 11.

I want to write a function funA in a class, which binds another function funB within the same class. And funB function is a parameter in the function funA. What could be the syntax of the funcA ? I tried using std::function func, but i am not able to compile. Please explain.

Thanks.

Using windows fiber in a simple way but unexplainable bugs occur

I played around with windows fibers implementing my own task scheduler when some odd crashes and undefined behaviors occurred. For the sake of simplicity I started a new project and wrote a simple program who performs the following operations:

  1. The main thread creates a bunch of fibers, then launch two threads
  2. The main thread waits until you kill the program
  3. Each worker thread converts himself into a fiber
  4. Each worker thread tries to find a free fiber, then switchs to this new free fiber
  5. Once a thread had switch to a new fiber, it pushes its previous fiber into the free fibers container
  6. Each worker thread goes to the step 4

If you are not familiar with fiber concept this talk is a good start.

The Data

Each thread has its own ThreadData data structure to store its previous, current fiber instances, and its thread index. I tried several way to retrieve the ThreadData data structure during execution:

  • I used thread local storage to store ThreadData pointer
  • I used a container which associate a thread_id with a ThreadData structure

The Problem

When a fiber is entered for the first time (look at the FiberFunc function), the thread using this fiber must pushes its previous fiber into the free fibers container. But it happens that sometimes the previous fiber is null, which is impossible. It is impossible because before switching to a new fiber the thread sets its previous fiber value with its current fiber value (and it sets its current fiber value with the new fiber value).

So if a thread enters in a brand new fiber with its previous fiber set as null, it would mean it comes from nowhere (which doesn't make any sense).

The only reasons a ThreadData has its previous fiber value set as null when it enters to a brand new fiber is that another thread sets it to null or that compiler reordered instructions under the hood.

I checked the assembly and it seems that the compiler is not responsible.

There are several bugs I can't explain:

  1. If I use the first GetThreadData() function to retrieve the ThreadData structure, I can retrieve an instance whose index is different from the thread local index (those indices have been set when threads started). This will make the program assert ( assert(threadData->index == localThreadIndex)).

  2. If I use any other function to retrieve the ThreadData structure I will assert in the FiberFunc function because the previous fiber value is null (assert(threadData->previousFiber)).

Do you have any idea why this code doesn't work ? I spent countless hours trying to figure out what is wrong but I don't see my mistakes.

The Code

I compiled and ran the code with Visual studio 2015 using VC++ compiler, in Release x64. You may try to run it several times before the assert fires.

#include "Windows.h"
#include <vector>
#include <thread>
#include <mutex>
#include <cassert>
#include <iostream>
#include <atomic>

struct Fiber
{
    void* handle;
};

struct ThreadData
{
    Fiber*  previousFiber{ nullptr };
    Fiber*  currentFiber{ nullptr };
    Fiber   fiber{ };
    unsigned int index{};
};

//Threads
std::vector<std::thread*> threads{};
std::vector<std::pair<std::thread::id, unsigned int>> threadsinfo{};

//threads data container
ThreadData  threadsData[8];

//Fibers
std::mutex  fibersLock{};
std::vector<Fiber> fibers{};
std::vector<Fiber*> freeFibers{};

thread_local unsigned int localThreadIndex{};
thread_local Fiber* debug_localTheadLastFiber{};
thread_local ThreadData* localThreadData{};

//This is the first way to retrieve the current thread's ThreadData structure using thread_id
//ThreadData* GetThreadData()
//{
//  std::thread::id threadId( std::this_thread::get_id());
//  for (auto const& pair : threadsinfo)
//  {
//      if (pair.first == threadId)
//      {
//          return &threadsData[pair.second];
//      }
//  }
//
//  //It is not possible to assert
//  assert(false);
//  return nullptr;
//}

//This is the second way to retrieve the current thread's ThreadData structure using thread local storage
//ThreadData* GetThreadData()
//{
//  return &threadsData[localThreadIndex];
//}


//This is the third way to retrieve the current thread's ThreadData structure using thread local storage
ThreadData* GetThreadData()
{
    return localThreadData;
}


//Try to pop a free fiber from the container, thread safe due to mutex usage
bool  TryPopFreeFiber(Fiber*& fiber)
{
    std::lock_guard<std::mutex> guard(fibersLock);
    if (freeFibers.empty()) { return false; }
    fiber = freeFibers.back();
    assert(fiber);
    assert(fiber->handle);
    freeFibers.pop_back();
    return true;
}


//Try to push a free fiber to the container, thread safe due to mutex usage
bool PushFreeFiber(Fiber* fiber)
{
    std::lock_guard<std::mutex> guard(fibersLock);
    freeFibers.push_back(fiber);
    return true;
}


//the __declspec(noinline) is used to inspect code in release mode, comment it if you want
__declspec(noinline) void  SwitchToFiber(Fiber* newFiber)
{
    //You want to switch to another fiber
    //You first have to save your current fiber instance to release it once you will be in the new fiber
    {
        ThreadData* threadData{ GetThreadData() };
        assert(threadData->index == localThreadIndex);
        assert(threadData->currentFiber);
        threadData->previousFiber = threadData->currentFiber;
        threadData->currentFiber = newFiber;
        debug_localTheadLastFiber = threadData->previousFiber;
        assert(threadData->previousFiber);
        assert(newFiber);
        assert(newFiber->handle);
    }

    //You switch to the new fiber
    //this call will either make you enter in the FiberFunc function if the fiber has never been used
    //Or you will continue to execute this function if the new fiber has been already used (not that you will have a different stack so you can't use the old threadData value)
    ::SwitchToFiber(newFiber->handle);

    {
        //You must get the current ThreadData* again, because you come from another fiber (the previous statement is a switch), this fiber could have been used by any other thread
        ThreadData* threadData{ GetThreadData() };

        //THIS ASSERT WILL FIRES IF YOU USE THE FIRST GetThreadData METHOD, WHICH IS IMPOSSIBLE....
        assert(threadData->index == localThreadIndex);

        assert(threadData);
        assert(threadData->previousFiber);

        //We release the previous fiber
        PushFreeFiber(threadData->previousFiber);
        debug_localTheadLastFiber = nullptr;
        threadData->previousFiber = nullptr;
    }

}


void ExecuteThreadBody()
{
    Fiber*  newFiber{};

    if (TryPopFreeFiber(newFiber))
    {
        SwitchToFiber(newFiber);
    }
}


void ThreadFunc(unsigned int index)
{
    threadsinfo[index] = std::make_pair(std::this_thread::get_id(), index);

    //setting up the current thread data
    ThreadData* threadData{ &threadsData[index] };
    threadData->index = index;
    threadData->fiber = Fiber{ ConvertThreadToFiber(nullptr) };
    threadData->currentFiber = &threadData->fiber;

    localThreadData = threadData;
    localThreadIndex = index;

    while (true)
    {
        ExecuteThreadBody();
    }
}


//The entry point of all fibers
void __stdcall FiberFunc(void* data)
{
    //You enter to the fiber for the first time

    ThreadData* threadData{ GetThreadData() };

    //Making sure that the thread data structure is the good one
    assert(threadData->index == localThreadIndex);

    //Here you will assert
    assert(threadData->previousFiber);

    PushFreeFiber(threadData->previousFiber);
    threadData->previousFiber = nullptr;

    while (true)
    {
        ExecuteThreadBody();
    }
}


__declspec(noinline) void main()
{
    constexpr unsigned int threadCount{ 2 };
    constexpr unsigned int fiberCount{ 20 };

    threadsinfo.resize(threadCount);

    fibers.resize(fiberCount);
    for (auto index = 0; index < fiberCount; ++index)
    {
        fibers[index] = { CreateFiber(0, FiberFunc, nullptr) };
    }

    freeFibers.resize(fiberCount);
    for (auto index = 0; index < fiberCount; ++index)
    {
        freeFibers[index] = std::addressof(fibers[index]);
    }

    threads.resize(threadCount);

    for (auto index = 0; index < threadCount; ++index)
    {
        threads[index] = new std::thread{ ThreadFunc, index };
    }

    while (true);

    //I know, it is not clean, it will leak
}

C++ SFINAE enable_if_t in member function, how to disambiguate?

Suppose we have some SFINAE member function:

class foo{
    template <class S, class = std::enable_if_t<std::is_integral<S>, S>
    void bar(S&& s);
    template <class S, class = std::enable_if_t<!std::is_integral<S>, S>
    void bar(S&& s);
}

If we declared it as above, then how can we define them? Both of their function signatures would look like:

template <class S, class>
inline void foo::bar(S&& s){ ... do something ... }

I have seen examples where one returns an std::enable_if_t<...> like:

template <class S, class>
decltype(auto) bar(S&& s) -> std::enable_if_t<!std::is_integral<S>, S>(...){
    ... do something ...
}

To disambiguate based off of the return type. But I don't want to return anything.

C++11 Range-based for loop for std::list

If I understand the range-based for loop correctly, which expands

for ( range_declaration : range_expression ) loop_statement

into

{
    auto && __range = range_expression ;
    for (auto __begin = begin_expr, __end = end_expr;
            __begin != __end; ++__begin) {
        range_declaration = *__begin;
        loop_statement
    }
}

thus incrementing the pointer, and if I understand that std::lists are internally implemented as doubly linked lists, isn't it correct to assume that something like this would not print 0 1 2 3, since the memory addresses are not sequential (implied by the ++__begin)?

std::list<int> myList = {0, 1};
std::list<int> otherList = {10, 11};
myList.push_back(2);
myList.push_back(3);

for(auto& i: myList)
    std::cout << i << " ";

And yet it does print correctly. So then, is std::list::iterator overriding the behavior of the operators used in the range-for-loop expansion?

This is of particular importance to me if I choose to implement my own range-for iterable data structures.

boost::asio hangs _endthreadx

int main(){
  boost::asio::io_context io_context;
  Server server(io_context, SOCKET_ADDRESS, SOCKET_PORT);

  std::thread thread_server([&]() {
    server.start();
    io_context.run();
  });

  std::thread thread_client([&]() {
    Client &client = Client::create(SOCKET_ADDRESS, SOCKET_PORT);
    client.start();
    done = true; // <-----atomic
  });

  std::thread thread_stop([&]() {
    while (done == false) {
      std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    server.stop();
  });

  thread_server.join();
  thread_client.join();
  thread_stop.join();
}

I am experimenting with boost::asio and encountered problem which I am unable to solve. When I run program(simpler example above) on Linux(compiled with gcc) everything is fine. Same when I run it on Release in VS2017CE. However when I run it on Debug(VS2017CE as well) it crash with and exception:

cannot dereference string iterator because string iterator was invalidated

It crash on _endthreadx either when exiting thread_stop or thread_server(most likely second one). Here are my questions then:

  1. What are the differences between Release and Debug basic configurations which might affect code execution and point me where should I look.(I am aware of some but couldn't find anything connected with this particular problem.)

  2. What mistakes were made by me which affects code execution.

I've made some classes so I will provide more code if neccessary, but code basically works so I am starting with just a piece of it.

SFINAE failing to work with intermediary type traits

Consider the following test code:

// Preprocessor
#include <iostream>
#include <type_traits>

// Structure with no type alias
template <class T>
struct invalid {
};

// Structure with a type alias
template <class T>
struct valid {
    using type = T;
};

// Traits getting the type of the first type
template <class T, class... Args>
struct traits {
    using type = typename T::type;
};

// One argument function
template <class T, class = typename traits<T>::type>
void function(T) {
    std::cout << "function(T)" << std::endl;
}

// Two arguments function
template <class T, class U, class = traits<T, U>::type>
void function(T, U) {
    std::cout << "function(T, U)" << std::endl;
}

// When function can be called on all arguments
template <
    class... Args,
    class = decltype(function(std::declval<Args>()...))
>
void sfinae(Args&&... args) {
    function(std::forward<Args>(args)...);
    std::cout << "sfinae(Args&&...)" << std::endl;
}

// When function can be called on all arguments except the first one
template <
    class T,
    class... Args,
    class = decltype(function(std::declval<Args>()...))
>
void sfinae(const invalid<T>&, Args&&... args) {
    function(std::forward<Args>(args)...);
    std::cout << "sfinae(const invalid<T>&, Args&&...)" << std::endl;
}

// Main function
int main(int argc, char* argv[]) {
    valid<int> v;
    invalid<int> i;
    sfinae(v);
    sfinae(i, v);
    return 0;
}

The code involves:

  • a structure invalid that has no ::type
  • a structure valid that has a ::type
  • a structure traits that defines ::type as T::type
  • an overloaded function which should work only if the type of the first argument is such that traits<T>::type is defined
  • an overloaded sfinae function that should be able to call function even if the first argument is invalid

However, the SFINAE mechanism does not seem to work in this instance, and I am not sure to understand why. The error is the following:

sfinae_problem_make.cpp:19:30: error: no type named 'type' in 'invalid<int>'
    using type = typename T::type;
                 ~~~~~~~~~~~~^~~~
sfinae_problem_make.cpp:29:46: note: in instantiation of template class 'traits<invalid<int>, valid<int> >' requested here
template <class T, class U, class = typename traits<T, U>::type>
                                             ^
sfinae_problem_make.cpp:30:6: note: in instantiation of default argument for 'function<invalid<int>, valid<int> >' required here
void function(T, U) {
     ^~~~~~~~~~~~~~~~
sfinae_problem_make.cpp:37:22: note: while substituting deduced template arguments into function template 'function' [with T = invalid<int>, U = valid<int>, $2 = (no value)]
    class = decltype(function(std::declval<Args>()...))
                     ^
sfinae_problem_make.cpp:39:6: note: in instantiation of default argument for 'sfinae<invalid<int> &, valid<int> &>' required here
void sfinae(Args&&... args) {
     ^~~~~~~~~~~~~~~~~~~~~~~~
sfinae_problem_make.cpp:60:5: note: while substituting deduced template arguments into function template 'sfinae' [with Args = <invalid<int> &, valid<int> &>, $1 = (no value)]
    sfinae(i, v);

The very surprising thing is that if traits is removed from the problem:

// Preprocessor
#include <iostream>
#include <type_traits>

// Structure with no type alias
template <class T>
struct invalid {
};

// Structure with a type alias
template <class T>
struct valid {
    using type = T;
};

// Traits getting the type of the first type
template <class T, class... Args>
struct traits {
    using type = typename T::type;
};

// One argument function
template <class T, class = typename T::type>
void function(T) {
    std::cout << "function(T)" << std::endl;
}

// Two arguments function
template <class T, class U, class = typename T::type>
void function(T, U) {
    std::cout << "function(T, U)" << std::endl;
}

// When function can be called on all arguments
template <
    class... Args,
    class = decltype(function(std::declval<Args>()...))
>
void sfinae(Args&&... args) {
    function(std::forward<Args>(args)...);
    std::cout << "sfinae(Args&&...)" << std::endl;
}

// When function can be called on all arguments except the first one
template <
    class T,
    class... Args,
    class = decltype(function(std::declval<Args>()...))
>
void sfinae(const invalid<T>&, Args&&... args) {
    function(std::forward<Args>(args)...);
    std::cout << "sfinae(const invalid<T>&, Args&&...)" << std::endl;
}

// Main function
int main(int argc, char* argv[]) {
    valid<int> v;
    invalid<int> i;
    sfinae(v);
    sfinae(i, v);
    return 0;
}

then it works as expected and outputs:

function(T)
sfinae(Args&&...)
function(T)
sfinae(const invalid<T>&, Args&&...)

Question: Why the first version does not work, and is there a way to make it work with the intermediary type traits?

How to Implement a converter to proper duration type in below case

I have written a small TimeUnit code that aims to implement duration types using easy to understand Enums and it works fine in implementing delay function. I want to write a converter which returns the required duration given The quantity and TimeUnit type. Can someone shed how I can implement this? I tried methods of template specialization but it is not working.

I need function say toDuration(const long&, const TimeUnit&) and returns appropriate type of duration which is say suitable for passing to condition_variable wait_for or any sleep_for delay function.

Ex:- toDuration(10, TimeUnit::MilliSeconds) should return std::chrono::milliseconds(10) and so on [ scope only for below types of Enums is fine ].

class TimeUnit_impl
{
    public:
        typedef std::chrono::duration<long, std::ratio<1l, 1000l> > MILLISECONDS;
        typedef std::chrono::duration<long, std::ratio<1l, 1000000l> > MICROSECONDS;
        typedef std::chrono::duration<long, std::ratio<1l, 1l> > SECONDS;
        typedef std::chrono::duration<long, std::ratio<1l, 1000000000l> > NANOSECONDS;
        typedef std::chrono::duration<long, std::ratio<60> > MINUTES;
        typedef std::chrono::duration<long, std::ratio<3600> > HOURS;
};

enum class TimeUnit { MilliSeconds , MicroSeconds , Seconds, NanoSeconds, Minutes, Hours };

void customSleep(const long& quantity, const TimeUnit& unit)
{
    switch(unit)
    {
        case TimeUnit::MilliSeconds : std::this_thread::sleep_for(TimeUnit_impl::MILLISECONDS(quantity));
                                      break;
        case TimeUnit::MicroSeconds : std::this_thread::sleep_for(TimeUnit_impl::MICROSECONDS(quantity));
                                      break;
        case TimeUnit::Seconds :      std::this_thread::sleep_for(TimeUnit_impl::SECONDS(quantity));
                                      break;
        case TimeUnit::NanoSeconds :  std::this_thread::sleep_for(TimeUnit_impl::NANOSECONDS(quantity));
                                      break;
        case TimeUnit::Minutes :      std::this_thread::sleep_for(TimeUnit_impl::MINUTES(quantity));
                                      break;
        case TimeUnit::Hours :        std::this_thread::sleep_for(TimeUnit_impl::HOURS(quantity));
                                      break;
        default:            std::cout << "error" << std::endl;
                            break;
    }
}

How to tell if `constexpr` is evaluated at compile time (without manual inspection)

Is there a standard way to find out what the compiler does to constexpr functions?

(Side note: For debug, every constexpr function is deferred to runtime by default. Why is this sensible? Is there a way to influence this?)

For release it depends on the context. Obviously, for small test settings you can easily inspect the generated machine code, but this cannot be the way to go for a real project.

My current 'workaround' (VC++) is to break somewhere, go to my constexpr function and (try to) inspect the disassembly. If none is there, I conclude that it was all done at compile time. But it is not 100% reliable this way. (Optimization, etc.) Only the other way around is certain: If I do find disassembly (and can even break there), I know that it was NOT done at compile time.

SFINAE: "enable_if cannot be used to disable this declaration"

Why can I not use enable_if in the following context?

I'd like to detect whether my templated object has the member function notify_exit

template <typename Queue>
class MyQueue
{
   public:
    auto notify_exit() -> typename std::enable_if<
            has_member_function_notify_exit<Queue, void>::value,
            void
        >::type;

    Queue queue_a;
};

Initialised with:

MyQueue<std::queue<int>> queue_a;

I keep getting (clang 6):

example.cpp:33:17: error: failed requirement 'has_member_function_notify_exit<queue<int, deque<int, allocator<int> > >, void>::value';
      'enable_if' cannot be used to disable this declaration
            has_member_function_notify_exit<Queue, void>::value,

or (g++ 5.4):

In instantiation of 'class MyQueue<std::queue<int> >':
33:35:   required from here
22:14: error: no type named 'type' in 'struct std::enable_if<false, void>'

I've tried a bunch of different things, but can't figure out why I can't use enable_if to disable this function. Isn't this exactly what enable_if is for?

I've put a full example here (and cpp.sh link that often fails)

I've found similar Q/As on SO, but generally those were more complicated and attempting something different.

Is double braced scalar initialization allowed by C++ standard?

I have following code:

int x = ;

Is this syntax valid according to C++ standard (I'm interested in C++11 and later)?

When using the latest compilers there is no problem, however in some older ones (e.g. gcc 4.8.5) it gives following error:

error: braces around scalar initializer for type 'int'

Is it safe to pass std::function

Given the following working code (main.cpp):

#include <functional>
#include <iostream>

struct worker
{
   std::function<bool(std::string)> m_callback;
   void do_work(std::function<bool(std::string)> callback) // <--- this line
   {
      m_callback = std::bind(callback, std::placeholders::_1);
      callback("hello world!\n");
   }
};


// pretty boring class - a cut down of my actual class
struct helper
{
   worker the_worker;
   bool work_callback(std::string str)
   {
      std::cout << str << std::endl;
      return false;
   }
};

int main()
{
   helper the_helper;
   the_helper.the_worker.do_work( [&](std::string data){ return the_helper.work_callback(data); });
}

Compiled with: -std=c++11 -O2 -Wall -Wextra -pedantic-errors -O2 main.cpp

I have comment the line in question (<-- this line - around line 7), where I think it would be more efficient to use: void do_work(std::function<bool(std::string)>&& callback) i.e. using the && move semantic.

I have never really used this, mostly because I still don't quite understand it.

My understanding is this:

void do_work(std::function<bool(std::string)> callback) - will take a copy of the lambda that I pass in (which is an rvalue I think).

void do_work(std::function<bool(std::string)> callback) - will move the lambda that I pass in because it is an rvalue.

My crude idea of an rvalue is any temporary variable.

Questions:

  1. What I am not 100% clear about is, is what I wrote correct? and therefore is it safe to use &&. Both seem to work.

  2. Does this && method also work if instead of passing a lambda like this:

the_helper.the_worker.do_work( [&](std::string data){ return the_helper.work_callback(data); });

we pass in std::bind(...):

the_worker.do_work(std::bind(&helper::work_callback, the_helper, std::placeholders::_1));

rvalue references, std::reference_wrappers and std::function

I was reading up on r-value references and move semantics. Experimenting this with std::function and std::reference_wrapper unfortunately confused me a bit more.

#include <iostream>
#include <string>
#include <string_view>
#include <functional>

class Greeting {
  std::string g;
  std::function <void(std::string_view)> f;
public:
  Greeting(std::string&& _g, std::function<void(std::string_view)>&& _f)
    : g(std::move(_g)), f(std::move(_f)){};
  void greet() {
    f(g);
  }
};

struct prefix_g {
  std::string g;
public:
  prefix_g(const std::string&& _g) : g(std::move(_g)) {}
  void operator() (std::string_view s) {
    std::cout <<g <<" "<< s << std::endl;
  }
};

int main() {
  prefix_g eng("Hello");

  Greeting g("World",eng);
  Greeting g2("World2",std::ref(eng)); // reference wrapper, special
                                       // forwarding for op ()
  std::string s3("world3"), s4("world3");

  // Greeting g3(std::ref(s3), std::ref(eng)); won't compile; &s3 -> &&s3
  // Greeting g3(s3, eng); won't compile lval to rval
  // Greeting g4(std::move(s4), std::move(eng)); // compiles, output Hello World2 -> World2 as g is moved?

  g.greet(); g2.greet();
  Greeting g4(std::move(s4), std::move(eng));
  g4.greet();

  Greeting g5("world5", std::move(eng)); // UB? move guarantees fn object is
                                         // still valid, ofc, g now gets default
                                         // init to empty
  g5.greet();
  return 0;
}

  1. How is it that r-value references to a std::function actually accepts l-values for eg. in case Greeting g("World",eng), a similar l-value wouldn't be acceptable for any other argument (other than templating the constructor and making a universal reference maybe?) ?
  2. What actually happens when a std::ref is passed to std::function, ref mentions that merely arguments are forwarded. However if I move the function object itself as the commented out g4 is shown I see the output of g2 which uses std::ref to actually see the move in effect, just printing world2

Need help trying to pass a member function of another class into a std::function parameter

I have a class with a function that takes a std::function and stores it. This part seems to compile ok (but please point out any issue if there are any)

class worker
{
   std::function<bool(std::string)> m_callback;
   void do_work(std::function<bool(std::string)> callback)
   {
      m_callback = std::bind(callback, std::placeholders::_1);
      callback("hello world\n");
   }
};

Now I have my main and another "helper" class where I want to call this above function and pass in a function from the helper class to it:

// pretty boring class - a cut down of my actual class
class helper
{
   worker the_worker;
   bool work_callback(std::string str)
   {
      std::cout << str << std::endl;
   }
}

int main
{
   helper the_helper;
   the_worker.do_work(std::bind(&helper::work_callback, the_helper, std::placeholders::_1));  // <---- SEGFAULT
}

Note: hand copied code, so there might be a type-o in here... please forgive!

I get a segfault, but I am not sure why :( I have used this before, in fact I copied this example from another place I used it. The only real difference that that the member function was part of the class I called it from (i.e. this instead of the_helper).

So this is why I am also asking if there is anything else I am doing wrong in general? Like should I be passing the std::function as:

void do_work(std::function<bool(std::string)>&& callback)

or

void do_work(std::function<bool(std::string)>& callback)

How to define Boolean class using boost, the possible value should be TRUE or FALSE?

I am trying to implement the API for Boolean, I need to implement KMboolean 
class, possible value should be true or false. Is there any other way to 
implement Boolean(API) functionality using defined class. please help me to 
resolve my issue.  
here is my snippet

typedef KMBoolean;
typedef class
{
bool true,false;
};

i am new to API implementation, i am not sure my way is right or wrong, Anyone please help me to implement in general way to define Boolean functionality.

Any disadvantages for std::atomic_flag not providing load or store operations? (Spin-lock example)

Comparing a std::atomic_flag to an std::atomic_bool, it seems to me that a std::atomic_flag just has a simpler interface. It provides only testing+setting and clearing the flag while an std::atomic_bool also provides overloads to several operators.

One question of mine is about terminology: What is meant by "load or store operations"? Does it mean that it is not possible to arbitrarily read and modify a std::atomic_flag's value?

Furthermore, I am wondering, could a std::atomic_bool be faster when being used for a spin-lock? It seems to me that an std::atomic_flag always must read AND write during a spin-lock:

while (my_atomic_flag.test_and_set()); // spin-lock

while an std::atomic_bool would only have to perform a read operation (assuming that the atomic bool is implemented lock-free):

while (my_atomic_bool); // spin-lock

Is an std::atomic_flag strictly more efficient than an std::atomic_bool or could it also be the other way round? What should be used for a spin-lock?

mardi 28 août 2018

Staic qobject won't destruct if having a active QTcpServer child

Here is the demo to reproduce, having a singleton Base class contains a QTcpServer child:

#include <QTcpServer>
#include <QApplication>
#include <QDebug>

class Base : public QObject
{
    Q_OBJECT
public:
    Base(Base const&)             = delete;
    Base operator=(Base const&)   = delete;
    static Base& instance() { static Base instance; return instance; }

    static void start() {
        qDebug("start");
        instance().init();
    }

private:
    void init() {
        qDebug("createSub");
        sub = new QTcpServer(this);
        sub->listen(); // ● Here is the problem
    }

    Base() = default;
    ~Base() {
        qDebug("destruct base");
    }

    QTcpServer* sub;
};

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    Base::start();

    return app.exec();
}

#include "main.moc"

The problem is if QTcpServer start listen, the destructor of Base won't be invoked. can comment listen to see the difference. Calling listen function makes "destruct base" will not be outputted when the program is closed.

Why does this happen?