mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I largely agree with you about modern C++ being too expert-friendly and not accessible enough to others. I think the core of the issue is some libraries focus more on features than on useability. It is easy, when you use template meta-programming or advanced generic programming techniques, to get caught up in "feature-building", and forget that the stuff needs to be relatively intuitive to use and predictable, well-specified, etc... And certainly, some Boost libraries tip a bit too far towards just being packed full of customizable behaviors and features, and at the end of the day, you can't use much of it because it lacks the most basic user-oriented qualities.

For Boost.Program-Option, I actually think it's pretty good (not perfect, of course). It is a small and simple library which was clearly designed with useability concerns in mind as the main objective of it. I think there are a few things that went a bit too far in it, making it a bit too complex in certain areas. You can argue that it is not used in an idiomatic way, and you might judge that as ugly, but that's a constant struggle in a multi-paradigm language like C++.

We've had at least a decade (90s to early 2000s) with a substantial group of people insisting on making C++ an "object-oriented language" and obey to practices similar to what you find in Java today (dating back to Simula). And they cried foul anytime they saw "ugly, complex, expert-only" template code, even …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This post is particularly enlightening ;)

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

but it's kind of ugly, no? ;)

And jrd::Menu menu("A) Option A;A|a;B) Option B;B|b;Q) Quit;Q|q"); is beautiful?

I guess one could use a few MACROs too:

#define JRD_MENU_IF(MENU, X, Y) jrd::Menu MENU; MENU.addOption(X, Y, [&]() 
#define JRD_MENU_ELSE_IF(X, Y) ).addOption(X, Y, [&]() 
#define JRD_MENU_END_IF )

And then have the menu creation be like this:

    JRD_MENU_IF(menu,  "A) Option A", "A|a") {
        std::cout << "You chose option A" << std::endl;
    } JRD_MENU_ELSE_IF("B) Option B", "B|b") {
        std::cout << "You chose option B" << std::endl;
    } JRD_MENU_ELSE_IF("Q) Quit",     "Q|q") {
        std::cout << "You chose to quit" << std::endl;
        done = true;
    } JRD_MENU_END_IF;

But I guess that won't satisfy you esthetic requirements either. ;)

Joking aside, this pattern of creating the object by several calls like the addOption() function above is a bit weird-looking, but it is very useful. This pattern is predominant in libraries like Boost.Program-Options and Boost.Parameter. I also use it often for creating objects that contain many parameters and can have many options and variations, especially manufacturing objects from a class template with many optional arguments simply by returning an object of a different type at every step. For example, this version giving a static number of menu options with templated callback functors:

template <typename... Functors>
class Menu final {
public:
    // ...

    template <typename NewFunctor>
    Menu< Functors... , NewFunctor >
      addOption(const std::string& aPrompt,
                const std::string& aAlternativeMatches,
                NewFunctor aCallback) const;

    // ...
private:
    std::array< std::string, sizeof...(Functors) > prompts;
    std::array< std::vector<std::string>, sizeof...(Functors) > matches; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here is an alternative for the Menu class that might be a bit more convenient (and I guess it might qualify as a Builder pattern, not sure as I, like deceptikon, don't care too much about these things).

// menu.h
#ifndef MENU_H
#define MENU_H

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

namespace jrd {
    class Menu final {
    public:
        Menu& addOption(const std::string& aPrompt,
                        const std::string& aAlternativeMatches,
                        std::function< void() > aCallback);
        bool execute() const;
    private:
        struct Item {
            template <typename ForwardIter>
            Item(const std::string& aPrompt,
                 std::function< void() > aCallback,
                 ForwardIter first, ForwardIter last)
                : alt(first,last), prompt(aPrompt), callback(aCallback)
            { }

            std::vector<std::string> alt;
            std::string prompt;
            std::function< void() > callback;
        };

        std::vector<Item> _items;
    };
}

#endif

// menu.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <regex>
#include <string>
#include <vector>
#include "menu.h"

namespace jrd {
    /*
        @description:
            Creates a menu-item from a prompt string, a formatted set of 
            alternative matches, and callback functor.

            The alternative matches string shall be in the following format:

                <match1>|<match2>...

            The prompt may not be an empty field, but the alternatives may be empty.
    */
    Menu& Menu::addOption(const std::string& aPrompt,
                          const std::string& aAlternativeMatches,
                          std::function< void() > aCallback)
    {
        std::sregex_token_iterator alt_first(aAlternativeMatches.begin(), 
                                             aAlternativeMatches.end(), 
                                             std::regex("[|]"), -1);
        std::sregex_token_iterator alt_last;
        _items.push_back(Item(aPrompt, aCallback, alt_first, alt_last));
        return *this;
    }

    /*
        @description:
            Displays the prompts for a collection of menu items and 
            executes the appropriate callback functor.

        @returns: True if a matching selection was detected, false otherwise.
    */
    bool Menu::execute() const
    {
        // Display the prompts
        for (auto x : _items)
            std::cout << x.prompt << '\n';

        std::cout << "> "; …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That's a neat code snippet!

Wouldn't it be nicer if the selection string was set to the given menu item (by name or ordinal) such that you would need to rely on the alternative match-strings for the switch case? In your test case, the alternatives are always an upper- or lower-case letter. What if you wanted alternatives like "quit" or "exit" for the quit option? That would result in two case entries (or two else-if blocks in this case).

You could have this selection-test loop:

        for (auto x : _items) {
            // Check all of the alternatives for a matching prefix
            if (std::any_of(std::begin(x.alt), std::end(x.alt), prefixed)) {
                selection = x.prompt;
                return true;
            }
        }

Then, you can do the test for selection as:

    if (!rc)
        std::cout << "Invalid selection\n";
    else {
        if( selection == "A) Option A" ) 
            std::cout << "You chose option A\n";
        else if( selection == "B) Option B" )
            std::cout << "You chose option B\n";
        else if( selection == "Q) Quit" ) {
            std::cout << "You chose to quit\n";
            done = 1;
        };
    }

I think it is desirable to make the content of selection (or whatever else identifies the option selected) have a unique value for each option, to make it more convenient and predictable for the user of the Menu class. A numeric value for the selection would also do nicely:

std::ptrdiff_t Menu::operator()() const
{
    // Display the prompts
    for (auto x : _items)
        std::cout << x.prompt << '\n'; …
tux4life commented: Nice catch. +13
deceptikon commented: I like that. +12
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

< off topic >

Are you saying that when I make a personal decision whether or not to use a product I am being stupid?

Absolutely not. I don't know where you got that idea from, being fearful and rash, maybe, and later being caught in a "stupid new-age trend", maybe, we'll see. My point is that these kinds of labels serve a very devious purpose. People naturally ascribe credibility to a label, e.g., if they see "FDA approved" on something, they can rightfully assume that the product has been thoroughly tested and is safe for consumption (I'm not saying the FDA is the most trustworthy thing, this is just an example). The problem with a label that simply classifies a product (e.g., "GMO-free" or "organic") is that there is absolutely nothing about that classification that guarantees quality or any amount of testing, or anything else beyond the (usually) broad classification criteria. But, people will nonetheless get the same "quality assured" feeling about products baring that label. And then, it is merely a matter of (1) finding some anecdotal evidence of bad GMO products, (2) finding some anecdotal evidence of good non-GMO products, and/or (3) driving a publicity / whisper campaign for non-GMO products, and it will be enough to make the broad-brush association in people's minds that GMO == bad. And then, you get a bunch of people who fervently and proudly proclaim they only eat non-GMO products. And at this point, the truth no longer matters, …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Unavailable for C++/CLI

C++/CLI and C++ are not the same thing. I assumed you were talking about C++. So, for C++/CLI, the only option is VS2012.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Wouldn't everyone be allergic to dust because there is always dust everywhere?

Well, I'm not sure that more exposition necessarily means more chance of being allergic to it, otherwise we'd all be allergic to milk by the time we're 5 years old.

I'm allergic to house dust too. Whenever I do any vaccuum cleaning or stir up some dusty things (like looking from something in some old boxes or closet), I quickly get a stuffy nose, watery eyes and sneeze repeatedly for a couple of hours. Really annoying. Keeping the house clean means being afflicted by this every other day, but not stirring up any dust means leaving the dust on the ground / tables / shelves / everywhere. Damned if I do, damned if I don't.

what are you guys allergic to?

I've been to the hospital once as a teenager with a moderate case of allergy (not acute or life-threatning), but we could never pin-point what it was that caused it, and I never had the same thing since, but it was definitely a allergic reaction. So, I guess I'm allergic to something, I just don't know what.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Before i was using Borland Delphi, but i would like to switch to something else like VS.

If you are familiar with Borland Delphi, it might be easiest to use Borland C++Builder. The problem is that it is not available for free (beyond a 30 day trial). It is a decent product, very much like Delphi (and the compiler shares the same back-end as the Delphi compiler, which means libraries can natively link between them, e.g., the VCL (GUI library) used in C++Builder is in fact the Delphi one (with C++ headers)).

i have tryed usind VS2010 but because IntelliSense is disabled for C++

Intellisense is certainly not disabled for C++, at least, not by default (and it's actually kind of difficult to disable completely, even if you want to). However, Intellisense will require that you have the code setup properly as a "project" with all the relevant cpp file added to it, all the needed include-paths set, and so on. If you are just editing source files without being within a project / solution, Intellisense cannot really do much, and it doesn't.

Can somebody please suggest a good dev. environment for c++ to run on Windows?

A pretty good, easy and fast IDE for Windows would be CodeBlocks or Qt Creator. In both cases, you would normally use the GCC compiler (under MinGW), which is pretty much the best (free) compiler overall. You can get CodeBlocks that includes MinGW here, and …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should make the timeFunction function template take a templated parameter as the functor (callable type). Simply put, you could do this:

template <typename F, typename T>
clock_t timeFuction(F f, T v)
{
    auto start = clock();
    f(v);
    return clock() - start;
}

Or, more in the style of C++11, you could use variadic templates to have an even more generic implementation:

template <typename F, typename T...>
clock_t timeFuction(F f, T... args)  // take a functor and a parameter pack (variadic).
{
    auto start = clock();
    f( std::forward<T>(args)... );  // un-pack parameters, forward them to the functor.
    return clock() - start;
}

As for calling the timeFunction function using a function template, you need to do as firstPerson showed (i.e., fully specify the template arguments). A useful trick is to wrap the function call into a callable function object type with a templated call-operator:

struct StandardDeviationCaller {
  template <typename T>
  double operator()(T v) const {
    return standardDeviation(v);
  };
};

// then, you can call timeFunction as follows:
cout << timeFuction(StandardDeviationCaller(), v) << endl;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I would find Inverted matrix A ... (A)-1

Like you would in any other language that don't have built-in methods to do so. There are many algorithms for this purpose, each with different properties (efficiency, stability, amplification of round-off errors, etc.) and for different kinds of matrices (general, normal, well-conditioned / ill-conditioned, symmetric, positive-/negative-definite, indefinite, rank-deficient (pseudo-inverse methods), etc.). By and large, however, inverting a matrix is rarely needed, so most methods are essentially methods to solve a system of linear equations (Ax = b), and by making the right-hand side equal to the identity matrix, you find the inverse (if that is really what you need). So, what you need to look for are methods to solve systems of linear equations. These include, but not limited to, Gaussian elimination (or its more sophisticated versions, the LU-decomposition or Cholesky decomposition (symmetric positive-definite)), QR decomposition (and variations like QL, RQ, and RRQR), Singular-value decomposition, etc... and the list goes on. There are entire books written on the subject, for example Golub and van Loan (this is pretty much the bible of matrix numerical methods).

There are also libraries that can do that for you, like Eigen, or my own, or the older classic (C) libraries like LAPACK or GSL.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

< off topic >

As for GM foods, my biggest problem is that the companies that make them are blocking legislation (and lying and breaking the law while doing it) that would require nutrition/content labels to identify products with GM content. Whether they cause cancer or other problems (or not), I want to know so I can decide for myself whether to buy or not.

My main objection to GM foods is the patenting of crops and all the vendor-lock-in crap that ensues (making it illegal to collect seeds to plant them the next season, because the companies want the farmer to come back the next season to buy a new supply of seeds from them). In terms of health effects, there are many positive effects like less chemical products used to grow them, or their increased content of nutrients in general (i.e., most GMOs are engineered to grow healthier (stronger), which usually results in higher content of vitamins and other nutrients). And all serious studies on the effects of individual health problems they might cause turned up no correlation or negative correlation, and only very dubious studies exist that say the opposite, and not anywhere near being conclusive (thus, the "pseudo-scientist with an agenda" label). Environmentally, there are some concerns in terms of biodiversity, and also the ever-present "playing God" argument, but this is mostly a problem because GE is a much faster way of doing what man has always been doing since the dawn of time, …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

what is the best way to pass these variables as a group while using classes?

By make the function a member function of the class. In the case of a function like:

void view(Shoes *Shoe);

The easiest way to do this in object-oriented code, is just as so:

class Shoes{
public:

    void view();

private:
    char Name[20]
    int Number;
    double ShoeSize;
};

And when you have an object like:

Shoes my_shoe;

You can simply call the member function like this:

my_shoe.view();

And because view() is a member function, a pointer to the object my_shoe is implicitely passed to the function. Inside the implementation of the view() function, you can access the data members either directly by name, or using the this pointer which is always pointing to the object on which the function was called. In other words, you can define the view() function like this:

void Shoes::view() {
  std::cout << Number << std::endl;
  std::cout << this->ShoeSize << std::endl;
};

In the above, when calling view() with my_shoe.view(), the variable Number refers to my_shoe.Number, and the variable this->ShoeSize equivalently refers to my_shoe.ShoeSize. This is really the whole point of having this so-called object-oriented syntax in C++, having the implicit passing of and reference to an instance of the class within member functions.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here are a few great lies:

"God exists." (every power-hungry "religious" leader)

"Lowering taxes on the rich stimulates the economy." (every rich guy who wants a tax cut)

"Genetically engineered foods cause cancer." (pseudo-scientists with an agenda)

"Vaccins cause autism." (convicted fraudster, Andrew Wakefield)

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yo! I think it's chicken since God created first the mother and father of all animals that we have right now. lol hope does it make sense.

Yeah it makes as much sense as to believe that a rabbit is really popped into existence when the magician pulls it out of his hat.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You can use yum as follows from a terminal:

$ sudo yum install some_package

Or, you can launch the software center from the main menu and search for the package you want.

and, of course, you need internet access.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I second that. Definitely, put that work experience on your CV. Not only does it show that you have not been sitting on behind for five years, it also shows a number of qualities like being hard working, being able to show up on time every day (at least, if your factory is anything like the wood-mill I used to work at), being consistent (the same job for 5 years), and so on.. Being a good employee has a lot in common even between wildly different occupations (programming vs. factory-floor worker, or whatever else). Work experiences should be taken out of your CV only if they are so old that they are not relevant anymore or if there is something really bad about it (very short employment, getting fired for a bad reason (as opposed to just "re-organization"), etc.).

james6754 commented: Thanks, really constructive comments. +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The reason is because you should not re-seed the random number generator each time. Just seed it with srand((unsigned)time(0)); once in the entire application, i.e., at the start of the main() function. That will fix the problem.

BTW, to print a fixed number of digits with leading zeros, you can just use the following:

cout << "NNNNNN: " << setfill('0') << setw(6) << number << endl;
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The compiler error in <memory> is just where the error ends up popping up, it is not the root cause of the error. The compiler error should have a number of additional lines telling you where the error originates from. Usually, in comes in the form of one line saying "error in function operator= ..." plus a number of lines saying something like "instantiated from '...'", "instantiated from '...'", and so on. Some of these lines should point to the specific lines in your code from which the error originates.

If not, simply comment out the lines of code, re-compile, uncomment, re-compile, and so on until you pin-point what line causes the error.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As far as I know, this cannot be done. From a practical point of view, compilers would be required to track in what namespace a particular function a function pointer point to was defined, and I don't think any compiler really does that because there is no real purpose for it, and also because one function can actually belong to a number of different namespaces (yes, that's what a "using somewhere::something;" statement does). From a coding point of view, there is no real value in a feature that seemingly restricts something, when in reality, it imposes no restriction whatsoever. Nothing prevents users of your class from declaring (or "using") their functions in that namespace. I could easily have this:

namespace my_code {

void my_function();

};

namespace StateAction {

using my_code::my_function;

};

// And now, you can do:
some_state.addAction(&StateAction::my_function);  // should this be allowed or not?

In any case, there is no way to forbid users from creating functions in that namespace, and thus, the restriction that function pointers must point to functions in that namespace is a very weak restriction.

An alternative might be to require that instead of a function pointer, you must give a polymorphic object from a class derived from some simple base class for all state-actions. Another alternative might be to make the addAction function a private function and then befriend only specific classes or functions, allowing them to be the only ones capable of providing a function pointer for that state class.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

how intelligent are you in dealing with those whose first language isn't English?

I have a bit of experience with that (both here and in real life), and English isn't my first language. I was lucky enough to be raised bilingual (French and Swedish), and later learned English (and use it almost exclusively every day now), and travelled around a bit and learned German (functional), Spanish (basic), Finnish (very basic), and a few things in other peripheral languages. And btw, as a result of that, I can also do accents pretty well (and suppress my own native accent easily). But one thing I can't suppress very well is my obnoxious tendency to use long and complicated sentences with lots of fancy words (that comes from French, my most native language). So, I've been around plenty on both sides of this issue, and I think I've learned to deal with that quite well.

The first thing is that it takes a bit of imagination / perspicacity to be able to interpolate, extrapolate, read-between-the-lines, and make word associations. Knowing different languages helps a lot for that because you can understand certain uses / meaning of words that would seem otherwise very odd in English but that are found in other languages (i.e., people translating literally from their native language with odd results in English). Same goes for sentence structures (e.g., speaking English with sentence structures borrowed from some other language (the speaker's native language). The same goes, of course, the …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Try splitting it up into multiple lines to see exactly where the error comes from. For instance, try this:

for(;it!=v.end();it++) {
    std::shared_ptr< Cloneable > pc = (*it)->clone();
    std::shared_ptr< Assembly > pa = std::static_pointer_cast< Assembly >(std::move(pc));
    out.push_back(std::move(pa));
}

This should tell you what step actually causes the error, the above code should, in essence, be equivalent to your original code. Also, since the error seems to come from some move operation (since the error in the <memory> header is within a move function), try to remove the std::move() calls from the above code and that will help you determine if the error comes from the move involved in the pointer-cast or when pushing the pointer to the vector.

So, report back when you tried the above code, and what happens if you remove one or the other std::move() calls.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Shouldn't that line be the following instead:

out.push_back( std::static_pointer_cast<Assembly>((*it)->clone()) );

Otherwise, it doesn't make much sense.

Also, you could define a free function for cloning that will make that syntax easier. For example, this:

template <typename CloneableType>
std::shared_ptr< CloneableType > clone(const std::shared_ptr< CloneableType >& p) {
  return std::static_pointer_cast< CloneableType >(p->clone());
};

which will make the above line much simpler (by deduction of the template argument):

out.push_back( clone(*it) );
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This last example is much more realistic to my actual code, is this not allowed?

This is certainly allowed, at least, it should be in a bug-free standard-compliant C++11-supporting compiler (VS2010 is neither of these things). The version with the dynamic_pointer_cast compiles fine on GCC 4.5.3, GCC 4.6.3 and GCC 4.7.3 (and probably everything in between and after, but I just have those three on my computer).

There is no reason for that dynamic_pointer_cast to fail to compile, or the push_back to the vector for that matter. Whatever is causing this error is not your responsibility, it is that of Microsoft developers. Either file a bug report or see if they fixed it in VS2012 (november update).

Other than that, you might have to use a workaround for the dynamic_pointer_cast function, it's not like it's very difficult to implement anyways:

template <typename T, typename U>
std::shared_ptr<T> dynamic_pointer_cast(const std::shared_ptr<U>& rhs) {
  T* tmp_ptr = dynamic_cast< T* >(rhs.get());
  if(tmp_ptr)
    return std::shared_ptr<T>(rhs, tmp_ptr);
  else
    return std::shared_ptr<T>();
};

template <typename T, typename U>
std::shared_ptr<T> static_pointer_cast(const std::shared_ptr<U>& rhs) {
  return std::shared_ptr<T>(rhs, static_cast< T* >(rhs.get()));
};

The error you pointed out is weird because it seems to come from the move-assignment operator of the VS2010 implementation of std::shared_ptr, however, that move-assignment operator is never used during the whole std::dynamic_pointer_cast implementation in VS2010's <memory> header. So, I guess it might occur within the vector push_back function, or something like that. Anyways, I have learned by experience not to waste time crying about all …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I have dealt with Dell crapware before, especially their incredibly stupidly written restoring program. Before, I had a dual boot system with the Windows bootloader as the primary bootloader (chain-loading grub from the Linux partition), and the Dell crapware did some kind of automatic restore point thing that also involved flashing a fresh version of the Windows bootloader. That had the effect of seemingly making my Linux installation disappear and I couldn't boot to it anymore because of the lost settings in the Windows bootloader. I had to remove all that Dell crapware (which is always a good idea regardless of whether you have a dual boot or not) and reset my bootloader to be able to find my Linux installation again and boot to it. So, I'm just saying that in case that is what happened to you. If not, and you actually restored the system and thus deleting your Linux installation, then there really isn't much you can if you don't have a backup.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are casting operators for shared_ptr called static_pointer_cast and dynamic_pointer_cast. In other words, if you have this code for raw pointers:

base* pb;
derived* pd = static_cast< derived* >(pb);
derived* pd = dynamic_cast< derived* >(pb);

then, the equivalent with shared_ptr is the following:

shared_ptr< base > pb;
shared_ptr< derived > pd = static_pointer_cast< derived >(pb);
shared_ptr< derived > pd = dynamic_pointer_cast< derived >(pb);

The difference between static_cast and dynamic_cast is that dynamic_cast will to a run-time type check to make sure that the base-class pointer actually does indeed point to an instance of the derived class. In other words, if you can make sure, by other means, that the pointer does indeed point to an instance of the derived class, then you can use static_pointer_cast, but otherwise, it is safer to use dynamic_pointer_cast.

BTW, in your example, your base class should have a virtual destructor, otherwise the destruction is not going to be done correctly. You need to have:

class base {
public:
    virtual shared_ptr<base> clone() = 0;  // your clone() function should be virtual too.

    virtual ~base() { };  // virtual destructor.
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

"It is two times more absorbant than the leading competition."

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I just saw Django Unchained during the holidays. Absolutely amazing movie. Arguably the best of all Tarantino movies (and that says a lot). The only critique that I can make is about that one Kill Bill style gun fight with over-the-top blood splaters, I thought it was a bit out of place given that there isn't much of that elsewhere in the movie, and so, it could have been toned down. But everything else was brilliant. And the part with the KKK baffoons was just hilarious.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Make sure to get the most up-to-date version. CodeBlocks just came out with version 12.11 (late november 2012) which includes the compiler GCC version 4.7.1 (the MinGW TDM-GCC distribution) which should work for Windows 8 (at least, according to the website). Other than that, you'd have to try the Clang compiler by following these instructions. Any IDE (like CodeBlocks, or even Visual Studio) can be configured use the Clang compiler instead (I'm sure you can find instruction for that on the web too).

Other than that, there aren't really too many options that are free.

In theory, anything that works on Windows 7 should also work on Windows 8, as far as I know. So, if you say that you "keep getting build errors", it might not be because the compiler is not working but rather that your code has errors (or things that are now errors in the newer version of the compiler). Make sure you test it with a very simple program:

#include <iostream>

int main() {
  std::cout << "Hello World!" << std::endl;
  return 0;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

With the way you describe it now, it seems that it might be more appropriate to use a general container of chars instead of a stream. Streams are mostly intended to be used for sequential operations, not so much for random-access operations (or somewhat random-access). If you are not going to use some of the nice features of the streams, like formatted input-outputs and the buffering, there is no need to use it, and it will just be a handicap. So, it might be easier to just dump the content of the stream into vector of chars, as so:

std::vector<char> charVector(std::istream_iterator<char>(inStream), std::istream_iterator<char>());

And then, you can just use iterator ranges and STL algorithms to do you tokenizing work.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

peek() wouldn't allow multi-character backtracking (no?),

No, the peek function allows you to see the next character without actually extracting it from the stream. What you have described as your tokenizing tasks can easily be implemented using that. For example, the code from your last post could be implemented as follows:

Token WordState::nextToken(std::istream& s, int c, Tokenizer& t) {
    string sval;
    while( s && wordChar( s.peek() ) )
        sval.push_back( char(s.get()) );
    return Token(Token::TT_WORD, sval, 0);
};

seeking would, can it be done relative to current poristion?

Yes, you can do it as follows:

s.seekg(-5, std::ios_base::cur);  // move back by 5 chars from current position.
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

did I miss something, is there similar funtionality in the standard library?

Well, there is a peek() function. Also, you can always do seeking operations to move the position of the get pointer on the stream. And you should really check out the Boost.Tokenizer library, not to mention other important parser libraries like Boost.Regex and Boost.Spirit.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

With this example the issue of scope is still relevant, when the passed reference goes out of scope it will be destructed, even though there is now a shared_ptr to it correct?

Yes, that's true. That's the reason why I mentioned the semantics issue in my previous post by saying:

When you give a non-const reference to a constructor, there is a conventional understanding that the reference must remain valid for as long as the object exists, and this is what allows it to be semantically correct to do what you are trying to do. Additionally, you should document that fact in the (doxygen) comments.

because any acute reader of your question would have pointed that problem out right away, and I was defusing that by pointing out that this is a case of borrowed ownership and is thus OK from a coding practices point of view.

I think you need to wrap your head around this concept of value-semantics and automatic storage (or scope-bound objects, or deterministic life-times) that is central to coding practices in C++. This is very different from coding practices in pure OOP languages. In Java/C# and others, objects are all created in freestore and interconnected as an object graph, and a garbage collector works in the background to clean up anything that has become disconnected from the rest (i.e., not needed anymore). In C++, the primary mechanism for creating objects is having them come into scope (in the call stack) and …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Ahh.. the Big Lebowski, that's definitely one of my all time favorites. The Dude abides.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That is a common situation and there are two common solutions to it. But first, it is important to mention to semantics of this. When you give a non-const reference to a constructor, there is a conventional understanding that the reference must remain valid for as long as the object exists, and this is what allows it to be semantically correct to do what you are trying to do. Additionally, you should document that fact in the (doxygen) comments.

Now for the solution. The problem is essentially that the object needs to hold a pointer to an object which it may or may not have ownership of (ownership == responsibility to delete it) (see this tutorial for a more thorough explanation of ownership relations in C++). This duality implies the need for a flag to tell, upon construction, whether the object has ownership or not of the pointee. And thus, a simple solution arises:

class PushbackReader {
  protected:
    std::istream* myreader;
    bool has_myreader_ownership;
    //other stuff for pushback buffer
  public:
    explicit PushbackReader(const std::string& filename) : 
                            myreader( new std::ifstream( filename.c_str() ) ),
                            has_myreader_ownership(true) {
      /* rest */
    };
    explicit PushbackReader(std::istream& reader) : 
                            myreader(&reader),
                            has_myreader_ownership(false) {
      /*rest*/
    };

    ~PushbackReader() {
      if(has_myreader_ownership)
        delete myreader;
    };

    // the class must be made non-copyable (C++11):
    PushbackReader(const PushbackReader&) = delete;
    PushbackReader& operator=(const PushbackReader&) = delete;

    // but you can still make it moveable (C++11):
    PushbackReader(PushbackReader&& rhs) {
      if(rhs.has_myreader_ownership) {  // either create a new myreader:
        myreader = new std::ifstream( 
          std::move( static_cast< std::ifstream& >( *(rhs.myreader) ) …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

"It's not you.. it's me.."

"Don't take it personally, but I think you're a <insert insult> ."

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, on my computer, the vimrc file is in the /etc/vim/ directory, and if I do the ls -l vim* command, I get the same result. Try this:

$ cat /etc/vim/vimrc

N.B.: To find a file, it is easier to use commands like these:

/etc$ locate vimrc
/etc/vim/vimrc
/etc/vim/vimrc.tiny

/etc$ find . | grep vim
./vim
./vim/vimrc
./vim/vimrc.tiny
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

<off topic>

contribute towards my success in getting to Harvard

Going to an Ivy league school doesn't guaranteed you a job or work.

After you graduate you will start square one. The only edge you have is because of the school you attended. Other than that you have to start from scratch. Plus you have to pay off your student loan.

I wouldn't wait until graduation. By that time, it's too late, it doesn't matter what school you went too. Also, people coming out of Ivy league colleges have the well-deserved reputation of either having rich parents (and thus, guaranteed opportunities after graduation), or having become lazy from years of attending a privileged school that is designed to let rich kids make their parents proud with a shiny degree (and employers are very much aware of that). The reputation of the school helps only to some extent: coming from an unknown average university can be a handicap, but flashy degrees aren't enough to impress any reasonably smart employer (only stupid ones).

The aim should be that by the time you graduate, someone can ask you "why should I hire you?" and you can talk for 15min without ever mentioning where you graduated from or what your grades were. In other words, internships, projects, theses, etc., whatever puts you ahead. The diploma, the name of the university, or your GPA, are only decorations on your CV (but necessary).

</off topic>

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Can C++11's Mutexes be used for Inter-Process Communication? In other words, can it be used for shared memory and signalling an event?

Yes. But the more important question is: Should mutexes be used for that? No. To use a mutex (or pair of mutexes) for this purpose, one could come up with a number of schemes. In any case, the scheme will be based on having one thread locking the mutex while the other waits to get a lock on it, and the unlock-lock transition would be the "signal" event. There are a number of problems with that. First, the way that a thread waits to get a lock on a mutex is generally implemented (this is OS dependent) in a loop like this:

while( check_if_mutex_is_available() )
  yield_thread_scheduled_time();

which is generally performed at the kernel level. This is rather inefficient, mostly because a mutex is not meant to be used that way. A mutex is meant to prevent two mutually exclusive codes from being executed at the same time, not as an event-based synchronization device.

The second problem are all the edge cases when the threads are running fast and are racing each other. You can have misses when thread A unlocks and re-locks the mutex without thread B noticing it (because it didn't get scheduled in between). You can have inefficiencies if thread B needlessly blocks thread A once it obtained a lock on the mutex. If you implement it with a pair of mutexes, …

rubberman commented: Great explanation of CVs Mike! +11
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Happy New Year! Wish you all the best!

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I will be honest, he is very creative... but i hate his films because they bore me. His best film is probably alice in wonderland...

I don't find Tim Burton to be very creative lately. In my book, he made a few great movies: Edward Scissorhands, Sleepy Hollow, and Sweeney Todd. I think you might pick another movie or two that were good. But most of the last movies in the streak of Tim Burton milking the "Johnny Depp" cash-cow by putting him in funny costume and having him prance around weren't very interesting, or creative.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

To clarify, Scott Meyer's explanation is as follows:

Because the default version of operator new is a general-purpose allocator, it must be prepared to allocate blocks of any size. Similarly, the default version of operator delete must be prepared to deallocate blocks of whatever size operator new allocated. For operator delete to know how much memory to deallocate, it must have some way of knowing how much memory operator new allocated in the first place. A common way for operator new to tell operator delete how much memory it allocated is by prepending to the memory it returns some additional data that specifies the size of the allocated block.

The broader point is essentially that the heap structure that does all the bookkeeping related to the dynamic allocations can have significant overhead with respect to the memory blocks that it needs to manage. In simple terms, the heap is essentially a data structure that makes an index of all the free space available for allocation. Whenever you allocate and deallocate memory (with new and delete), the heap must be updated and entries are added or removed. So, you must expect a certain amount of overhead in memory and time needed for all that bookkeeping. So, be economical with dynamic allocations, and prefer other strategies when allocating a large amount of small objects (such as a memory pool).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Definitely, go for Boost.Python. It can effectively replace a "plugin system" by just making you C++ code into Python classes and functions. It is seemless, with only a few quirks here and there. Essentially, you can make your C++ class hierarchy be reflected into Python packages, have Python classes derive from them, and then use those derived-class instances from the C++ code. This is basically how it's done.

I prefer to just use Boost.Python as the plugin system, because 99% of what you need to do to create a plugin system is already done by Boost.Python as it exports the classes into Python classes, and the other 1% can easily be done as additional exports. Then, you use Python scripts as the high-level "glue code", with the additional benefit that you can seemlessly mix Python classes, Python classes derived from C++ base classes, and wrapped C++ classes. It is easier to do that work in the Python scripts (e.g., feed an object of a Python class derived from a C++ base class to a wrapped C++ class/function, and the wrapped C++ code won't even see the difference), because loading Python packages and code from C++ code is a lot harder (but possible too).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I'm certain you didn't pay $10,000 USD to get it legally.

I've obtained several versions of Visual Studio "Ultimate" (or Professional) (2005, 2008, and 2010) through eAcademy and other programs that deliver free software products to university students. Most universities have such agreements (after all, it makes sense for companies to give out their software for free to students, because they'll be advocating the use of those products later when they start working).

tux4life commented: Exactly. +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Visual Studio 2012 (November update).

Way ahead of GCC (the other major contender) in C++11 conformance - Microsoft has implemented almost everything in the standard.

clang 3.2 with its libc++ is on par with VS 2012; and it is somewhat more mature and stable in comparison. But it has to be built from sources; and installing it is not an easy task for everyone.

Whoa... With all due respect, vijayan121, I think you are quite a ways off here. In any case, the question is not about which is the best C++11 compiler.

Overall, if any compiler is way ahead of the competition, it is the Intel compiler (ICC), it leaves the other compilers in a trail of dust with respect to code optimization and compiling speed. And the main contender to ICC is GCC, and then, a bit further behind is Clang. While the Microsoft compiler is not really competing (by their own admission), their aim is just to try and make MSVC usable, which it barely is (the "professional" alternative is to use Visual Studio IDE with the Intel compiler).

@deceptikon: The November update of MSVC11 did add support for, most notably: variadic templates, initializer-lists, and delegating constructors. This does move MSVC up to a respectable amount of support for C++11 features, about on par with the Intel compiler (in terms of C++11 feature support only). Of course, Intel is ahead on concurrency, as expected. MSVC is ahead of GCC on concurrency, which is a big …

tux4life commented: Very clear and thorough! +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you read the community rules, you will see the following:

  • Do post in full-sentence English
  • Do use clear and relevant titles for new articles
  • Do not write in all uppercase or use "leet", "txt" or "chatroom" speak
  • Do read the forum description to ensure it is is relevant for your posting
  • Do provide evidence of having done some work yourself if posting questions from school or work assignments

These are all the rules you have broken in this thread. Please consider them in the future.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Technically, yes, you could make the derived class copy-assignable. The intent of the "non-copyable" idiom is to make the class non-copyable for users of the class. As an author of a derived class, you can still make it copyable by making a public copy-constructor and a copy-assignment operator. But you cannot do so by using the copy-constructor or copy-assignment operator of the base class (since they are private and undefined), so it means that you need to write your own code to do the copy (assuming that all data members are accessible, i.e., they are private). So, it still makes sense, because you cannot inadvertently make write code that will copy the non-copyable base-class.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Moving from Java to C++, the main thing to understand well is the distinction between Java's reference-semantics and C++'s value-semantics. Simply put, everything in Java is a reference (or placeholder, or pointer) for an object (managed by the garbage collector). In C++, everything is a value (or object, or variable) (e.g., int), which could be an address-value (pointer) (e.g., int*) or a alias for a value (reference) (e.g., int&).

Now, to the problem in your code:

class Cloneable {
  public:  // (I added 'public:', otherwise your clone() function is private).
    virtual Cloneable clone()=0;
}

There are two things to notice. First, the presence of a pure virtual function makes the class abstract, which means, in C++, that it cannot be instantiated (i.e., you cannot create an object of that class). Second, the member function clone() returns an object of type Cloneable, that is, not a reference, not a placeholder nor a pointer, but an actual object (by value). Do you see a contradiction? Such an object cannot be created because Cloneable is abstract.

Basically, to do what you want to do you have to return things by pointer:

class Cloneable{
  public:
    virtual Cloneable* clone() = 0;  // notice Cloneable* (pointer)
}

However, using a raw pointer is not really recommended for a factory function (or clone function). It is preferrable to use a smart-pointer such as std::shared_ptr or std::unique_ptr. And because std::unique_ptr is moveable into a std::shared_ptr, that is the …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

But any moderator can come around, unsolve the thread, post to it, and re-solve it.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

No, you can still post on a solved thread.