lundi 31 août 2015

Operator overloading -> in CPP

We can't change the arity of the operator. -> is binary operator, but to overload it we need to use it as unary postfix. what is the reason? Why CPP compiler allows to change the arity?

How to move a unique_ptr?

I have this code:

unique_ptr<int[]> p1, fitness_data (new int[NewPerson->num_entries]);

...add data to fitness_data...

p1 = std::move(fitness_data); //Attempt 1 or...
p1(std::move(fitness_data)); //Attempt 2. Either attempt is commented. 

Both stop the program with exit code 139. My IDE, CLion gives the error

'unique_ptr::operator=(const unique_ptr &)' is deleted

I'm assuming that the error is referring to an attempt made to copy the pointer, But I need to move it.

I would appreciate any help. I would hate to have to move back to manually freeing memory again. Unfortunately, the version of OpenMP we are allowed to use does not get along with vectors.

Thanks, Daniel

Deleted vs empty copy constructor

Examples of empty and deleted copy constructors:

class A
{
public:
    // empty copy constructor
    A(const A &) {}
}

class B
{
public:
    // deleted copy constructor
    A(const A&) = delete;
}

Are they doing the same in practice (disables copying for object)? Why delete is better than {}?

Exclude external project sub directory

I'm creating a project using Cmake and I'm using ExternalProject to include a dependency. That dependency has its own CMakeLists.txt and inside of that CMakeLists.txt it includes two more directories using add_subdirectory and those directories are examples and I want to remove them.

For example:

ExternalProject_Add(
  foobar
  URL url_goes_here
  PREFIX ${CMAKE_CURRENT_BINARY_DIR}/vendor/foobar
  INSTALL_COMMAND ""
)

Inside of the CMakeLists.txt of foobar it has add_subdirectory(example1) and add_subdirectory(example1).

I want to remove those two examples from being built.

I can't seem to instantiate class specializations with enable_if

I'm trying to make a class that has 3 possible versions of a template method implementation, depending on the template type being of one of three 'type sets'. Also, I'm trying to keep instances of these objects in a map.

So my initial attempt was:

class DescriptorType {
public:
    int id;
    DescriptorType() : id(-1) {}
    virtual ~DescriptorType() {}
};

template <typename T>
class Descriptor : public DescriptorType {
public:
    T value;

    void update(TYPE_CONSTRAINT((TYPE(int) || TYPE(float)))) {
        // specific implementation for these types
    }

    void update(TYPE_CONSTRAINT((TYPE(vec2) || TYPE(vec3) || TYPE(vec4)))) {
        // specific implementation for these types
    }

    void update(TYPE_CONSTRAINT((TYPE(mat2) || TYPE(mat3) || TYPE(mat4)))) {
        // specific implementation for these types
    }
};

(I have an include file with the following -- for the macros):

template <bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;

#define TYPE_CONSTRAINT(x) enable_if_t<x, T>
#define TYPE(x) std::is_same<x, T>::value

But it doesn't seem to work. It compiles but the minute I try to instantiate a Descriptor<T> for any T, be it the generic T or a concrete type like 'int' I get linker errors for all possible types (16 in my case).

My guess is I'm using enable_if wrong. But I'm not sure how.

Are auto in temple parameter list in lambdas part of the standard?

Today, I stumbled across the following code snippet:

#include <utility>

int main()
{

  auto a = [](std::pair<auto, auto> value)
  {

  };

  a(std::pair<int, bool>{ 3, true });
}

http://cpp.sh/5p34

I have only one question: is this code supported by the standard?

It compiles in GCC (with -std=c++14), but not clang or Visual Studio 2015 (VC++14).

This seems like it should be part of the standard because if lambdas should have the same template support as regular functions, then this should be supported.

This seems to convert to all template types, not just std::pair.

Converting input from std::cin to runnable code C++

I'm working on a project and I need a way of receiving input from the console/user and use that to run a certain part in the code without the need of elaborate switch/if:else statements. Let me give you an example.

#include <iostream>
#include <string>

using namespace std;

void foo();
void foo2();

int main(){
    string s;
    cin >> s;

    /*Take the input from cin and turn it into a function call, or some other
    form of runnable code, like so*/

    //Lets say the user inputs "run foo"
    foo();
    //Or if they input "run foo2"
    foo2();

    return 0;
}

void foo(){
    cout << "Foo works, yay :D";
}

void foo2(){
    cout << "Foo2 works, yay :D";
}

You might think I could do this with a switch or multiple if:else statements but this little code is just a small representation of what I need to do. The project requires this to be used on a large scale and I'd like it if I didn't need to use those, to save lines.

So is there any way I can do this in C++? Where the console user tells the program what to run and it runs said function?

Thanks!!

converting C# static class with constructor to standard C++11 [duplicate]

This question already has an answer here:

Based on Bearvine's answer here Static constructor in c++

I've taken the following C# code:

namespace Services
{
    internal static class Strings
    {
        private static Dictionary<uint, string> stringIDs = new Dictionary<uint, string>(0x2);

        static Strings()
        {
            stringIDs.Add(0x1, "String1");
            stringIDs.Add(0x2, "String2");
        }
    }
}

And in C++

#include <unordered_map>
#include <string>

namespace Service
{
  class Strings
  {
  private:
    static std::unordered_map<unsigned int,std::wstring> stringIDs;

  public:
    static void init (void);
  };

  void Strings::init() 
  {
    stringIDs.insert({0x1, L"String1"});
    stringIDs.insert({0x2, L"String2"});
  }
}

However this throws error when compiled:

$ g++ -std=c++11 test1.cpp /tmp/ccE3dKa6.o: In function Service::Strings::init()': test1.cpp:(.text+0x30): undefined reference toService::Strings::stringIDs' test1.cpp:(.text+0x6c): undefined reference to `Service::Strings::stringIDs' collect2: error: ld returned 1 exit status

Some my question is

1) how to I get this reference defined 2) is there a better way to replicate this design pattern in C++

Why is the C++11 move operator (=) behavior different

I have tested the move Semantic in C++11. I wrote a class with a move constructor.

class DefaultConstructor
{
public:
    DefaultConstructor(std::vector<int> test) :
        m_vec(std::forward<std::vector<int>>(test))
    {

    };

    DefaultConstructor(DefaultConstructor &&def) :
        m_vec(std::forward<std::vector<int>>(def.m_vec))
    {
    }

    DefaultConstructor& operator=(DefaultConstructor&& def) {
        m_vec = std::move(def.m_vec);
        return *this;
    }

    DefaultConstructor& operator=(const DefaultConstructor&) = delete;
    DefaultConstructor(DefaultConstructor &) = delete;

    std::vector<int> m_vec;
};

I wrote a main function that use the move semantic. I understand what happend in the move semantic and it is great tool. But there is some behavior which is for me not explainable. When I call in the main function DefaultConstructor testConstructor2 = std::move(testConstructor); for me the DefaultConstructor& operator=(DefaultConstructor&& def) should called. But the Visual Studio 2015 calls the move constructor.

int main()
{
    std::vector<int> test = { 1, 2, 3, 4, 5 };
    DefaultConstructor testConstructor(std::move(test));

    DefaultConstructor testConstructor2 = std::move(testConstructor);
    DefaultConstructor &testConstructor3 = DefaultConstructor({ 6, 7, 8, 9 });
    DefaultConstructor testConstructor4 = std::move(testConstructor3);
    swapMove(testConstructor, testConstructor2);
}

Okay I thought maybe the = Move Operator is not necessary anymore. But I tried a SwapMove function. This function calls the = move Operator.

template<typename T>
void swapMove(T &a, T &b)
{
    T tmp(std::move(a));
    a = std::move(b);
    b = std::move(tmp);
}

Can someone explain what exactly is the difference betwenn the two calls? Shouldn't be the calls a = std::move(b); and DefaultConstructor testConstructor2 = std::move(testConstructor); have the same behavior?

Should I extend std::less for a comparison functor?

I want to create a shared_ptr content-comparison functor to stand in for std::less in associative containers and std algorithms. I've seen sevearl examples of custom comparators that use the following (or similar) model:

template <typename T>
struct SharedPtrContentsLess {
  bool operator()(const boost::shared_ptr<T>& lhs, 
      const boost::shared_ptr<T> rhs) const {
    return std::less<T>(*lhs, *rhs);
    //or: return (*lhs) < (*rhs);
  }
  //defining these here instead of using std::binary_functor (C++11 deprecated)
  typedef boost::shared_ptr<T> first_argument_type;
  typedef boost::shared_ptr<T> second_argument_type;
  typedef bool return_type;
};

But why wouldn't I want to instead extend std::less? Like so:

template <typename T>
struct SharedPtrContentsLess : public std::less< boost:shared_ptr<T> > {
  bool operator()(const boost::shared_ptr<T>& lhs, 
      const boost::shared_ptr<T> rhs) const {
    return std::less<T>(*lhs, *rhs);
  }
};

Does this buy me anything at all?

I would think this gets me the typedefs for free, as though I was extending the deprecated std::binary_function. In C++03, I actually would be extending it through std::less. However, this would also be portable from C++03 to C++11/14 and even C++17 when std::binary_function will be removed, as it just follows the changes in std::less.

I've read a bunch of answers on StackOverflow regarding std::less use, custom comparison functors, and even some of the Standard specs and proposals. I see specializations of std::less and guidance not to extend STL containers, but I can't seem to find any examples of extending std::less or guidance against it. Am I missing an obvious reason not to do this?

Is overloading the addition operator with an rvalue reference as its left hand operand considered as a good practice?

Assuming stris a class for storing string values, it would overload the addition operator in order to support string concatenation. Like this:

str operator+(const str &a,const str &b);

But the problem is if we have something like this:

str s=str("Hel") + str("lo ") + str("Wor") + str("ld!");

Then it would create 3 temporary objects (as we get a new object in every addition) which aren't really needed in this context. A simple solution to this problem may be overloading a new addition operator which accepts a rvalue-reference as its left operand and returns this operand also as a rvalue-reference after concatenating it with the right operand. Something like this:

str &&operator+(str &&a,const str &b){
   a+=b;
   return std::move(a);
}

By having overloaded this operator, then the mentioned statement would just create a single temporary object and following additions will just be concatenated to that temporary object.

My question is, is this method a correct solution for this problem?

Syntax error with typename and scope operator

Can someone tell me how to fix the syntax problem below?

#include <iostream>

template <int N>
struct Thing { 
    static const int num = N;
};

template <int N>
struct Get {
    using type = Thing<N>;
};

template <int... Is>
void foo() {
//  int a[] = {(std::cout << Thing<Is>::num << '\n', 0)...};  // This compiles.
    int a[] = {(std::cout << typename Get<Is>::type::num << '\n', 0)...};  // This does not.
}

int main() {
    foo<0,1,2>();
}

GCC 5.1.0 says [Error] expected '(' before '<<' token. Any quick way to fix this (without writing a new function and have it called within foo)?

Overriding << operator in C++11, pure virtual in base class and different implementations in each derived class

I have a given base class that has some implementations, and has two derived classes. I want to override the cout operator << to have a custom way to print the data I want from these classes, and each of the derived classes does so slightly differently.

class Base
{
public:
    // Various functions, as expected
    virtual friend std::ostream& operator<<(std::ostream& stream, const Base& base) = 0;
    // More functions, members, all those things
}

These are the implementations in the derived classes:

class DerivedOne
{
public:
    std::ostream& operator<<(std::ostream& stream, const Base& base)
    {
    stream << base._someData << "\t" << "first desired print statement: "  << base._otherData;
    }

class DerivedTwo
{
public:
    std::ostream& operator<<(std::ostream& stream, const Base& base)
    {
    stream << base._someData << "\t" << "second desired print statement: "  << base._otherData;
    }

Note that the actual class members I'm calling belong to the Base class, and don't vary between the two implementations. The only thing that changes is the string between the data members.

This is the compilation error I get on Visual Studio. It seems one of the problems is that the << operator specifically appears with the keyword "friend," which makes it more complicated than other operators.

One of the ways I thought to solve this problem is to simple save each string as part of base._otherData (which is also a string), but that seems inelegant to me, and I was hoping that there was a more direct way to override this operator and have varying implementations in my derived classes.

[I would just like to add as a side note that I'm relatively new to this site, and while I tried to format and phrase the question properly, I'm sure there are some mistakes, and I appreciate any constructive feedback and editing of style.]

Convert arguments of variadic function

This is probably a newbie question but I thought it might be interesting. Let's say I have this function:

template <typename First, typename... T>
int ComputeSomething(const First& f, const T&... t);

I would like to write a second function that calls the one above in the general case, but converts the arguments when First and T are of type float, i.e., it calls a Convert function on each argument:

long Convert(float f);

template <typename First, typename... T>
int MyFun(const First& f, const T&... t) {
  return ComputeSomething(f, t...);
}

// This is what I would like:
int MyFun(const float& f, const float& t...) {
  return ComputeSomething(Convert(f), Convert(t)...);
}

How can I achieve that?

QStyledItemDelegate createEditor() has wrong location for some items

I use a specialised QStyledItemDelegate to create a QLineEdit as editor in my QTreeView:

QWidget* MyStyledItemDelegate::createEditor(QWidget* parent, QStyleOptionViewItem const& option, QModelIndex const& index) const
{
  QLineEdit* lineEdit = new QLineEdit(parent);
  QStyleOptionViewItemV4 opt = option;
  initStyleOption(&opt, index);
  lineEdit->setFixedSize(opt.rect.width(), opt.rect.height());
  return lineEdit;
}

This creates a correct editor that has the correct size and location for most items. However, if the item has a checkbox (created with Qt::CheckStateRole), the line edit is slightly of in y-coordinate (around 2px) and of in x-coordinate (around the size of the checkbox). This covers other parts of the Treeview and does not look great.

Is there a way to circumvent this issue?

how to change the text of qlineedit when Qlistview index is changed in another qdialog?

Hi i want get the text string of QListView in my main window when i click a button in Qdialog. my implementation is :

in Qdialog

void hist::getValue(){
QModelIndexList templatelist =
    ui->listView->selectionModel()->selectedIndexes();
QStringList stringlist;
foreach (const QModelIndex &index, templatelist) {
  stringlist.append(index.data(Qt::DisplayRole).toString());
 }
 qDebug()<<stringlist;
// return stringlist;   // what i need to here to return stringlist ?
}

void hist::on_downloadselected_clicked() {

connect(ui->downloadselected, SIGNAL(clicked()), SLOT(accept()));

 // TODO selected download
  }

in mainwindow

void mainwindow::on_pushButton_2_clicked()
{
hist history;
history.exec();
if( history.exec() == QDialog::Accepted ){
   QString damn = history.getValue();  // am getting error here 
   ui->url->setText(damn);
   qDebug()<<"pressed";
}
}

Boost add_console_log yields invalid operands to binary expression error

I have the following simple setup:

#include <boost/log/sources/record_ostream.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/expressions/keyword.hpp>


namespace mynamespace
{
    namespace keywords = boost::log::keywords;
    namespace expr = boost::log::expressions;

    enum SeverityLevel
    {
        Trace,
        Debug,
        Info,
        Warning,
        Error,
        Critical
    };


    class LoggingConfig
    {
    public:
        void init()
        {
            // Add default console logging sink
            auto format = expr::stream << expr::message;
            boost::log::add_console_log(std::cout, keywords::format=format);
        };
    };
}

Compiling gives this:

/Users/iulian/ClionProjects/project/util/logging.hpp:33:40: error: invalid operands to binary expression ('const stream_type' (aka 'const actor<base_type>') and 'const message_type' (aka 'const attribute_keyword<tag::message>'))
            auto format = expr::stream << expr::message;
                          ~~~~~~~~~~~~ ^  ~~~~~~~~~~~~~

I have seen numerous example of configuring the format etc in a similar manner to what I am trying above. Why doesn't this compile?

Generate a std::tuple from standard container

Is there a portable way to generate a std::tuple (really a std::array) from the contents of a container? Such a tuple would allow std::apply to extract function arguments from a container.

My first attempt, using tail recursion, fails with compiler error: "recursive template instantiation exceeds maximum...".

I could not quite get my second attempt (std::for_each with a mutable lambda holding tuple) to compile with desired results.

I assume that something along the lines of how boost::mpl handles variadic metafunctions (ie magic using boost::preprocessor) could be made to work -- but that's so c++03. I'm hoping there's a better solution.

The function signature would look something like:

std::list<int> args_as_list = {1, 2, 3, 4};
auto tpl = args_as_tuple(args_as_list);

where type of tpl is std::array<int const, 4>.

Thanks for suggestions!

why lock_guard can get an already locked mutex by unique_lock? - still questions

I am studying this example. I have found this question and thought that I will get an answer, but I still have a question.

I post the the code here for convenience:

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
    // Wait until main() sends data
    std::cout << "------------------------\n";
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{return ready;});

    // after the wait, we own the lock.
    std::cout << "Worker thread is processing data\n";
    data += " after processing";

    // Send data back to main()
    processed = true;
    std::cout << "Worker thread signals data processing completed\n";

    // Manual unlocking is done before notifying, to avoid waking up
    // the waiting thread only to block again (see notify_one for details)
    lk.unlock();
    cv.notify_one();
}

int main()
{
    std::thread worker(worker_thread);

    data = "Example data";
    // send data to the worker thread
    {
        std::lock_guard<std::mutex> lk(m);
        ready = true;
        std::cout << "main() signals data ready for processing\n";
    }
    cv.notify_one();

    // wait for the worker
    {
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return processed;});
    }
    std::cout << "Back in main(), data = " << data << '\n';

    worker.join();

    return 0;
}

Should not the statement std::unique_lock<std::mutex> lk(m); block the main thread because mutex m is locked by worker_thread? If yes, isn't the statement cv.wait(lk, []{return processed;}); after it unnecessary in this example? When main thread can lock the mutex, processed will be already true.

object initialzation before initialization list [duplicate]

This question already has an answer here:

given:

class A {
    std::list<int> m_list;
    std::list<int>::iterator m_iterator;
public:
    explicit A() : m_iterator(m_list.begin()) { }
};

Am I guaranteed m_list will be constructed before evaluating ctor initialization list, so that a begin() will correctly dereference its beginning/end? Or should I better use an m_iterator assignment inside ctor body?

std::stoi not recognized by eclipse

On my system, running Windows 7 x64, Eclipse Luna, and g++ 4.9.2 (installed via cygwin), it seems std::stoi was never declared by g++. According to the documentation, stoi is part of the string library, so obviously I have #include <string>.

In addition, I know that stoi was introduced in C++11, and I have set the appropriate flags for my compiler (g++), even though this seems like an IDE error, rather than a compiler error.

Still, I would get one of the following error messages when building my project:

error: 'stoi' is not a member of 'std'
error: Function 'stoi' could not be resolved

How do I fix this? How do I make Eclipse recognize stoi?

OCCI linkage error with gcc 5

Recently I've upgraded my gcc from 4.1.2 to 5.2.0.

This caused a linkage error with the OCCI library:

Source Code I'm trying to run:

#include <iostream>
#include <occi.h>
using namespace oracle::occi;
using namespace std;

int main (int argc, char *argv[])
{    
  Environment *env;
  Connection *conn;

  oracle::occi::MetaData metaData = conn->getMetaData ((char *)"PERSON_OBJ");
  metaData.getString(MetaData::ATTR_NAME); 

  return(0);
}

The linkage error:

gmake -f /home/davidd/temp.mak CFG=Debug g++ -g "-Wl,-rpath,/omniqdir/arch/x86_64/release/lib:/omniqdir/instantclient_12_1:/usr/lib,-rpath-link,/omniqdir/arch/x86_64/release/lib:/omniqdir/instantclient_12_1:/usr/lib,-ldl,-lpthread" /omniqdir/arch/x86_64/release/lib/libjemalloc.so -o "Debug/temp" Debug/temp.o /omniqdir/instantclient_12_1/libocci.so /omniqdir/instantclient_12_1/libclntsh.so Debug/temp.o: In function main': temp.cpp:(.text+0xac): undefined reference to_ZNK6oracle4occi8MetaData9getStringB5cxx11ENS1_6AttrIdE' collect2: error: ld returned 1 exit status gmake: *** [Debug/temp] Error 1

I've noticed that the undefined reference contains c++11 related symbols, which i guess have to do with the new gcc compiler I'm using.

Function declaration from occiControl.h

OCCI_STD_NAMESPACE::string getString(MetaData::AttrId attrid)

I'm using Centos 6.6 and latest OCCI version instantclient-basiclite-linux.x64-12.1.0.2.0.

Any ideas?

Thanks, David

Assigning pointer to lambda function to pointer to another lambda function

I am trying to assign a pointer to lambda function to pointer to another lambda function. The code will speak for itself:

#include <iostream>

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

    auto l1 = []() { std::cout << "Lambda 1!" << std::endl; };
    auto l2 = [] { std::cout << "Lambda 2!" << std::endl; };

    auto l1p = &l1;
    l1p = &l2; // Why can't I do this assignment?
    return 0;
}

Since the return types and argument of both lambda functions are the same, can't I do this assignment?

How to get the move constructor calling

Consider following code:

class Base {
public:
    int bi;
    Base() : bi(100)    {std::cout << "\nBase default constructor ...";}
    Base(int i) : bi(i) {std::cout << "\nBase int constructor: "<< bi;}
    Base(const Base& b) {std::cout << "\nBase copy constructor";}
    Base(Base&& b)      {std::cout << "\nBase move constructor";}
};

Base getBase() {
    cout << "\nIn getBase()";
    return Base();  
}
int main() {
    Base b2(getBase());  
    Base b3 = Base(2);   
    Base b4 = getBase(); 
}

In spite of rvalues being given, none of the above constructions in main are calling the move constructor. Is there a way to ensure that user defined move constructor is called?

Here is what I am getting:

In getBase()    
Base default constructor ...
Base int constructor: 2
In getBase()
Base default constructor ...
Base destructor: 100
Base destructor: 2
Base destructor: 100

std::function type and template instantiation

I'm new to C++ and I'm learning about lambdas,functors and callables, and I know that there's a wrapper class, namely std::function that allows callables of different types to be stored and called (as long as the have the same call signature,or function type).

Now, I understand that you can have function with function type parameters that are really just function pointer parameters as in :

void fun(int,int*(int,int&));

which is nothing more than a function that takes an int and a function pointer to a function like int *f(int,int&),even if the language allows me to pass a function as an argument (with or without the ampersand).Infact, the function parameter list might as well be written as:

void fun(int,int*(*)(int,int&));

Now,back to the std::function type

I know that I can instantiate std::function with a function type and that allows any kind of callable to be passed to the wrapper. But, a function type is not a type I can use as a template type argument in any instantiation such as:

std::vector<int(int)> f_vec;

instead, I should make a vector of function pointers

std::vector<int(*)(int)> f_vec;

and that would allow me to insert pointers to function,but not functors or lambdas.

So, my question is, how can I instantiate a template with a type argument like a function type?? what's happening under the hood in the library std::function type.I mean a function type seems to me a type I cannot use in templates?? pleas can you make things a little clearer,as I'm just beginning to learn these topics. Thanks

Issue in passing argument to std::function for vector of functions

I'm trying to create a vector of std::function and then pass that vector to a function. I also need to pass arguments to the function objects, so I'm using std::bind. Here is the code:

#include <functional>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void execute(vector<function<void (int)>>& fs) {
    for (auto& f : fs) 
        f();
}

void func(int k) {
    cout << "In func " << k << endl;
}

int main()
{
    int i = 1;
    vector<function<void (int)>> x;
    auto f1 = bind(func, i);
    x.push_back(f1);

    execute(x);
}

but this gives following error:

function_tmpl.cpp: In function ‘void execute(std::vector >&)’:
function_tmpl.cpp:14:5: error: no match for call to ‘(std::function) ()’
   f();
     ^
In file included from function_tmpl.cpp:1:0:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2142:11: note: candidate is:
     class function
           ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2434:5: note: _Res std::function::operator()(_ArgTypes ...) const [with _Res = void; _ArgTypes = {int}]
     function::
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2434:5: note:   candidate expects 1 argument, 0 provided

If I call f() inside main(), that works fine, which means that the function has bound with the arguments, but it's not working when passed to another function as argument

dimanche 30 août 2015

Undefined Reference issue with C++ and Netbeans

I have the following files:

ListaEnc.hpp

#include "Elemento.hpp"
#include <cstdlib>
#include <iostream>

template<typename T>
class ListaEnc {

public:
    ListaEnc();
    ~ListaEnc();
...
Implementation of ListaEnc<T>

main.cpp:

#include "ListaEnc.hpp"
using namespace std;

int main(int argc, char** argv)
{
    ListaEnc<int>* teste = new ListaEnc<int>();

    return 0;
}

Poligono.hpp

#ifndef POLIGONO_HPP
#define POLIGONO_HPP

#include "Ponto.hpp"
#include "ListaEnc.hpp"
#include <string>

using namespace std;

class Poligono 
{
   ...
};

#endif  /* POLIGONO_HPP */

Poligono.cpp

#include "Poligono.hpp"

Poligono::Poligono(ListaEnc<Ponto> pontos, string nome)
{
    this->pontos = pontos;
    this->nome = nome;
}
...

I get these compile errors on Poligono.cpp:

/home/mariana/NetBeansProjects/TrabalhoCG/Poligono.cpp:12: undefined reference to `ListaEnc::~ListaEnc()'

The destructor for ListaEnc is empty, but is implemented. Does anyone know how to solve this problem?

Why not call nullptr NULL?

In C++11, the nullptr keyword was added, as a more type-safe null pointer constant, since the previous common definition of NULL as 0 has some problems.

Why did the standards committee choose not to call the new null pointer constant NULL, or declare that NULL should be #defined to nullptr?

How to format doubles in the following way?

I am using C++ and I would like to format doubles in the following obvious way. I have tried playing with 'fixed' and 'scientific' using stringstream, but I am unable to achieve this desired output.

double d = -5; // print "-5"
double d = 1000000000; // print "1000000000"
double d = 3.14; // print "3.14"
double d = 0.00000000001; // print "0.00000000001"

What is The Most Effective Data Structure To Use in My Neural Network program? Does my program require dynamic allocation

I have a background in Java and am trying to learn C++. I am currently trying to write a neural network program, but I am struggling with some fundamental concepts with regards to memory allocation. My question is primarily concerned with the Network class.

In the Network constructor I need to initialize an array of pointers to arrays of Neuron objects and pass it to the Network class variable layers. I do not believe I need to use any dynamic memory allocation (i.e. vectors) because I know the size of the arrays at compile time (obviously correct me if I'm wrong here). Should I be declaring the arrays in the constructor and then extending their scope with unique_ptr? or is there a way to initialize the arrays as a class variable and somehow define their sizes in the constructor.

Any suggestions on other parts of my code is also welcome. I am trying to learn as much as I can here.

Also where can I find resources on this stuff? All of the c++ resources I have found cover only the basics.

Network.h

class Network {
public:
    size_t numLayers;
    size_t* layerSizes;
    //array of ptrs to array of Neurons
    /*here I essentially need a two dimensional array of neurons
    where each column is a layer (array) of neurons in the network*/
    vector<unique_ptr<Neuron[]>> layers;
    Network (void){};       //input nodes
    Network (size_t[], size_t);
};

Network.cpp

Network::Network (size_t structure[], size_t size) {
/*structure is an array of values indicating the size of each layer
i.e for an xor nnet structure would equal {2,2,1} for 2 input nodes
2 hiden nodes and 1 output node */

//total number of layers
numLayers = size;   
//number of nodes in each respective layer                  
layerSizes = structure;

for (size_t l = 1; l < size; l++) {
    size_t arraySize = structure[l];
    Neuron temp[arraySize]; //initialize array with default Neurons
    for (size_t n = 0; n < arraySize; n++) {
        temp[n] = Neuron(/*array of Neurons in previous layer, array of random weights, size, threshold*/);
    }
}

}

Neuron.h

class Neuron {
public:
    //ptr to array of connecting neurons
    Neuron** synapse;
    //equal sized array of corresponding weights    
    double* weights;    
    //length of the synapse and weight arrays;
    size_t size;        
    double threshold, value;
    Neuron (void);      //input nodes
    void initialize (Neuron*[], double[], size_t, double);
    int propagate(void);
};

Neuron.cpp

//default constructor
Neuron::Neuron (void) {}

void Neuron::initialize (Neuron* connects[], double initial_weights[], size_t arraySize, double thresh) {
    synapse = connects;
    weights = initial_weights;
    size = arraySize;
    threshold = thresh;
}

int Neuron::propagate (void) {
    double inputSignal = 0.0;
    //sum the weights*values of each connecting node
    for(size_t i = 0; i < size; i++){
        inputSignal += *(weights+i) * (**(synapse+i)).value;
    }
    inputSignal += (-1 * threshold);
    value = 1.0/(1.0 + exp(-inputSignal));
    return 0;
}

Why can't std::function be optimised away?

After reading this question I tried looking at an even simpler case to see if std::function could be completely optimised away:

#include <functional>

int main()
{   
    auto f = []() { return 100; }; // a
    // std::function<int()> f = []() { return 100; }; // b
    return f();
}

the assembly with clang++ -std=c++11 -O3 (clang 3.6) for a and b respectively is:

main: #a
    movl    $100, %eax
    retq

main: #b
    pushq   %rax
    movl    $1, %edi
    callq   operator new(unsigned long)
    movl    $1, %esi
    movq    %rax, %rdi
    callq   operator delete(void*, unsigned long)
    movl    $100, %eax
    popq    %rdx
    retq

operator delete(void*, unsigned long):
    jmp operator delete(void*)

Why can't the construction of the std::function object be optimised away?

C++11 alias template to alias template

Consider I have helper, which binds 1 template parameter to class template, lets say to int as first parameter to std::is_same:

template <class Base, template <typename...>class Exec>
struct t_bind_fst{
    template <class ...Type>
    using type = Exec<Base,Type...>;
};

Now, to use it, I have to :

template<class T>
using is_int = typename t_bind_fst<int, std::is_same >::type<T>;

And I can use is_int for type checking. Now look at the following code (see coments):

http://ift.tt/1NQFqM6

using namespace std;

template <class Base, template <typename...>class Exec>
struct t_bind_fst{
    template <class ...Type>
    using type = Exec<Base,Type...>;
};

/*
template <class Base, template <typename...>class Exec>
using t_bind_fst_t = t_bind_fst<Base, Exec>::template type;  // Why not work ?
*/


template <template<typename...>class Callback, class Cond, class Res, class ...Other>
struct switch_case_callback_t_impl{
    using type = std::conditional_t<
            Callback<Cond>::value,
            Res,
            typename switch_case_callback_t_impl<Callback, Other...>::type
    >;
};

template <template<typename...>class Callback, class Cond, class Res, class Default>
struct switch_case_callback_t_impl<Callback, Cond, Res, Default>{
    using type = std::conditional_t<
            Callback<Cond>::value,
            Res,
            Default
    >;
};


template < template<typename...>class Callback, class ...Conditions>
using switch_case_callback_t = typename switch_case_callback_t_impl<Callback, Conditions...>::type;

template <class Base, class ...Conditions>
using switch_is_same = switch_case_callback_t<
        t_bind_fst<Base, std::is_same>::template type,
        //t_bind_fst_t<Base, std::is_same>,            // want this shortcut
        Conditions...
>;


int main(){
    using T = int;
    using res = switch_is_same<T,
        int,  true_type,
        char, false_type,
        void
    >;

    cout << res::value;
    return 0;    
}

So the question is - why I can't have / or how I can have the following shortcut:

t_bind_fst_t<Base, std::is_same>

Why isn't std::shared_ptr::owner_before noexcept?

I was reading through the interfaces for std::shared_ptr and std::weak_ptr and noticed that almost every member function had at least one overload that was noexcept. Upon further reading, however, I found that neither std::shared_ptr::owner_before nor std::weak_ptr::owner_before could provide this guarantee.

Why can neither shared_ptr nor weak_ptr offer the noexcept guarantee in the method owner_before?

openann c++ compilation fail

I have a problem compiling some c++ code with OpenANN. I wonder if you can help me, here is the log of make: log

I have installed he dependancies for OpenANN.

Thanks

failure to call cv::imread in opencv on mac while compiling with g++

When I call the cv::imread() in main.cpp file on Mac 10.10, I confront with this problem:

Undefined symbols for architecture x86_64:
"cv::imread(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int)", referenced from:
  readOpenCv()     in main.o
"cv::imshow(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, cv::_InputArray const&)", referenced from:
  readOpenCv()     in main.o

However, if I call the function in C language, all the things run well.

IplImage* img = cvLoadImage( filename, CV_LOAD_IMAGE_COLOR);
cvNamedWindow( "MyJPG", CV_WINDOW_AUTOSIZE );
cvShowImage("MyJPG", img);
cvWaitKey(0);
cvReleaseImage( &img );
cvDestroyWindow( "MyJPG" );

someone people say I should add -stdlib=libstdc++ in my makefile, however, it's still useless. After half day passed by, I finally find a solution. Except add -stdlib=libstdc++ on makefile, I have to specify the CXX variable in makefile, because the default g++ will still call the c++ in Mac system instead of installed by homebrew. My whole makefile is like below:

objects = main.o

#you have to specify the c++ version, c++-4.9 was installed by homebrew
CXX = /usr/local/bin/c++-4.9
CC = /usr/local/bin/g++-4.9
PKG_CONFIG = /usr/local/bin/pkg-config

# use any one of the LDFLAGS below
LDFLAGS = `$(PKG_CONFIG) --libs protobuf` `$(PKG_CONFIG) --libs --cflags opencv`
# LDFLAGS = -I/usr/local/include -L/usr/local/lib -lopencv_core -lopencv_highgui

main: $(objects) 
    $(CC) -o main $(objects) $(LDFLAGS)
    # if unspecified the varibale CC, you have to add options -stdlib=libstdc++
    # $(CC) -o main $(objects) $(LDFLAGS) -stdlib=libstdc++

run:
./main

.PHONY : clean
clean:
    -rm main $(objects)

I hope my experience is able to help someone out of troubles.

passing array to a function and using it in for-range loop [duplicate]

This question already has an answer here:

I am learning c++ so question might be stupid but I haven't managed to solve it hence my first SO question :) So I have the following code

# include <iostream>

using namespace std;

void printArr(int Arr[])
{
    for (auto i : Arr)
        cout << i << ", ";
}

int main()
{
    int myArr[] = {28,1,0,55,12,54,22};
    for (auto i : myArr)
        cout << i << ", ";
    // printArr(myArr);
}

The code doesn't compile at the moment. So if you comment out the for range loop the code will compile. The problem is in iterator because compiler says that there is no begin() or end() defined in the scope of the function, but curious thing is that it works in the main() body i.e. just remove function printArr() and it will compile and for range loop will work. I think the problem is in the fact that array is passed as pointer (at least that is how I understand compiler error).

So is there any was to pass array and use for range loop?

I have solved the problem in two ways for now but I am still curious about why it doesn't work because I am basically doing a work around and not understanding what is happening.
First way with <vector>

# include <iostream>
# include <vector>

using namespace std;

void printArr(vector<int> Arr)
{
    cout << "Print func" << endl;
    for (auto i : Arr)
        cout << i << ", ";
}

int main()
{
    vector<int> myArr = {28,1,0,55,12,54,22};
    cout << "Main func" << endl;
    for (auto &i : myArr)
        cout << i << ", ";
    cout << endl;
    printArr(myArr);
}

And by using auto

# include <iostream>
# include <vector>
# include <typeinfo>

using namespace std;

void printArr(auto Arr)
{
    for (auto i : Arr)
        cout << i << ", ";
    cout << endl << "type in the function: " << typeid(Arr).name();
}

int main()
{
    auto myArr {28,1,0,55,12,54,22};
    cout << "deducted type: " << typeid(myArr).name() << endl;  
    for (auto i : myArr)
        cout << i << ", ";
    printArr(myArr);
}

I would also like to know is this the proper way to use auto?
I use compiler g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2 with -std=c++14.

How can I create C++ functions which return each other?

I want to have a few functions in C++ where each function represents a screen in the program. The functions handle user interaction, and based on that will return a std::function to one of the other functions, with parameters bound via std::bind so that the return value can be called with no arguments. It is possible to get from any function to any other function by this process, without using recursion - the main function would be an infinite loop that just calls the returned function over and over.

But I'm stumped here - what should the definition of the return type be for these functions? They need to return std::function objects that take no parameters, but that's as far as I can get. std::function<what_goes_here ()>?

How fix compile error: invalid initialization of non-const reference of type 'std::__1::string&

I'm new in C++ and i can't figure out what's wrong with this code

 string& GetAddonCmeterString(string& sid) {
     ostringstream oss;
     oss <<  "{"; 
     oss <<     "currentValues : {sid : " << sid << "}"; 
     oss <<  "}";
     string& result = oss.str();
     return result;
 }

Compile error message:

error: invalid initialization of non-const reference of type 'std::__1::string& {aka std::__1::basic_string, std::__1::allocator >&}' from an rvalue of type 'std::__1::basic_string, std::__1::allocator >' string& result = oss.str();

Are compilers able to avoid branching instructions?

I've been reading about bit twiddling hacks and thought, are compilers able to avoid branching in the following code:

constexpr int min(const int lhs, const int rhs) noexcept {
    if (lhs < rhs) {
        return lhs;
    }
    return rhs
}

by replacing it with (explanation):

constexpr int min(const int lhs, const int rhs) noexcept {
    return y ^ ((x ^ y) & -(x < y));
}

Why doesn't changing the value of the object that is pointed doesn't change in shared_ptr?

While using raw pointer if you changed the value of the object that is pointed the pointer's value while dereferecing also changes. But while using shared_ptr that is not the case. Why is it so?

    int i = 3; 
    shared_ptr<int> q = make_shared<int>(i);
    //  what i want "int*q = &i;"
    i = 5;
    cout << *q << endl; //isn't it suppose to print 5

invalid use of incomplete type boost function_traits

I tried to make following things work but it failed to compile.

// T is a function with a callback, std::function<void(std::function<void (DataType)> >
struct doFunc {
    template<typename T>
    void operator()(T && func) {
        auto callback = [](typename function_traits<typename function_traits<T>::arg1_type >::arg1_type r) {
            std::cout << r;
        };
        func(callback);
    }
};

// usage
doFunc()([](std::function<void(string)> cb){
    cb("hello");
});

the error is:

invalid use of incomplete type 'struct boost::detail::function_traits_helper<SomeClass::TestBody()::<lambda(std::function<void(std::__cxx11::basic_string<char>)>)>*>'

Is this because the compiler cannot deduct the type out? If I want to keep the usage like that, How to fix it?

samedi 29 août 2015

use-after-move POD parts of composite class with defaulted move ctor

Suppose we have a class with non-POD and POD parts. Move constructor and move assignments are defaulted. Are the POD-parts of an instance of this class safe to use after a move?

#include <string>
struct A {
    std::string s = "foo";
    int i = 42;
};
A a;
A b = std::move(a);
int j = a.i; //OK or UB?

Is element-wise move/copy guaranteed (so this would be OK) or could a conforming implementation alter the POD parts (e.g., by swapping with a default-constructed object)?

Simulating the range-based for loop's begin/end behavior

Consider the specification of the range-based for loop's begin-expr and end-expr (N4140 [stmt.ranged]/p1). Given a range __range of type _RangeT,

begin-expr and end-expr are determined as follows:

  • if _RangeT is an array type, begin-expr and end-expr are __range and __range + __bound, respectively, where __bound is the array bound. If _RangeT is an array of unknown size or an array of incomplete type, the program is ill-formed;
  • if _RangeT is a class type, the unqualified-ids begin and end are looked up in the scope of class _RangeT as if by class member access lookup (3.4.5), and if either (or both) finds at least one declaration, begin-expr and end-expr are __range.begin() and __range.end(), respectively;
  • otherwise, begin-expr and end-expr are begin(__range) and end(__range), respectively, where begin and end are looked up in the associated namespaces (3.4.2). [ Note: Ordinary unqualified lookup (3.4.1) is not performed. —end note ]

Is it possible to simulate this exact behavior in ordinary C++ code? i.e., can we write a magic_begin and a magic_end function template such that

for(auto&& p : range_init) { /* statements */ }

and

{
    auto&& my_range = range_init;
    for(auto b = magic_begin(my_range), e = magic_end(my_range); b != e; ++b){
        auto&& p = *b;
        /* statements */
    }
}

always have the exact same behavior?

Non-answers include qualified calls to std::begin/std::end (doesn't handle the third bullet, among other things) and using std::begin; begin(range); because, among other things, that is ambiguous if ADL for begin finds an overload that's equally good as std::begin.

Moving std::function with member function

I've written a super simple event system using std::function.

It amounts to

std::vector<Delegate<Args ...>*> _delegates;

Where Delegate is a typedef of std::function

template <typename ... Args>
using Delegate = std::function<void(Args ...)>;

With the event's operator(), operator+=, and operator-= overloaded.

operator() calls all of the listening functions.
operator+= adds a listener.
operator-= removes a listener.

Hooking them up looks like this...

Foo::Foo(Bar& bar)
{
    m_bar_ptr = &bar;

    using namespace std::placeholders;

    event_receiver =
    Delegate<const Bar&, const SomeBarData>
    (std::bind(&Foo::OnEventReceived, this, _1, _2));
    bar.BarEvent += event_receiver;
}

Everything works as intended, but when I move the owner of a Delegate I end up having to unhook and duplicate the code for the initial hook up (as expected).

It looks like this...

Foo& Foo::operator=(Foo&& other)
{
    m_bar_ptr = other.m_bar_ptr;
    other.m_bar_ptr = nullptr;

    m_bar_ptr->BarEvent -= other.event_receiver;

    using namespace std::place_holders;

    event_receiver =
    Delegate<const Bar&, const SomeBarData>
    (std::bind(&Foo::OnEventReceived, this, _1, _2));
    bar.BarEvent += event_receiver;
}

Aside from having to keep a handle to Bar, which is acceptable, this is a lot of code to re-target the Delegate...and leaves a lot of room for error.

I like the simplicity of these events (though I am open to suggestions), but what I'm really looking for is a way to keep this event system and simplify moves.

Any suggestions?

Thanks

std::bind syntax difference between global and member functions

When using std::bind, why is it that I must specify a & before a member function, but not before a global function? For instance, my main.cpp is:

  1 #include <functional>
  2 
  3 class Foo
  4 {
  5   public:
  6     void Exec(void) {}
  7 };
  8 
  9 void Exec(void) {}
 10 
 11 int main(void)
 12 {
 13   Foo inst;
 14   auto blah1 = std::bind(Exec);
 15   //auto blah2 = std::bind(Foo::Exec, &inst);
 16   auto blah2 = std::bind(&Foo::Exec, &inst);
 17   blah1();
 18   blah2();
 19   return 0;
 20 }

This compiles fine, but if I uncomment 15 and comment line 16, I get:

$ g++ main.cpp -o a.out -std=c++11 -Wall
main.cpp: In function ‘int main()’:
main.cpp:15:31: error: invalid use of non-static member function ‘void Foo::Exec()’
   auto blah2 = std::bind(Foo::Exec, &inst);

I really don't understand this error. I would have expected both instances to either require & or not, but they turned out to be treated differently. Can someone help me understand why the compiler is picky about this difference?

Box2D b2body segmentation fault

Some I'm trying to encapsulate an object with Box2D and SFML. It's supposed to just be a simple box. I'll expand on it to be adaptable to other shapes later on once I have the basics worked out. However, I have gotten stuck with a segmentation fault. I tried searching online for answers, but I'm still lost.

Here is where my boxes get called to be created. Nothing wrong appears to happen here.

main.cpp

if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
    int MouseX = sf::Mouse::getPosition(Window).x;
    int MouseY = sf::Mouse::getPosition(Window).y;
    Box box(&World, MouseX, MouseY);
    box.setTexture(BoxTexture);
    boxes.push_back(box);
}

Next this is the Box constructor. Still seems to run through this without an issue.

Box.cpp

Box::Box(b2World* World, int MouseX, int MouseY)
{

    Shape.SetAsBox((32.f/2)/SCALE, (32.f/2)/SCALE);
    BodyDef.position = b2Vec2(MouseX/SCALE, MouseY/SCALE);
    BodyDef.type = b2_dynamicBody;
    b2Body* Body = World->CreateBody(&BodyDef);
    FixtureDef.density = 1.f;
    FixtureDef.friction = 0.7f;
    FixtureDef.shape = &Shape;
    Body->CreateFixture(&FixtureDef);
}

Once a box is created and added to the vector, it's supposed to update the sprite attached.

main.cpp

for(int i = 0; i < boxes.size(); i++)
{
    boxes[i].update();
    Window.draw(boxes[i].getSprite());
}

The code for the update is where I receive the segmentation fault. It appears whenever I call the pointer for Body.

Box.cpp

void Box::update()
{
    sprite.setOrigin(16.f, 16.f);
    sprite.setPosition(SCALE * Body->GetPosition().x, SCALE * Body->GetPosition().y); //Segmentation Fault
    sprite.setRotation(Body->GetAngle() * 180/b2_pi); //Segmentation Fault
}

Here I'll provide the entire files in case you may need something I didn't provide to help me.

main.cpp: http://ift.tt/1KuAI5s

Box.h: http://ift.tt/1Jtu4dD

Box.cpp: http:// pastebin (dot) com/1y1cpwzq

sorry about that last one. Says I can only post 2 links

increment begin() (of a list) in c++ stl doesn't work

I have this code

list<int> p {5,3,6,2,1};
vector<int> v {2,3,4};
cout<<*(v.begin() + 1);
cout<<*(p.begin() +1);

I get output of the 3rd line as 3 but the 4th line shows this error

no match for 'operator+' (operand types are 'std::list<int>::iterator {aka std::_List_iterator<int>}' and 'int')

What's wrong here .. why does the increment doesn't work with a list pointer..?

Porting the code for GetExtendedTCPTable in older c++ compilers

vector<unsigned char> buffer;    
DWORD dwRetValue = 0;
DWORD dwSize = sizeof(MIB_TCPTABLE_OWNER_PID);
struct in_addr clientAddr;
do{
    buffer.resize(dwSize, 0);
    dwRetValue = GetExtendedTcpTable(buffer.data(), &dwSize, TRUE, AF_INET,  TCP_TABLE_OWNER_PID_ALL, 0);
} while (dwRetValue == ERROR_INSUFFICIENT_BUFFER);
if (dwRetValue == ERROR_SUCCESS)
{
    PMIB_TCPTABLE_OWNER_PID ptTable = reinterpret_cast<PMIB_TCPTABLE_OWNER_PID>(buffer.data());
        //Iterate through ptTable->dwNumEntries
}

I need to initialize the vector buffer.data,it works with compilers who support C++11 but for older compilers say VS2005 this wont run.So instead of Vector i initialized it as unsigned char * buffer with dwSize as its length and passed its address as the first parameter instead of buffer.data but with no success.What am i missing? So basically the question comes down as how to effectively use vector:: data in general c++.Any help is highly appreciated.

Best way to delete job context objects in a pipelined processor

I appreciate it if someone suggests best way to finally delete context objects used represent a job processed through a pipeline of steps.

Here in the following code an object of class text_file_processing_request is created and sent to the io_service. My pipeline here is made up of one step, there could be more steps in real code.

Now, I would like to get opinions on the best way to delete these objects of type text_file_processing_request once they are done with.

Thank you!

#include <iostream>
#include "boost/asio.hpp"
#include "boost/thread.hpp"

using namespace std;
namespace asio = boost::asio;

typedef std::unique_ptr<asio::io_service::work> work_ptr;

typedef boost::function<void(void) > parse_and_aggregate_fun_t;

class file_processing_request{
 public:
    virtual void process(int num) = 0;
};

class text_file_processing_request : public file_processing_request {
public:
    virtual void process(int num) {
        cout << "text_file_processing_request::process " << num << endl;
    }
};

class processor {
public:
    processor(int threads) : thread_count(threads) {
        service = new asio::io_service();
        work = new work_ptr(new asio::io_service::work(*(service)));
        for (int i = 0; i < this->thread_count; ++i)
            workers.create_thread(boost::bind(&asio::io_service::run, service));
    }

    void post_task(parse_and_aggregate_fun_t job){
        this->service->post(job);
    }

    void stop(){
        this->work->reset();
    }

    void wait()
    {
        this->workers.join_all();
    }
private:
    int thread_count;
    work_ptr * work;
    asio::io_service* service;
    boost::thread_group workers;
};

class job_discoverer {
public:
    job_discoverer(processor *p): worker(p){}
    void start_producing(){

        do {
            file_processing_request * cPtr = new text_file_processing_request();
            this->worker->post_task(boost::bind(&file_processing_request::process, cPtr, 42));
        } while (0);

        this->worker->stop(); // no more data to process
    }
private:
    processor *worker;
};

int main(int argc, char** argv) {

    processor *pr = new processor(4);
    job_discoverer disocverer(pr);
    disocverer.start_producing();

    pr->wait();

    delete pr;

    return 0;
}

Strange Segfault on Ubuntu 15.04

I'm in a Comp Sci class and my teacher uses a testing framework to grade our homeworks. I can build my assignments, but when I attempt to run, I get a segmentation fault. In LLDB, I get this backtrace:

* thread #1: tid = 11993, 0x00007ffff796e990 libstdc++.so.6`std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string(), name = 'cpp_refresher', stop reason = invalid address (fault address: 0x10)
  * frame #0: 0x00007ffff796e990 libstdc++.so.6`std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()
    frame #1: 0x000000000042229c cpp_refresher`MemoryAllocation::~MemoryAllocation() + 28
    frame #2: 0x0000000000422555 cpp_refresher`void std::_Destroy<MemoryAllocation>(MemoryAllocation*) + 21
    frame #3: 0x000000000042251f cpp_refresher`void std::_Destroy_aux<false>::__destroy<MemoryAllocation*>(MemoryAllocation*, MemoryAllocation*) + 47
    frame #4: 0x00000000004224dd cpp_refresher`void std::_Destroy<MemoryAllocation*>(MemoryAllocation*, MemoryAllocation*) + 29
    frame #5: 0x0000000000422321 cpp_refresher`void std::_Destroy<MemoryAllocation*, MemoryAllocation>(MemoryAllocation*, MemoryAllocation*, std::allocator<MemoryAllocation>&) + 33
    frame #6: 0x0000000000421847 cpp_refresher`std::vector<MemoryAllocation, std::allocator<MemoryAllocation> >::~vector() + 55
    frame #7: 0x00000000004217a5 cpp_refresher`UTTest::~UTTest() + 37
    frame #8: 0x0000000000422f49 cpp_refresher`UTTestRunner::RunSuite(std::string, std::function<void (UTTestRunner*)>) + 249
    frame #9: 0x000000000041e716 cpp_refresher`main + 118
    frame #10: 0x00007ffff6fe4a40 libc.so.6`__libc_start_main + 240
    frame #11: 0x000000000041bc09 cpp_refresher`_start + 41

Based on this, I think that the testing framework is causing the standard C++ libraries to segfault when it attempts to destroy a string. The interesting this is that this only occurs on Ubuntu 15.04. I can run this script on Ubuntu 14.04 and it runs perfectly.

Any ideas why this is happening only in Ubuntu 15.04?

Variadic template error -- MSVS2013 compiles, clang-3.5 does not

The code below compiles and runs fine with MSVC 2013, but not clang++3.6. Which compiler is correct?

MSVC 2013 compiles and executes the code, printing 26.04:

#include <iostream>

template <typename T, typename ... U>
auto mul(T t, U ... u) -> decltype(t * mul(u ...))
{
    return t * mul(u ...);
}

template <typename T>
T mul(T t) { return t; }

int main()
{
    std::cout << mul(2., 3.1, 4.2) << std::endl;
}

However, compiling with clang++-3.6 yields errors:

$ clang++ test.cpp -stdlib=libc++ -Wall -Wextra -std=c++14 
prog.cc:14:15: error: no matching function for call to 'mul'
        std::cout << mul(2., 3.1, 4.2) << std::endl;
                     ^~~
prog.cc:4:6: note: candidate template ignored: substitution failure [with T = double, U = <double, double>]: use of undeclared identifier 'mul'
auto mul(T t, U ... u) -> decltype(t * mul(u ...))
     ^                                 ~~~
prog.cc:10:3: note: candidate function template not viable: requires single argument 't', but 3 arguments were provided
T mul(T t) { return t; }
  ^
1 error generated.

Is the declaration of mul is not available to determine the return typedecl?

Boost Spirit: Sub-grammar appending to string?

I am toying with Boost.Spirit. As part of a larger work I am trying to construct a grammar for parsing C/C++ style string literals. I encountered a problem:

How do I create a sub-grammar that appends a std::string() result to the calling grammar's std::string() attribute (instead of just a char?

Here is my code, which is working so far. (Actually I already got much more than that, including stuff like '\n' etc., but I cut it down to the essentials.)

#define BOOST_SPIRIT_UNICODE

#include <string>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

using namespace boost;
using namespace boost::spirit;
using namespace boost::spirit::qi;

template < typename Iterator >
struct EscapedUnicode : grammar< Iterator, char() > // <-- should be std::string
{
    EscapedUnicode() : EscapedUnicode::base_type( escaped_unicode )
    {
        escaped_unicode %= "\\" > ( ( "u" >> uint_parser< char, 16, 4, 4 >() )
                                  | ( "U" >> uint_parser< char, 16, 8, 8 >() ) );
    }

    rule< Iterator, char() > escaped_unicode;  // <-- should be std::string
};

template < typename Iterator >
struct QuotedString : grammar< Iterator, std::string() >
{
    QuotedString() : QuotedString::base_type( quoted_string )
    {
        quoted_string %= '"' >> *( escaped_unicode | ( char_ - ( '"' | eol ) ) ) >> '"';
    }

    EscapedUnicode< Iterator > escaped_unicode;
    rule< Iterator, std::string() > quoted_string;
};

int main()
{
    std::string input = "\"foo\u0041\"";
    typedef std::string::const_iterator iterator_type;
    QuotedString< iterator_type > qs;
    std::string result;
    bool r = parse( input.cbegin(), input.cend(), qs, result );
    std::cout << result << std::endl;
}

This prints fooA -- the QuotedString grammar calls the EscapedUnicode grammar, which results in a char being added to the std::string attribute of QuotedString (the A, 0x41).

But of course I would need to generate a sequence of chars (bytes) for anything beyond 0x7f. EscapedUnicode would neet to produce a std::string, which would have to be appended to the string generated by QuotedString.

And that is where I've met a roadblock. I do not understand the things Boost.Spirit does in concert with Boost.Phoenix, and any attempts I have made resulted in lengthy and pretty much undecipherable template-related compiler errors.

So, how can I do this? The answer need not actually do the proper Unicode conversion; it's the std::string issue I need a solution for.

Object changing after storing and retrieving from unordered_map

Consider the following code. I want to use mutex_by_name() to create and retrieve mutexes. The lock is not a real lock, but should do its job with a one second gap.

Expected output is that m4.lock() fails aka prints lock FAILED because _locked is already set to true. But it does lock. I'm new to C++ and pretty sure I'm missing something obvious. Can you please explain how to implement that correctly.

#include <iostream>
#include <string>
#include <unordered_map>
#include <unistd.h>

class Mutex {
private:
    int _id;
    bool _locked = false;
    void status(std::string s) {
        std::cout << _id << " " << name << " " << s << " " << std::endl;
    }
public:
    const std::string name;
    Mutex(std::string name): name(name) {
        static int id = 0;
        _id = id++;
        status("created");
    }
    Mutex(const Mutex& m): _id(m._id), _locked(m._locked), name(m.name) {
        status("copy-constructed");
    }
    Mutex(Mutex&& m) = delete;
    void operator=(Mutex&) = delete;
    ~Mutex() {
        status("deleted");
    }
    void lock() {
        // YES, THIS IS NOT A REAL AND SAFE LOCK
        if (!_locked) {
            _locked = true;
            status("locked");
        } else {
            status("lock FAILED");
        }
    }
};

std::unordered_map<std::string, Mutex> mutexe;

Mutex& mutex_by_name(std::string name) {
    mutexe.emplace(name, Mutex(name));
    auto found = mutexe.find(name);
    return found->second;
}


using namespace std;

int main() {
    cout << "# 1" << endl;
    Mutex m1 = mutex_by_name("hello");
    m1.lock();
    sleep(1);

    cout << "# 2" << endl;
    Mutex m4 = mutex_by_name("hello");
    m4.lock();
    sleep(1);
}

Error when pass std::map as template template argument

I defined a function like this, in which there is a template template class

template<typename Key, typename Value, template <typename, typename> class Map>
    struct ForEachOf {
        void operator()(const Map<Key, Value>& map, std::function<void (Key, Value)> func) {
            for(const auto& pair : map) {
                func(pair.first, pair.second);
            }
        }
    };

std::map<int, string> m { {1, "foo"}, {3, "bar"}};
ForEachOf<int, string, std::map> forEachOf;
    forEachOf(m, [](int key, string value) {
        cout << key << value;
    });

However, above code is not able to compile. the error is like:

error: template template argument has different template parameters
      than its corresponding template template parameter
    ForEachOf<int, string, std::map> forEachOf;
/Applications/http://ift.tt/1N2a2el: note: too many template
      parameters in template template argument
    template <class, class, class, class> friend class _LIBCPP_TYPE_VIS_ONLY map;
note: previous template template parameter is here
    template<typename Key, typename Value, template <typename, typename> class Map>

Then How to pass std::map as the template template parameter here?

decltype definning a variable as a reference

I was studying about the differences between auto and decltype type specifier and I had saw in another question that when I use decltype with a reference, like this:

const int ci = 0, &cj = ci;
decltype(ci) x = 0;
decltype(cj) y = x; 

decltype(cj) will not give me the type of the object that cj refers to (that is, const int) but will give me the type of cj itself. So y will be const int&.

Why it happens? And it could affect my code in someway? Is it related with the difference between decltype() and decltype(())?

c++ - Understanding what exactly this code does [duplicate]

This question already has an answer here:

I have the following snippet:

    cin.ignore(numeric_limits<streamsize>::max(), '\n');

I am trying to understand precisely what it does, as I cannot figure it out... here it is in context:

while (!(cin >> originalPrice)) {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "That wasn't good input!\nEnter the original price of the item you are buying: (ex. 5.45):";
                        }

I think it prevents us from capturing the carriage return, but I am a C++ noob and am lost.

c++11 constructor with variadic universal references and copy constructor

How to declare copy constructor, if we have constructor with universal reference arguments, also?

http://ift.tt/1LBY5sE

struct Record{
    template<class ...Refs>
    explicit Record(Refs&&... refs){
        cout << "param ctr" << endl;
    }

    Record(const Record& other){     // never called
        cout << "copy ctr" << endl;
    }

    Record(Record&& other){         // never called
        cout << "move ctr" << endl;
    }    
};

int main() {
    Record rec("Hello");    
    Record rec2(rec);  // do "param ctr"

    return 0;
}

According to this constructor list of std::tuple http://ift.tt/1NNO6CK [look case 3 and 8] this problem somehow solved in standard library... But I can't get through stl's code.


P.S. Question somewhat related to C++ universal reference in constructor and return value optimization (rvo)

P.P.S. For now, I just added additional first param Record(call_constructor, Refs&&... refs) for really EXPLICIT call. And I can manually detect if we have only one param and if it is Record, and than redirect call to copy ctr/param ctr, but.... I can't believe there is no standard way for this...

Multidimensional brace-enclosed initializer list to multi vector

What I want is a possiblility to generate a 5x5 matrix via a brace-enclosed initializer list. So that it may look later like:

enum class MyListType  {
  EMPTY,
  A
};

auto matrix = {
  {MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY},
  {MyListType::A, MyListType::A, MyListType::A, MyListType::A, MyListType::A},
  {MyListType::A, MyListType::A, MyListType::A, MyListType::A, MyListType::A},
  {MyListType::A, MyListType::A, MyListType::A, MyListType::A, MyListType::A},
  {MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY}
};

auto somthing = std::make_shared<Matrix5T>(matrix);

For that I have now my Matrix5T class, which works at the moment only for vectors:

class Matrix5T
{
public:
  Matrix5T(std::initializer_list<MyListType> matrixIn)
    : matrix(std::make_shared<std::vector<MyListType> >(matrixIn))
  {}

  virtual ~TileMatrix() = default;

private:
  std::shared_ptr<std::vector<MyListType> > matrix;
}

So I can do the following:

auto matrix = {
  MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY,
  MyListType::A, MyListType::A, MyListType::A, MyListType::A, MyListType::A,
  MyListType::A, MyListType::A, MyListType::A, MyListType::A, MyListType::A,
  MyListType::A, MyListType::A, MyListType::A, MyListType::A, MyListType::A,
  MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY, MyListType::EMPTY
};

auto somthing = std::make_shared<Matrix5T>(matrix);

At the moment I don't find a solution to have a multidimensional vector in my class initialized by a multidimensional brace-enclosed initializer list.

I tried for example the following, which results in errors:

class Matrix5T
{
public:
  Matrix5T(std::initializer_list<std::initializer_list<MyListType> > matrixIn)
    : matrix(std::make_shared<std::vector<std::vector<MyListType> > >(matrixIn))
  {}

  virtual ~TileMatrix() = default;

private:
  std::shared_ptr<std::vector<std::vector<MyListType> > > matrix;
}

Error is saying that the conversion from the initializer list to the multidimensional vector does not work:

no known conversion for argument 1 from ‘std::initializer_list<std::initializer_list<MyListType> >’ to ‘const std::vector<std::vector<MyListType> >&’

So how can I fix this?

Compile time string encryption using constexpr

I want to have a compile-time string encryption, such that I could write in my code:

const auto encryptedInvalidLicense = ENCRYPT("Invalid license");
std::cout << encryptedInvalidLicense.decrypt() << std::endl; // outputs "Invalid license"

and the string "Invalid license" wont appear in the binaries. Pre-builds might be the answer, but I'm looking for a pure c++ constexpr solution to this problem, and that it will be supported by VS2015.

Any suggestions?


  1. I've already looked into Compile-time string encryption, which doesn't provide a constexpr solution to the problem.

  2. I've also looked into http://ift.tt/1fN60YE . Though it's a constexpr solution, VS2015 still adds the strings plain text to the binaries.

Seeking compile-time formula for many specializations

Is there a way to write

template <int> struct Map;
template <> struct Map<0> { using type = index_sequence<0>; };
template <> struct Map<1> { using type = index_sequence<1>; };
template <> struct Map<2> { using type = index_sequence<2>; };
template <> struct Map<3> { using type = index_sequence<0,1>; };
template <> struct Map<4> { using type = index_sequence<0,2>; };
template <> struct Map<5> { using type = index_sequence<1,2>; };
template <> struct Map<6> { using type = index_sequence<0,1,2>; };

as one single unspecialized template?

template <int N> struct Map {
    using type = index_sequence<???>;
};

Here the int template arguments shall always be listed in increasing order and can only have values 0, 1,..., MAX. The case for MAX == 2 is the example above. How to write the above for any value of MAX?

In case you are wondering, this example usage is a motivation for the solution:

#include <iostream>
#include <array>
#include <list>

class Base {
    public:  virtual ~Base() = default;
};

template <int...>  // The ints shall always be listed in increasing order and have values 0, 1, or 2.
class Derived : public Base {};

std::array<std::list<Base*>, 7> groups;

template <int...> struct index_sequence {};

template <int> struct Map;
template <> struct Map<0> { using type = index_sequence<0>; };
template <> struct Map<1> { using type = index_sequence<1>; };
template <> struct Map<2> { using type = index_sequence<2>; };
template <> struct Map<3> { using type = index_sequence<0,1>; };
template <> struct Map<4> { using type = index_sequence<0,2>; };
template <> struct Map<5> { using type = index_sequence<1,2>; };
template <> struct Map<6> { using type = index_sequence<0,1,2>; };

template <int... Is>
bool isDerivedType (const index_sequence<Is...>&, Base* base) {
    return dynamic_cast<Derived<Is...>*>(base) != nullptr;
}

template <int N>
void checkTypes (Base* base, std::array<std::list<Base*>, 7>& array) {
    if (isDerivedType(typename Map<N>::type{}, base))
        groups[N].push_back(base);
    else
        checkTypes<N+1>(base, array);   
}

template <>
void checkTypes<7> (Base*, std::array<std::list<Base*>, 7>&) {}  // End of recursion

int main() {
    const std::list<Base*> list = {new Derived<0>, new Derived<1,2>, new Derived<0,2>, new Derived<1>, new Derived<1,2>, new Derived<0>, new Derived<0,1,2>, new Derived<0,1>, new Derived<1,2>, new Derived<2>, new Derived<2>, new Derived<0>, new Derived<0,2>};
    for (Base* x : list)
        checkTypes<0>(x, groups);
    for (int i = 0; i < 7; i++) {
        std::cout << "Group " << i << ": ";
        for (const Base* x : groups[i])
            std::cout << x << "  ";
        std::cout << '\n';
    }
}

/*
Output:

Group 0: 0x6e13f0  0x6e1940  0x6e5d80
Group 1: 0x6e1900
Group 2: 0x6e5dd0  0x6e5d60
Group 3: 0x6e5e40
Group 4: 0x6e18e0  0x6e5d70
Group 5: 0x6e1440  0x6e1920  0x6e5db0
Group 6: 0x6e1960
*/

OpenSource project. C++11/14

I am looking for some opensource project written in C ++.

Important for me are:

  1. A project developed in C ++ 11/14.
  2. I would like to highlight that I am not expert ( but I am not newbie as well) so I'm looking for something help me develop my skills.

Let me recommend something.

Check whether a type is a template specialization or not

Given an arbitrary template class/struct, just like:

template <typename T>
struct A {};

I would like to perform a <type_traits> fashion check (let's name it is_A) to determine whether an arbitrary type is a specialization of A or not, just like:

#include <type_traits>

template <typename T>
struct is_A: std::integral_constant<bool, /* perform the check here */ > {};

constexpr bool test0 = is_A< A<int> >::value // true
constexpr bool test1 = is_A< A<float> >::value // true
constexpr bool test2 = is_A< int >::value // false
constexpr bool test2 = is_A< float >::value // false

How is that possible?

Thanks in advance

vendredi 28 août 2015

Boost.Bind'ing a member function and posting it to io_service

I am trying to wrap an object that represents a job to be done by an io_service.

The job is of arbitrary type, and does not have to be an IO operation. Similar to what is described here.

I have been able to post bound regular functions, but was not able to post member functions.

Why this code does not compile:

#include <iostream>
#include "boost/asio.hpp"
#include "boost/thread.hpp"

using namespace std;
namespace asio = boost::asio;

class class_fun1 {
public:

    void an_expensive_calculation(int num) {
        cout << "an_expensive_calculation: " << num << endl;
    }
};

class class_fun2 {
public:
    void a_long_running_task(int num) {
        for (int x = 0; x < num; ++x)
            cout << "a_long_running_task: " << num << endl;
    }
};

int main(int argc, char** argv) {

    int my_thread_count = 4;

    asio::io_service io_service;
    asio::io_service::work work(io_service);

    boost::thread_group threads;
    for (std::size_t i = 0; i < my_thread_count; ++i)
        threads.create_thread(boost::bind(&asio::io_service::run, &io_service));

    class_fun1 f1();
    class_fun2 f2();
    io_service.post(boost::bind(&class_fun1::an_expensive_calculation, &f1, 42));
    io_service.post(boost::bind(&class_fun2::a_long_running_task, &f2, 123));

    threads.join_all();

    return 0;
}

while this one works:

#include <iostream>
#include "boost/asio.hpp"
#include "boost/thread.hpp"

using namespace std;
namespace asio = boost::asio;

void an_expensive_calculation(int num) {
    cout << "an_expensive_calculation: " << num << endl;
}

void a_long_running_task(int num) {
    for (int x = 0; x < num; ++x)
        cout << "a_long_running_task: " << num << endl;
}


int main(int argc, char** argv) {

    int my_thread_count = 4;

    asio::io_service io_service;
    asio::io_service::work work(io_service);

    boost::thread_group threads;
    for (std::size_t i = 0; i < my_thread_count; ++i)
        threads.create_thread(boost::bind(&asio::io_service::run, &io_service));

    io_service.post(boost::bind(an_expensive_calculation, 42));
    io_service.post(boost::bind(a_long_running_task, 123));

    threads.join_all();

    return 0;
}

I went through some of the online tutorials and documentation, and as far as I know that first should work. I followed the guidelines for binding a member function and posting it to io_service, but it did not work.

Failure to instantiate function template involving universal (forward) reference to templated type

Universal references (i.e. "forward references", the c++ standard name) and perfect forwarding in c++11, c++14, and beyond have many important advantages; see here, and here.

In Scott Meyers' article referenced above (link), it is stated as a rule of thumb that:

If a variable or parameter is declared to have type T&& for some deduced type T, that variable or parameter is a universal reference.

Example 1

Indeed, using clang++ we see that the following code snippet will successfully compile with -std=c++14:

#include <utility>                                                                                                                                                                                                                                                             

template <typename T>                                                                                                                   
decltype(auto) f (T && t)                                                                                                               
{                                                                                                                                       
    return std::forward<T> (t);                                                                                                         
}                                                                                                                                       

int        x1 = 1;                                                                                                                      
int const  x2 = 1;                                                                                                                      
int&       x3 = x1;                                                                                                                     
int const& x4 = x2;                                                                                                                     

// all calls to `f` result in a successful                                                                                              
// binding of T&& to the required types                                                                                                 
auto r1 = f (x1);                                                                                                                       
auto r2 = f (x2);                                                                                                                       
auto r3 = f (x3);                                                                                                                       
auto r4 = f (x4);

Given any description of universal references (forward references) and type deduction (see, for instance, this explanation) it is clear why the above works. Although, from the same explanation, it is not abundantly clear why the below fails to work as well.

(failed) Example 2

This question addresses the same issue. The provided answers do not, however, explain why templated types are not categorized as being "deduced".

What I am about to show (seemingly) satisfies the requirement stated above by Meyers. However, the following code snipped fails to compile, producing the error (among others for each call to f):

test.cpp:23:11: error: no matching function for call to 'f'

auto r1 = f (x1);

test.cpp:5:16: note: candidate function [with T = foo, A = int] not viable: no known conversion from 'struct foo< int >' to 'foo< int > &&' for 1st argument

decltype(auto) f (T< A > && t)

#include <utility>                                                                                                                                                                                                                                                             

//
// It **seems** that the templated type T<A> should
// behave the same as an bare type T with respect to
// universal references, but this is not the case.
// 
template <template <typename> typename T, typename A>                                                                                                                   
decltype(auto) f (T<A> && t)                                                                                                               
{                                                                                                                                       
    return std::forward<T<A>> (t);                                                                                                         
}

template <typename A>                                                                                                                 
struct foo                                                                                                                            
{                                                                                                                                     
    A bar;                                                                                                                            
};                                                                                                                                    

struct foo<int>        x1 { .bar = 1 };                                                                                               
struct foo<int> const  x2 { .bar = 1 };                                                                                               
struct foo<int> &      x3 = x1;                                                                                                       
struct foo<int> const& x4 = x2;                                                                                                       

// all calls to `f` **fail** to compile due 
// to **unsuccessful** binding of T&& to the required types                                                                                                
auto r1 = f (x1);                                                                                                                     
auto r2 = f (x2);                                                                                                                     
auto r3 = f (x3);                                                                                                                     
auto r4 = f (x4);

In context, since the type T<A> of f's parameter is deduced, surely the parameter declaration T<A>&& t would behave as a universal reference (forward reference).

Why is this not the case? Are there techniques to overcome this problem with templated types in c++11/14? Are there well known, extant codebases (in the wild) making successful use of c++'s forward references with templated types?

How to maintain a thread safe reference to an element in another class

I have a class (class A) that is using the monitor pattern for safe access to a std::deque. Any time I need to simply add or remove an element I am fine. But sometimes a different class (Class B) needs to call in and get a reference to an element in the deque in Class A. I have been returning an iterator to that element, but there's the chance that another thread could 'push' a new element into Class A and invalidate the iterator that the Class B is using. The only way I can think to prevent this is to lock a mutex in Class A before returning the iterator, and then have the Class B call another function when it's finished to release the mutex, but this seems hackey. Any Ideas for a cleaner way.

Thanks.

Optimize away unused parameterized fields

I'm trying to define a parent class for a hierarchy of "codecs" that operate on a memory "membuf" - some of these codecs are purely functional, but some need to have (non-local) side-effects, like setting a bit in a byte somewhere ("flags" below). So, I'd like to have 2 parent classes, essentially, one that has a member flag_type*, and one that doesn't, and I'd like to save the 8 bytes of the flag_type* - I tried to define a second base class, with no template parameters and no member flag_type* but that didn't work. Any idea?

template <typename flag_type =void>
class Codec
{
  public:
    Codec(flag_type* flags =nullptr)
    : _mem(graph.mem()), _flags(flags)
  {}

  protected:
    membuf& _mem;
    flag_type* _flags;
};

Unable to process linked list deletion

I am trying to work with single linked list and came up with a problem while deleting tail from it. My inputs were 1 1 1 2 2 1 2 3 2 2 then nothing comes after it , for checking i have even put a cout statement , but it's not displaying.What's the problem here ? i am using geany in ubuntu. is there any problem with the compiler ? i have even tried after restarting and also have tried with gcc , so i dont think that there's a problem with compiler .

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

struct node{
    int data;
    node * link;
}*head=NULL,*tail=NULL ,*temp,*temp2;

 void AddElements();

 void DisplayElements();
 void DeleteElements();

int main()
{
int option;
cout<<"Enter your option:"<<endl;
cout<<"1.Add Elements"<<endl;
cout<<"2.Delete Elements"<<endl;
cout<<"3.View Elements"<<endl;
cout<<"4.Exit"<<endl;
cin>>option;
switch(option)
{
    case 1:AddElements();
            break;
    case 2:DeleteElements() ;
            break;
    default: exit(1);
return 0;
}
}
void DisplayElements()
 { temp=head;
     /*cout<<"head"<<head<<endl;
     cout<<"head->data"<<head->data<<endl;
     cout<<"head->link"<<head->link<<endl;*/
     while(temp!=NULL)
        {
     cout<<temp->data;cout<<"--->";
     temp=temp->link; 
        }cout<<"\n";
    main();
 }

void AddElements()
{
    temp=(struct node*)malloc(sizeof(node));
    if(head==NULL)
    {
        head=temp;
        cout<<"Enter first head"<<endl;
        cin>>temp->data;
        head->link=NULL;
        tail=head;
    }
    else if(head!=NULL && head->link==NULL)
    {
        int option2;
        cout<<"1.New Head"<<endl;
        cout<<"2.New Element ? "<<endl;
        cin>>option2;
        if(option2==1)
        {
        cout<<"Enter new head data"<<endl;
        cin>>temp->data;
        temp->link=head;tail=head;
        head=temp;
        }
        else if(option2==2)
        {
            cout<<"Enter new element data"<<endl;
            cin>>temp->data;
            temp->link=NULL;
            head->link=temp;tail=temp;
        }
    }
    else if(head!=NULL && head->link!=NULL)
    {
        int option2;
        cout<<"1.New Head"<<endl;
        cout<<"2.New Element ? "<<endl;
        cin>>option2;
        if(option2==1)
        {
        cout<<"Enter new head data"<<endl;
        cin>>temp->data;
        temp->link=head;
        head=temp;
        }
        else if(option2==2)
        {    
            temp=head;
            temp2=(struct node*)malloc(sizeof(node));
            while(temp->link!=NULL) 
    {
        temp=temp->link;
    }
    temp->link=temp2;
    tail=temp2;
            cout<<"Enter new element data"<<endl;
            cin>>tail->data;


        }
    }
    DisplayElements();
}

void DeleteElements()
{   temp = (struct node*)malloc(sizeof(node));
    int deleteoption;
    cout<<"1.delete head \n";
    cout<<"2.delete tail \n";
    cout<<"3.delete node with position \n";
    cin>>deleteoption;
    cout<<deleteoption;
    if(deleteoption==2)
    {  cout<<"bullshit";
        temp=head;
                    while(temp->link->link!=NULL);
                    {
                    temp=temp->link;        cout<<temp;

                    }
                    temp->link=NULL;
                    DisplayElements();}
}

Can this technique for creating a container of heterogenous functors be salvaged?

This blog post describes a technique for creating a container of heterogeneous pointers. The basic trick is to create a trivial base class (i.e. no explicit function declarations, no data members, nothing) and a templated derived class for storing std::function<> objects with arbitrary signatures, then make the container hold unique_ptrs to objects of the base class. The code is also available on GitHub.

I don't think this code can be made robust; std::function<> can be created from a lambda, which might include a capture, which might include a by-value copy of a nontrivial object whose destructor must be called. When the Func_t type is deleted by unique_ptr upon removal from the map, only its (trivial) destructor will be called, so the std::function<> objects never get properly deleted.

I've replaced the use-case code from the example on GitHub with a "non-trivial type" that is then captured by value inside a lambda and added to the container. In the code below, the parts copied from the example are noted in comments; everything else is mine. There's probably a simpler demonstration of the problem, but I'm struggling a bit to even get a valid compile out of this thing.

#include <map>
#include <memory>
#include <functional>
#include <typeindex>
#include <iostream>

// COPIED FROM http://ift.tt/1UbH5ke
namespace {

  // The base type that is stored in the collection.
  struct Func_t {};
  // The map that stores the callbacks.
  using callbacks_t = std::map<std::type_index, std::unique_ptr<Func_t>>;
  callbacks_t callbacks;

  // The derived type that represents a callback.
  template<typename ...A>
    struct Cb_t : public Func_t {
      using cb = std::function<void(A...)>;
      cb callback;
      Cb_t(cb p_callback) : callback(p_callback) {}
    };

  // Wrapper function to call the callback stored at the given index with the
  // passed argument.
  template<typename ...A>
    void call(std::type_index index, A&& ... args)
    {
      using func_t = Cb_t<A...>;
      using cb_t = std::function<void(A...)>;
      const Func_t& base = *callbacks[index];
      const cb_t& fun = static_cast<const func_t&>(base).callback;
      fun(std::forward<A>(args)...);
    }

} // end anonymous namespace

// END COPIED CODE

class NontrivialType
{
  public:
    NontrivialType(void)
    {
      std::cout << "NontrivialType{void}" << std::endl;
    }

    NontrivialType(const NontrivialType&)
    {
      std::cout << "NontrivialType{const NontrivialType&}" << std::endl;
    }

    NontrivialType(NontrivialType&&)
    {
      std::cout << "NontrivialType{NontrivialType&&}" << std::endl;
    }


    ~NontrivialType(void)
    {
      std::cout << "Calling the destructor for a NontrivialType!" << std::endl;
    }

    void printSomething(void) const
    {
      std::cout << "Calling NontrivialType::printSomething()!" << std::endl;
    }
};

// COPIED WITH MODIFICATIONS
int main()
{
  // Define our functions.
  using func1 = Cb_t<>;

  NontrivialType nt;
  std::unique_ptr<func1> f1 = std::make_unique<func1>(
      [nt](void)
      {
        nt.printSomething();
      }
  );

  // Add to the map.
  std::type_index index1(typeid(f1));
  callbacks.insert(callbacks_t::value_type(index1, std::move(f1)));

  // Call the callbacks.
  call(index1);

  return 0;
}

This produces the following output (using G++ 5.1 with no optimization):

NontrivialType{void}
NontrivialType{const NontrivialType&}
NontrivialType{NontrivialType&&}
NontrivialType{NontrivialType&&}
NontrivialType{const NontrivialType&}
Calling the destructor for a NontrivialType!
Calling the destructor for a NontrivialType!
Calling the destructor for a NontrivialType!
Calling NontrivialType::printSomething()!
Calling the destructor for a NontrivialType!

I count five constructor calls and four destructor calls. I think that indicates that my analysis is correct--the container cannot properly destroy the instance it owns.

Is this approach salvageable? When I add a virtual =default destructor to Func_t, I see a matching number of ctor/dtor calls:

NontrivialType{void}
NontrivialType{const NontrivialType&}
NontrivialType{NontrivialType&&}
NontrivialType{NontrivialType&&}
NontrivialType{const NontrivialType&}
Calling the destructor for a NontrivialType!
Calling the destructor for a NontrivialType!
Calling the destructor for a NontrivialType!
Calling NontrivialType::printSomething()!
Calling the destructor for a NontrivialType!
Calling the destructor for a NontrivialType!

... so I think this change might be sufficient. Is it?