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

I quick google search reveals that counted_ptr is a pre-historic version of shared_ptr. Unless you are using a specific (old) library that requires the use of counted_ptr, I must say that you should prefer using the standard std::shared_ptr pointer, or it's equivalent in Boost boost::shared_ptr.

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

The problem has nothing to do with the typedef or type of your function pointer. The type of the pointer returned by GetProcAddress is void*, and then you cast it to what it is supposed to be. In other words, the information about what kind of function is in the DLL is lost, and thus, there is no way to verify it. It is entirely your responsibility to make sure that the function-pointer type to which you cast it is exactly the same as the function exported by the DLL (parameters and return type must match). If you get it wrong, you will get a crash (or other corruption of some kind), not a NULL pointer.

If you are getting a NULL pointer out of the GetProcAddress call, it means that functions with that name could not be found in the DLL.

You can use a utility like dumpbin or dependency walker to inspect the list of exported symbols from the DLL. Also, of course, I don't need to remind you that the DLL functions must be declared with extern "C", see explanation.

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

Non deterministic methods: present many choice and one must choose the suitable one among others(e.g. Genetic algorithms), in such case we talk about a pseudo-algorithm.

We generally call that a probabilistic method, or probabilistic algorithms. This is quite different from the concepts of deterministic / non-deterministic Turing machines. A non-deterministic Turing machine does not "choose the suitable one" from the many choices, but rather, it simultaneously follows them all (that's the only practical way to look at it). They are called non-deterministic because the result (i.e., the successful path) is not predictable from looking at its previous "states" because it followed all possible next states.

When you consider probabilistic methods, they are essentially deterministic algorithms where the state is a belief-state (or probability distribution) and the transitions predictable ("deterministic") as long as we are satisfied with a belief-state, as opposed to an exact knowledge of the state. For example, we can say that a probablistic algorithm will solve a problem is a certain amount of time because at that point we can predict the state to be in the "solved" regime within a certain degree of confidence (e.g., 99% chance of having succeeded at time point). Genetic algorithms fall under that category, obviously.

But that said, I find much more promising avenues in the field of probabilistic methods than in the "wild-goose" pursuit of non-deterministic machines.

NP problems are problems that can be solved by a non-deterministic Turing machine in polynomial time.

That sounds more promising …

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

Printing in Unix/Linux would usually go through low-level utilities such as lpr and lpq. You don't have to make a postscript file if you just want to print a simple text file (postscript files is what you need for general fancy graphics, e.g., formatted text and images, and that is true for both Windows and Linux, as postscript files are the file format that printers "understand").

From a C++ program, what you would normally do is create a text file with whatever you want, and then issue a system command to send that file to the printer:

std::system("lpr my_file.txt");

which uses the lpr tool.

BTW, Windows uses the same utility (lpr) for simple printing tasks. (which is not suprising since this stuff pre-dates even the existence of Microsoft and DOS)

If you want to have fancier printing outputs, I suggest you look into using another toolset to prepare the document. For example, you could generate a tex file out of a basic template into which you insert to text, and then, generate a postscript / pdf file from that (using the tex / latex / pdftex programs). This is pretty standard because building all the formatting and alignment and stuff like that, and creating files like postscripts / pdfs, is not a simple task, but creating a tex file from a template is trivial, and let the tex toolset deal with the "rendering" of it.

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

WallMart doesn't sell walls either.

It's Walmart, with only one L. That's why they don't sell walls ;)

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

If you're providing coverage beyond what ACA allows, at a price above what ACA allows, and now you're told by the ACA that you have to lower the price but aren't allowed to reduce the coverage, you as a company have but one option: cancel the policy.

I'm afraid your understanding of the ACA is literally completely the opposite of what it is in reality. In a nutshell, the ACA sets a minimum bar for the insurance policies, but only on what the policies provide, not how much they cost, that is completely up to the insurance company (which is why the insurance companies absolutely love the ACA). Then, it requires everyone to get insurance (the "mandate") at least reaching that minimum bar, but if they can't afford even that insurance, the government will provide the necessary financial assistance to be able to afford the minimum insurance policy. Then, it gets rid of "pre-existing conditions" as an excuse that insurance companies have used for decades to either refuse to insure someone, or retro-actively cancel their policy the day they need it (get sick). There are a few other goodies, but that's the main parts of it.

Many progressives (including me) would criticize the ACA for being too much of a hand-out to the insurance companies (the mandate + government assistance is a big pay-out for the insurance companies), and the fact that there is no price control or competition. Allowing everyone to buy into Medicare if they so …

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

The main program is a function. The question makes no sense. The alternatives: "within a function" instead of "within a function".

You would open / close a file within any function for the same reason that you would open / close a file with the main function, i.e., because you need to read from or write to the file.

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

Does this mean , that I am copying One_mat_ (which I am casting it as a mymat3* ) to One_mat which is defined as a mymat3 matrix ?

No, you are only making a copy of the pointer. The cast from float* to mymat3* causes the pointer One_mat_ to be copied into a pointer of a different type, the One_mat pointer. These are pointers, i.e., only an address value, copying them does not copy the memory at the address they point to.

And why as an argument I have float *One_mat_ and inside function I do: (mymat3 *)One_mat_ and not (float *)One_mat_ ?

You are asking us why you did this? I don't know, you are the one who wrote that code (presumably), you should know why you wrote it that way, or at least, what you expected it would do. I am not a mind-reader.

All I know is that it is a very questionable piece of code. It is valid, but very fragile and certainly not recommended.

Could I have inside argument the void myfunc(mymat3 * One_mat_, .... instead of void myfunc(float *One_mat_, .... ?

Yes, and you probably should. Or better yet, use void myfunc(mymat3& One_mat_, ...., i.e., pass the static array by reference, this way you will avoid the error-prone double-dereferencing syntax.

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

but it is not easy when debugging... :-)

Yeah, that's true, that's one of the annoying things with MACROs. However, you should try using the Clang compiler instead of GCC (or others..) because it has great diagnostics of compilation errors, including the expansion of MACROs to show where the error actually occurs in the post-MACRO-expanded version of the code. Much nicer.

But all in all, any code that you are going to put in this kind of MACRO should be very heavily tested before to make sure it doesn't have any serious problems or bad interactions with the rest of the code.

And, AFAIK, for this kind of problem the only real alternative is to do like Qt has done with their "QT_OBJECT" thing, that is, have their own pre-processor program to go an insert all those bits of "ground-work" code. But, I think that sticking with the standard pre-processor and regular MACROs is better for as long as it's sufficient.

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

Well, first of all, the two options are not mutually exclusive, there is not problem with providing both a factory function (create) and a polymorphic cloning function, it is, in fact, very common. Something like this:

class Object {
  public:
    // NEVER FORGET THE VIRTUAL DESTRUCTOR!!!
    virtual ~Object() { };

    virtual int getInt() { return 0; };

    virtual unique_ptr<Object> clone() const {
      return unique_ptr<Object>(new Object(*this));
    };

    template <typename... Args>
    static unique_ptr<Object> create(Args&&... args) {
      return unique_ptr<Object>(new Object(std::forward<Args>(args)...));
    };
};


class One : public Object {
  public:

    virtual int getInt(){return 1;}

    virtual unique_ptr<Object> clone() const {
      return unique_ptr<Object>(new One(*this));
    };

    template <typename... Args>
    static unique_ptr<One> create(Args&&... args) {
      return unique_ptr<One>(new One(std::forward<Args>(args)...));
    };
};

The use of the unique_ptr in the factory function is just because they are implicitely moveable into a shared_ptr, so, there is no reason to "commit yourself" to the shared_ptr in the factory function. Instead, let the calling context determine if the caller of the factory function wants to put the result in a shared-pointer or in a unique-pointer. But if you want to avoid using unique-pointers (since they are C++11 only, as opposed to shared-pointers which exist since TR1 and are available in Boost), then using shared_ptr is also perfectly acceptable.

Is it possible to achieve this kind of functionality without forcing the user to add a specific function to each class?

This is a bit difficult. As far as I know, there is no clever trick to achieve this in a really …

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

Yo mama is so fat that when she goes near the ocean, the tide rises.

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

What I'm opposed to is the lack of quantification of anything. When it says "could potentially pose a catastrophic EMP threat", there's no measure in that statement: "potentially" could mean anywhere from 99% chance to one chance in one trillion; and, "catastrophic" could mean anything from wiping out all of the human race to causing significant damage to the infrastructure (require significant repairs, and possibly an extended down-time). This kind of alarmist language with no real measure or proportions irritates me to the highest degree.

From the 2010 report I glanced over (which was rather poor quality, from my judgement as an engineer who has studied those kinds of effects), even they seem to conclude that there are serious concerns about preserving the equipment and avoiding wide-spread power failure due to a cascade of failed equipment. But it seems limited to bursting relays and burned PLCs, and they do a lot of wild speculations about the likelihood of equipment to be damaged. And there are many questionable methods in their study, like, for instance, using upset-limit voltages to decide if a pulse of a certain voltage will damage them, without considering the power density. Also, they seem to model all plugged-in electrical equipment as being a large antenna (the cable) plugged into the equipment, without modeling ground capacitance and dynamic response of the equipment and transmission equipment. Long story short, it does not convince me that there is very much of a threat except for a few mishaps that would …

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

A single nuclear weapon detonated at an altitude of 400 kilometers over the United States would project an EMP field over the entire country, as well as parts of Canada and Mexico.

That's exactly the kinds of things people should not say, because it lacks any kind of measure of impact. This statement is trivial, i.e., you could potentially create a large enough nuclear weapon such that if it detonates in the sky above Texas, you would be able to measure / detect an EMP in Vancouver, Canada. But the important questions here are "how big would that nuclear weapon need to be?" and "how strong will the impact of the EMP be when it reaches Vancouver?". The reality is, to have an EMP impact in Vancouver that would be strong enough to shutdown just the most vulnerable electronic equipments, you would probably need a nuclear weapon so powerful that it would likely turn Texas and Mexico and every state in that radius into a massive crater.

To have any real impact, the EMP needs to carry a lot of energy (eletro-magnetic energy), and in a blast radius, energy diffuses in an cubic rate, meaning that you very quickly end up with very little energy left in the pulse. And the larger the radius of effect, the larger the initial pulse needs to be, by a cubic power.

A more likely scenario to try and cripple the entire USA through an "EMP attack" would have to involve detonating …

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

Taco Bell and poor service.

I think you cannot really generalize the quality of the service in these types of franchises. Chain restaurants like Taco Bell share a common name, menu, prices, and ingredients, roughly speaking. But usually, the rest is mostly up to the franchisee, i.e., the guy who owns that particular franchise, or his manager. In other words, if you got poor service at your local Taco Bell, then it probably just means the guy owning / managing that particular restaurant isn't paying enough attention to making sure customers get good service. You can not really generalize.

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

What if all the power house countries went to war with each other and we all sent EMPS at each other

You watch too many movies. You are not alone though, even the US Air Force had to make a video "Hollywood vs EMPs" to dispell the hollywood myths about the power and impact of EMPs. For one, the power required to send a real wide-spread EMP is only achievable with nuclear weapons. And if you were to generate enough EMPs to seriously cripple the entire power grid or tele-comm systems, it's not the outages you should be worried about but the nuclear fallouts. On a more practical level, EMPs can be used to induce glitches on targeted systems, possibly temporarily shutting them down or damaging some electronics components. But the effect is very limited (either very narrowly targeted, or wide-spread with very little impact except a few minor glitches). It is nothing like in the movies, that's called fiction.

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

Farmers raise cattle, like parents raise their children. Farmers don't "grow" cattle, just like parents don't "grow" their children.

Here's a free grammar lesson:

The sentence "cows are grown" implies the more complete sentence "cows are grown by the farmer". This is a passive form of the verb "to grow". The equivalent active form would be "the farmer grows the cows". This does not work because the verb "grow" is reflexive (the object is always the subject). You can say "I grow" or "I grew up", or you can say "wheat grows" or "the tomato plants have grown", because these are all active, reflexive forms (in "I grow" the "I" is both the subject and the object of the growth). Technically, you cannot say "the farmer grows corn", you should say "the farmer cultivates corn", for the same reason, but it's a common mistake (and somewhat accepted, I think). So, the appropriate verbs are "to breed", "to raise", and "to cultivate".

(sorry for being a bit of a grammar-nazi)

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

I thought the winters were too severe for them, but I've never been in Canada.

Farm animals would generally spend the winter inside heated barns. And they can often takes strolls outside, on milder days. But, yeah, we "grow" all sorts of animals here, just like almost anywhere else, including cows/beef, pork, chicken, sheep, whatever.. And most of them can live in fairly low temperature climate, as long as they have food.

Just like human children -- they are grown.

I thought children were raised. Cows are bred and then, raised. I think these are the proper terms.

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

Knock out the satellites and all communications

Easier said than done, there are far so many satellites that a large number of satellites could be "knocked out" without really compromising the whole system. Global telecommunication systems are massively redundant by design, there aren't really any single points of failure in it. And also, how exactly can you knock out a satellite? Satellites on geosync orbits (where most tele-com sats are, except of a few russian sats on high elliptical orbits) are very far away (about 36,000 km altitude), are not affected by problems like space debris, are too far to be destroyed remotely, have safety low-gain antennas in case attitude control is lost, and are designed to run for decades before needing to be replaced. They are not about to disappear, I can tell you that much. Even GPS satellites are quite safe, even though they are much closer to the Earth. The more dangerous zones for satellites are in low-Earth orbits (LEO), where observation satellites are (weather sats, spy sats, etc.).

The Internet is not about to go down either, after all, it was designed for redundancy and failure safety in the first place (i.e., military networks relayed through planes, helicopters, vehicles, and bases, which are all subject to suddenly disappearing). The only thing that really threatens the internet is people with economic motive to compromise it's inherent openness and neutrality, which are the key aspects of its fail-safety and redundancies.

computers will run at 5.2 …

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

We don't have Taco Bell here. It's because of consumer protection laws against false representation. Basically, you cannot sell a "beef taco" if you cannot show that it actually contains beef. That's why Taco Bell (and a few other american chains) don't exist in Quebec.

That said, if I'm south of the border, I enjoy a good Taco Bell, just like the next bloak.

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

Whatever happened to just failing those cheaters? If the prof has found out that one of his student took an answer from here or elsewhere, that's plagarism, that's an automatic zero on the assignment / exam. That's how it is here (if not worse). If the prof does not have the chutzpah to fail his cheating students, it's his problem, not yours.

It's very easy these days for CS courses to have anti-plagarism filters (take code and search for exact matches on the web).

JeffGrigg commented: Yes; they need to have and use a policy that works. +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

(1) what should be strategy to design a good hashing function.

I am not an expert on hashing functions. The basic idea is that it should be a good way to map all the numbers you are storing to a compact and non-clashing set of numbers. The standard containers will use a basic one-size-fits-all hashing function. For example, if you are storing int objects, and let's say those are 32bit, then the range is −2,147,483,648 to 2,147,483,647, and the default hashing function will probably make the assumption that the integers you give to store will be uniformly distributed over that entire range. So, if your numbers are between 0 and 1000, then that hash function is wildly inappropriate.

This is all a matter of probability distributions of the data and minimizing collisions while maintaining compactness. As explained in the link I provided: hashing is an art. And I can't claim to know much about it.

(2) Is it possible to use well design Hash function with unordered_set as unordered_set will have its own hash function .

Yes. The standard containers like unordered_set take a template argument to specify the hash function to use. See the reference page. Notice the "Hash" argument to the template. By default, the std::hash functor is used, see docs.

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

I think that your implementation of the Option 3 is quite messed up. There are a number of impossible things in there, and errors. This part is especially troublesome:

    onE=[]() {
            bool a=tmpE();//(a)
            bool b=o.onEvent();
            return a||b;
        };
    delete tmpE;

1) Your lambda expression here is a stateful lambda, because it needs to capture o and tmpE. Stateful lambdas cannot be converted to function pointers. You need to use std::function<bool()> instead of a bool(*)() function-pointer.
2) Lambda expressions are not allocated with new, and thus, should not and cannot be deallocated with delete. Lambdas are syntactic sugar for function objects, i.e., they are copied around by value. They are not allocated on the heap, they are created like any other local variable (and can be copied into the return value or a data member). Under some conditions, lambdas can be converted to function-pointers, but that is only if the "call operator" in the equivalent function-object class could be implemented as a static member function (i.e., stateless, or no captured parameters).

And I don't think this option really works very well. You are kind of getting the worst of both worlds.

I think that we are starting to talk in circles a bit with all these options, because we lack a clear set of requirements. There are different solutions for different sets of requirements. Initially, I assumed you had some sort of traditional OOP requirements (run-time polymorphism, shared ownership, persistent instances, etc.). But from the options you …

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

The standard solution to this is to use an associative container to store the list of numbers. One obvious option is to use std::set which relies on a binary search tree and will achieve look-up times of O(log(N)), as is typical of binary search trees. In your case, however (numbers and millions of records), it might be more appropriate to use a hash-table implementation, which, in the standard C++, is implemented in the std::unordered_set, which will acheive look-up times of O(1) through a hashing function. To really optimize the performance, you would probably need to design a good hashing function that is tailored for your application (MSISDN numbers).

There are other options, but I think that a hash-table is definitely the way to go in this case.

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

The closest you can get is probably something like this:

class Data {
  // ....

  private:
    static const double* getInitValues() {
      static const double arr[] = {1.0,4.0,5.0};
      return arr;
    };

  public:

    Data() : V(std::vector<double>(getInitValues(), getInitValues() + 3)) 
    {
    };

};

But frankly, I don't see the point of going through all this trouble just to either (1) avoid using a C++11 feature, or (2) avoid putting three simple statements in the constructor body.

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

The two good reference sites are:

http://www.cplusplus.com/reference

http://en.cppreference.com/w/

There are also some downloadable versions of these as compressed help files (chm or qch) for local viewing (downloaded). I'm not sure what the best "hard copy" reference could be.

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

Here is the output that I get:

Test
X=65535
Segmentation fault (core dumped)

Which did not surprise me at all. I was more surprised that my compiler actually accepted the code, because I did not expect the line *o=t|i; to compile successfully (because it would seem to require copying an abstract-class object).

I can easily fix the code to get well-defined behavior (not a seg-fault or other corruption problem) (and I also could not resist fixing the bad formatting!):

#include <iostream>
#include <vector>

using namespace std; //its just a test code-segment

class Object {
  public:
    virtual bool onEvent() = 0;

    // NEVER FORGET TO HAVE A VIRTUAL DESTRUCTOR!!
    virtual ~Object() { };
};

class test : public Object {
  public:
    virtual bool onEvent() {
      cout << "Test" << endl; 
      return false;
    };
};

class inc : public Object { 
  private:
    int x;

  public:
    inc() : x(0) { };

    virtual bool onEvent() {
      cout << "X=" << x++ << endl;
      return false;
    };
};

class Cumulator:public Object {
  private:
    Object &a,&b;
  public:

    Cumulator(Object &a, Object &b) : a(a), b(b) { };

    virtual bool onEvent() {
      bool ra = a.onEvent();
      bool rb = b.onEvent();
      return ra || rb;
    };
};

Cumulator operator| (Object &a, Object &b)
{
    return Cumulator(a,b);
}

int main() {
  vector<Object*> objs;
  test t;
  inc i;
  objs.push_back(&t);
  objs.push_back(&i);
  Cumulator c = t | i;
  objs.push_back(&c);
  for (int i=0; i<10; ++i){
    for (auto x:objs)
    {
      x->onEvent();
    }
  }
  return 0;
}

Which did indeed get the …

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

I still remember the good old days (only a few years ago), when any given search on a devel problem would result in a number of results from different sites (forums and mailing-lists), and when SO and Daniweb were more or less as likely to hit on searches. Now, it seems that Google has somehow made sure that the top three to five search results are always for StackOverflow, regardless of how unrelated the threads are to the actual search terms. Very often, I find myself making a search, and almost automatically scroll down to the middle / end of the first page of results, because I so often find the first results to be irrelevant stuff (irrelevant to my question) from the "preferred sites". I'm seriously thinking finding an alternative search engine (I hear duckduckgo is not too bad, any other ideas?).

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

If you also want to allow for output to the console, this is very easy to do because the printf(..) function is just a short-hand for fprintf(stdout,..), where the stdout is the "file handle" for the console output. Here is that version:

void printtree_recursion(FILE* OutFile, struct node *tree)
{
    if (tree!=NULL)
    {
        printtree_recursion(OutFile, tree->left);
        fprintf(OutFile, "%s %d\n",tree->word, tree->lineNumber);
        printtree_recursion(OutFile, tree->right);
    }
}

void printtree_to_file(struct node *tree)
{
    FILE *OutFile = fopen("test.txt","w");
    printtree_recursion(OutFile, tree);
    fclose(OutFile);
}

void printtree_to_console(struct node *tree)
{
    printtree_recursion(stdout, tree);
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

There are a few minor issues to begin with:

virtual bool onEvent(Event e)=0;
..
  const Object &o
..
  o.onEvent(e);

This is not going to compile because the member function onEvent is a non-const member, and the object o is a const object. You will need to choose between having a const onEvent member, as so:

virtual bool onEvent(Event e) const = 0;

Or requiring your objects to be non-const.

Second, there is really no point in defining operators to be member functions if you don't particularly need it's implementation to be very strongly tied to the class' internals. In this case, your operator| could easily be a non-member function. This will free up a few options to solve your problem, because you can make smart use of overloading (on both parameters).

Third, beyond the fact that you cannot really "reassign" the onEvent function to be a lambda expression (as your second post suggests you have already realized), there is the problem of the capture of objects into the lambda. Normally, you would have to have done something like this to declare your lambda:

[this, &o](Event e) {
  return this->onEvent(e) || o.onEvent(e);
}

which piece-by-piece means:
[this,..]: Capture the this pointer by value.
[.., &o]: Capture the o object by reference.
(Event e): Make a lamba that takes one parameter (an Event object by value).
With no return type specified, meaning, the compiler deduces it from the return statement (if trivial enough).

Now that …

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

Just split the function into the user-facing function and the recursive function, and pass around the file handle in that function. As so:

void printtree_recursion(FILE* OutFile, struct node *tree)
{
    if (tree!=NULL)
    {
        printtree_recursion(OutFile, tree->left);
        fprintf(OutFile, "%s %d\n",tree->word, tree->lineNumber);
        printtree_recursion(OutFile, tree->right);
    }
}

void printtree(struct node *tree)
{
    FILE *OutFile = fopen("test.txt","w");
    printtree_recursion(OutFile, tree);
    fclose(OutFile);
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Just use fprintf instead of printf. You use fopen and fclose to open and close the file (with a FILE* handle).

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

I would like to see the beginning of creation

Lol! Don't forget to tell Eve not to eat that apple. Or better, just cut down that tree, better not take any chances. If you don't go back that far, you can at least warn Jonah to watch out for big fishes. Or tell Lot's daughters to leave town before their father gives them up to be raped by an angry mob.

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

Yeah, the aging is a major component here. If that pill means that you stay at a middle age like 30-40 or something like that, then we can have a conversation. But I think that if the pill implies that you keep aging, then it would mean that after the first 80-100 years of your life, you will live for another 900 years in an an extremely old and weak state, like a typical 100-year-old person, then I don't find that prospect very interesting at all.

I think that if that magic pill is somehow a pill that makes it so that once you are fully grown adult, you effectively stay at that age until the end of time (or until you die of an accident or of a disease, meaning that on average you would live on for hundreds of years). Then, I think this does have some appeal. After all, if you get really bored, you can just kill yourself.

I might go for that.

I think there are some interesting problems if all would take that pill. Children would have to become very rare, given that we would need far less of them to balance out the deaths. That would be a bit sad, I think. And also, let's say your 785 years old, and you have a son/daughter who is 654 years old, that's a bit weird too, i.e., you could basically have the same age / life-experience as your kids. And what about education, would …

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

This truth table looks more like ( (NOT p) OR q ). Or, it could be if p then q else TRUE.

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

as a beginner, i managed to do this much (85%) and i am facing the problems of "Cannot find or open the PDB file."

PDB files are files that are specific to Visual Studio projects. This is a problem with setting up your C++ project. Are you able to run a simple "Hello World" program? Did you make sure the follow all the steps to create a win32 console application in Visual Studio?

You might want to consider using a simpler (lighter-weight) IDE like CodeBlocks instead (make sure the download / install the version with MinGW). It uses a simpler (and less troublesome) project configuration system than Visual Studio.

am i supposed to place the files in a special place for the program to read it?

If you provide absolute paths, then it does not matter. If you provide relative paths, then they will be relative to the place where the executable runs from (which is kind of unclear in Visual Studio). Just locate the folder in which the "*.exe" file for you project was generated (it is usually in the "debug" or "release" directories of your project folder). I'm sorry, it's been a long time since I've used Visual Studio with default build configurations (I, like most experts, use other external build configuration-script systems).

Also, your input method:

cout << "Input the name of the input file: " << endl;
cin >> inFileName;
inFile.open(inFileName.c_str());

will only capture the first …

ddanbe commented: No one can beat the deepness of your explanations. +15
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You mean the lie that people who like their present insurance won't have to change it???

The only people who would have to change their policy are those whose insurance policy is so terrible (not enough coverage, too much deductibles) that it doesn't meet the minimum standards set by the ACA. These people would be required to upgrade to a better plan since that crappy plan would disappear. And, a very important part of this is that if they cannot afford to increased price for the better plan, the state will subsidize it. Then, there are only a very tiny percentage of people who would actually end up having to pay more, and only those who can afford it. I have heard that the actual percentage of people affected in this way is less than 1 percent of the population. Even the right-wing media has trouble finding cherry-picked examples of people in that situation. Like this example of the disgruntled woman who complained she was forced to upgrade her plan, but then retracted that complaint when she was informed that the new plan would not cost too much more (after subsidies) and cover her far better (due to the minimal requirements / mandates).

Oh, and by the way, they just (today) anounced a provision to the law to say that if you want to keep your sub-standard coverage (i.e., not upgrade to a policy that meets the minimum requirements), you can do so. I doubt many …

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

Welcome to Daniweb!

I'm glad to welcome another C++ apprentice! (btw: I'm one of the main C++ gurus here)

i made an account here, in which i was able to post a question i had a bout a project for grading program, then i received email of required activation which i thought was weird cause i was able to post when i wasnta activated

Yeah, that's the system Dani put in place. Basically, there is a 24hour grace period right after registering where you can post without having "verified" the account through the email link. This is to make it easier for people to just register and post immediately, while still protecting against fake accounts or bots.

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

Happy Birthday Dani!

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

It depends on the code that you are testing. In general, it's a matter of how deterministic the code is, how sensitive to input it is, pathological cases or error conditions, and so on. An arbitrary number does not really make that much sense, but sometimes it boils down to a simple "more tests = more confidence that it works", and then you can just do as many tests as is necessary for you to be confident enough to release the code.

For example, if you have a simple algorithm like a matrix-vector multiplication, then testing it once is probably enough because the algorithm has no error cases (unless you want to handle overflows / underflows and other "rare" errors), has no pathological cases, is completely deterministic, and is not sensitive to the input (the algorithm is the same regardless of the actual input numbers).

On the other hand, if you are testing a matrix inversion algorithm, then you are going to need much more testing because it has error cases (singular matrices), the results are very sensitive to the input values (e.g., generation of round-off error), and the algorithm's execution depends on the input (i.e., it looks at data to make decisions). This means that you need to test it with a wider set possible inputs, including inputs that should fail (gracefully), and including any input that could be pathological (i.e., manufactured to throw off the algorithm).

And then, there are algorithms that are non-deterministic. They might use random-number …

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

This speaks to the point I made in the last post. The code you just posted makes no sense at all.

And obviously, when I posted the simple example of what a "functor" is, I didn't mean that as a suggestion for something to try for your specific problem. It was just the simplest possible example I could come up with of something that can be called a "functor", to illustrate the concept. It had nothing to do with your specific problem. You asked for an explanation of what a "functor" is, and I delivered that. A functor is a very general and fundamental concept in C++, and so, I had to explain it in very general terms, having nothing to do directly with your specific problem.

but i get errors when i change the Soma()

What do you mean?!?!? You cannot "change the Soma()". That makes no sense at all. A function has one definition and only one definition (that's the fundamental C++ rule, called the "One Definition Rule"). That definition is fixed during compilation, and can never be changed after that.

You can create a variable that points to a function, that's called a function-pointer. You can create a variable of a class type like std::function which can be made to point to any callable "something". But these are always just pointing to a function which has one unique and immutable definition.

And the error itself is due to this syntax:

a.Soma(int a, int b) …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

the foo structure accept parameters?

No. The call operator definition is as follows:

void operator()() const { };

Which means:
void: This function has no return value.
operator(): This function is invoked by "calling" the object like you would call a function.
(): This function takes no parameters.
const: This function does not modify the object on which it is called.
{ };: This is the function body (which I left empty).

So, the answer is: No, an functor of type "Foo" is called with no parameters.

how can i change the funtion?

What do you mean? I left the body of the function empty, but, of course, you would normally write code in that function-body. If that's what you mean by "change the function", then that's that, i.e., you can change the function when you open the source file in a text editor or IDE and you write code in the function-body.

If you mean to somehow assign the call operator to trigger the call of some other function, then that's impossible in this code. In C++, a function is just a function, you cannot "change" it in that sense. If you have a variable like a function-pointer or a std::function object, then this is different, these are variables that are meant to be changed to whatever value you want. A "function" is not a variable, it's immutable (cannot be changed).

I'm gonna be frank here, I must say that you seem be …

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

No. A functor is just a short for "function object" or "callable object". It is a callable thing. For example, this is a functor:

struct Foo {
  void operator()() const { };
};

Because if you have an object declared as something like Foo f;, then you can "call" it, as in, you can do f();.

Technically, almost anything that is callable is a "functor". A function pointer is a functor, because it is an object (a pointer is a variable, which is an object) and it is callable. A lambda expression is a functor too. The standard class template std::function is a functor too, with the special feature that it can encapsulate any other functor you give it.

Traditionally, however, the term functor is mostly used to describe an object of a class like the "Foo" class in the above snippet. In other words, an object of a class that has a "call operator", i.e. the operator(). But in modern C++, with things like std::function, std::bind and lambdas, that line has become a bit more blurred. I just use the term "functor" for any object that is callable.

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

As far as I know, the standard does not provide a specialization of std::function for "variadic functions" (also called "variable argument functions", or just var-arg functions). When you use the ellipses alone (not part of a variadic template syntax), it declares a variadic function, which is a special kind of function that was inherited from C to allow for a variable amount of parameters (e.g., to allow the implementation of functions like printf or scanf).

I am not too surprised that the standard committee overlooked this possibility since variadic functions are antiquated and unsafe. It is generally not recommended to use them, ever. And one of the main purposes of variadic templates is to replace variadic functions with a type-safe solution. In other words, forget about variadic functions, they are just part of the C legacy that C++ has to drag around.

If variadic functions could be used with std::function, your code would have to look like this:

class event2
{
public:
    typedef std::function<void(...)> OnSomethingHandler;


    template <typename... Args>
    void operator() (Args&&... args)
    {
        eventwithoutarg(std::forward<Args>(args)...);
    }

    event & operator = (OnSomethingHandler Handler)
    {
        eventwithoutarg = Handler;
        return *this;
    }

private:
    OnSomethingHandler eventwithoutarg;
};

Except that this will not work because the type std::function<void(...)> is not defined by the standard (AFAIK).

If I understand what you are trying to do, I think you need to do a classic type-erasure strategy. Here is what I mean:

class events {
  private:
    // have a placeholder base-type:
    struct base {
      virtual ~base(); …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

can i use the instance\object name?

Not for the definition. The member is a static data member, meaning that it is linked to the class, not an object. However, for expressions, you can access the static data member through the object, but this is just a syntax feature, the static member is still the same for all objects of the same class. Here is an extension to the example:

class Foo {
  public:
    static int bar;  // <- 'declaration'
};

int Foo::bar = 42;  // <- 'definition'

int main() {
  Foo f;
  f.bar = 69;  // OK
  std::cout << Foo::bar << std::endl; // <- this will print '69'
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

No, you cannot. You can have one definition of the static data member (i.e., constructor / initialization of the data member). But after that, you cannot modify the static member at the global scope, because that would have to be either an expression (which is not allowed), or a second definition (which would break the C++ One Definition Rule (ODR)). Of course, you can modify the static data member within any function, but not at global scope.

Here is a simple example:

class Foo {
  public:
    static int bar;  // <- 'declaration'
};

int Foo::bar = 42;  // <- 'definition'

Foo::bar = 69;  // ERROR: expressions not allowed at global scope.

int Foo::bar = 69;  // ERROR: re-definition of 'Foo::bar'

int main() {
  Foo::bar = 69;  // OK
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

you're saying that I cannot create 1 program that will be cross platform (in c++) but I can make a library that is cross platform

Whether you create a program or a library, the situation is the same. Usually, it is more practical to make a cross-platform library (i.e., encapsulate the platform-specific code in a library). However, you could also do it in a program.

by swapping in correct code at compile time (presumably using #ifdef directives).

Yes. You swap the correct code at compile time, either using some #ifdef stuff in the code, or using the build script to swap between distinct cpp files that implement the same functions but in a different way (for each platform).

Then if I want my code to work on two systems I compile it twice, once with each OS specified?

Yes. This is often inevitable, depending on how different the platforms are. Some platforms use completely different binary formats for executables and libraries. Specifically, Windows versus Linux/Unix/BSD (i.e., POSIX). Among different versions of Linux and other similar systems, things will mostly work without recompilation, as long as the target architecture (instruction set) is general enough (like i386 for example). But executable programs for very different platforms like Mac, Linux and Windows are not going to work between them, you have to recompile for each platform.

When we talk about doing cross-platform development in C/C++ (or any other native compiled language), we are just talking about the …

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

I see the same problem (the username spilling over under the faint line) on my browser: Chromium in Linux(Kubuntu).

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

I think Labdabeta misunderstood your code. He thought that your declaration of Printed was meant to be a function pointer to a function that takes no argument and returns a events<> object. In reality, your declaration of Printed was a declaration of a data member of type events<> with an in-declaration initializer (that uses the new {} uniform initialization syntax) to an empty lambda functor. Later, when he initializes the Printed function pointer to point to a lambda expression, it cannot work because the lambda expression must return an events<> object, instead of void. In other words, it doesn't work.

cambalinho commented: thanks +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I tested the code (that I posted in my last post, and using your implementation of the "events" class) and it all works, no warnings, no errors, and runs as expected, with the correct output.

if i'm overloading '()' operator, why i can't use it, outside of main?

It does not matter what you overload or not, you cannot execute code outside of any function's body. It's that simple. See this simple code:

// these lines are fine, 
//  they are 'definitions' of global variables. 
int a = 2;
int b = 3;

// this line is OK too, 
//  it's also a 'definition' of a global var.
int c = a + b;

// this line is an ERROR!
//  it's an 'expression' not a 'definition'
c = a * b;

At the global scope, you are allowed to declare stuff like classes, functions and variables, and you are allowed to define stuff like functions (by providing a body for the function) and variables (by providing an initial value / constructor-invocation). But, you are not allowed to write expressions that need to be evaluated. The compiler only issues "static initialization code" for the global objects, it cannot accomodate general expression evaluations (unless they are made a part of the construction of one of the global variables).

When you tried to give a new value to the data member a.Printed, that was an expression, just like the c = a * b; expression above, which is …

cambalinho commented: thanks +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yeah, the most common use for static member functions is for factory functions, whether it is a straight-up "Create()" function to create an object of the class, or whether it is for a set of factory functions like "fromString" and stuff (i.e., Java-style conversion functions, when people are not familiar with or not comfortable with C++'s conversion operators, or they just want a more explicit syntax).

There are some other special purposes for static member functions. Most of the time, it just boils down to semantics. If a given function clearly and only belongs to the class, but it does not need to be called on an object of that class or does not take one (or more) as an argument to the function, then the only way to really tie it to the class is to make it a static member function. This is the same argument as for static data members.

And the name pollution can be a real concern sometimes. As a rule of thumb, if you have a class named "Foo" and you want to create a static member function named "Bar", and you are considering making that function a free-function (in the namespace/global scope) instead. If, while making the function a free-function, you would have to rename it to something like "FooBar" in order to make it make sense, then you are probably better off leaving it as a static member function, i.e., calling it as "Foo::Bar". This is the basic "semantics test" to figure …