Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
that awful man
Feb 18, 2007

YOSPOS, bitch

A MIRACLE posted:

My professor wants me to write a hash table library for my data structures class using the following function declaration to create the table:
code:
void *hash_table_create(int data_size, unsigned int (*hash)(void *key, int tablesize), int (*compare_keys)(void *key1, void *key2))
As he was nice enough to never go over function pointers in class I have to ask, am I supposed to write these inner argument functions outside *hash_table_create? And how will it look when I call hash_table_create? If I'm asking too much could someone point me to a good tutorial on function pointers?

Why on earth does he want you to return a void pointer instead of a pointer to some sort of structure?

Adbot
ADBOT LOVES YOU

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Not 100% sure but I'm positive it has something to do with information hiding. He loves that stuff.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

that awful man posted:

Why on earth does he want you to return a void pointer instead of a pointer to some sort of structure?
Presumably because this way the hash table underlying structure can be completely changed without any recompile of the stuff that uses it.

It would still be better to at least make it something like a typedeffed void*, just so that your code can refer to the value as a hash_table (or whatever) for readability's sake. The extra functions hash_table_add and hash_table_destroy or whatever else that you'd need to be useful would be a lot clearer if their first parameter is a hash_table than if their first parameter is a void*.

vvv Yeah, I was going to say that that's what I do. Then even if the thing itself isn't one of that struct in the end, you can still just re-cast it just as you would have to with a void* so it doesn't make any [negative] difference from the point of view of the implementation.

roomforthetuna fucked around with this message at 19:39 on Nov 29, 2010

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
You could get the same effect, plus actual type-checking, by only forward-declaring the struct in the header.

That Turkey Story
Mar 30, 2003

rjmccall posted:

You could get the same effect, plus actual type-checking, by only forward-declaring the struct in the header.

Seconding this. void* here is just a poor choice.

Evil Robot
May 20, 2001
Universally hated.
Grimey Drawer
Sorry, dumb question.

frightened goat
Aug 9, 2003

If your goat doesn't look like this then you are doing something wrong
Does anybody know what's going on with my numerical solution code? Somebody else wrote it, and I've been tasked with getting it to work, but I can't seem to. The source code is here: http://codepad.org/0T67a824.

I first tried compiling it with gcc in linux (after changing fopen_s() to fopen() throughout) and that segfaulted after the first iteration, I think. It fares a bit better in VS/win7, managing to write some output, but it just hangs at 0% CPU after having done one iteration. I'm practically a mediocre mathematician posing as a programmer, so I don't know where to start :(

brosmike
Jun 26, 2009
I just tried this on a windows box under cygwin and it seems to work fine; however, you need to press enter after the first iteration, since the

code:
if( iter%ask == 0 )
in line 490 will evaluate to true on the first (0th) iteration regardless of the value of ask.

The segfault on linux might be a permissions error - the program never bothers to check that fopen() succeeded, and if it failed then the following fprintf would segfault.

Mopp
Oct 29, 2004

I'm looking for an easy way to create a makefile for my small project, any ideas on what I could use?

mr_jim
Oct 30, 2006

OUT OF THE DARK

A text editor? If you're looking for a program that generates makefiles, you'll need to give a little more detail. But take a look at premake4.

Mopp
Oct 29, 2004

mr_jim posted:

A text editor? If you're looking for a program that generates makefiles, you'll need to give a little more detail. But take a look at premake4.

oh, sorry. i'm looking for something that I can just show my files, and let it do all the linking needed to create the makefile. a makefile generator, in other words.

slacjs
Feb 27, 2009

I'm trying to build an expression tree and I'm sure there's an easier way of doing it than what I'm doing at the moment.

code:
//aSet returns whether the node is a set or not. 
//Popfront returns and removes the front of the equation. 
//Before any of this is ran, the first part of the equation is set as the root.
//To reverse it (postfix), lefts go right and rights go left and flip the expression backwards.

build(root, expression) 
{
    int full; //Is left full?

    if(root.left == NULL)
    {
        root.left = new Node(NULL, expression.popfront, NULL);
    }
    else if(root.left == aSet || full == 1)
    {
            full = 0;
            if(root.right == NULL)
            {
                root.right = new Node(NULL, expression.popfront, NULL);
            }
            else if(root.right == aSet)
            {
                full = 1;
            }
            else build(root.right, expression)
    }
    else build(root.left, expression)

    if(full == 0)
        build(root, expression);

}
It seems so long. I've had a google around and can't find much for C++. Anyone have any suggestions? Thanks.

nielsm
Jun 1, 2009



Mopp posted:

oh, sorry. i'm looking for something that I can just show my files, and let it do all the linking needed to create the makefile. a makefile generator, in other words.

Let's say you have three source files, file1.cpp file2.cpp file3.cpp

You want to compile those and link into a program named awesome.

Here's a makefile that should accomplish that:

code:
awesome: file1.o file2.o file3.o
        $(CXX) file1.o file2.o file3.o -o awesome
I think there is some way to simplify it further, but I couldn't make it work at this time. (I'm quite sure it's possible to get make to write the linking commandline as well, just by defining an appropriate target.)
You can set variables such as CXXFLAGS in the makefile too, to affect the default targets that produce objects from C and C++ source files.

Mopp
Oct 29, 2004

nielsm posted:

Let's say you have three source files, file1.cpp file2.cpp file3.cpp

You want to compile those and link into a program named awesome.

Here's a makefile that should accomplish that:

code:
awesome: file1.o file2.o file3.o
        $(CXX) file1.o file2.o file3.o -o awesome
I think there is some way to simplify it further, but I couldn't make it work at this time. (I'm quite sure it's possible to get make to write the linking commandline as well, just by defining an appropriate target.)
You can set variables such as CXXFLAGS in the makefile too, to affect the default targets that produce objects from C and C++ source files.

Yeah, I'm familiar with standard makefiles but this program is the biggest one i've written yet so I wanted to have something that could do it for me.

I got premake to work, and it did exactly what I wanted. Thanks for the tip!

Jick Magger
Dec 27, 2005
Grimey Drawer
So I'm working on a little something in a Qt framework. I don't normally use it (or C++ for that matter), so I'm completely lost when stuff just doesn't seem to be working.

I'm trying to something very simple: I want to see if a QString contains a substring

code:
if(fileName.contains("jgt", Qt::CaseInsensitive)){
     //do some poo poo
}
Simple enough, the function is built right in. But, Qt Creator keeps throwing this error:
conversion from 'const char[4]' to 'QChar' is ambiguous.

The contains() function is overloaded, and one of the versions accepts a QChar. But one also accepts a QString, which is clearly what I would like it to do. Casting it as a QString doesn't seem to help.

I'm even trying to run the EXAMPLE CODE provided by the documentation
code:
 QString str = "Peter Pan";
     str.contains("peter", Qt::CaseInsensitive);
And this returns:
conversion from 'const char[10]' to non-scalar type 'QString' requested.
conversion from 'const char[6]' to 'QChar' is ambiguous.


So what the gently caress am I doing wrong?


[edit]
Oh screw it, I'll just use standard strings.

Jick Magger fucked around with this message at 00:27 on Dec 3, 2010

Zhentar
Sep 28, 2003

Brilliant Master Genius
Do you have QT_NO_CAST_FROM_ASCII defined?

Jick Magger
Dec 27, 2005
Grimey Drawer
Yup, looks like that gets defined. I can see why that would cause problems. I don't know why the original author defined it, so I guess I'll just work around it for now.

Thanks, I was afraid I was a REALLY terrible programmer, instead of just a terrible one.

Dooey
Jun 30, 2009
Can anyone show me an example of template metaprogramming use in the "real world"? I've heard quite a bit about it and seen lots of examples (90% of which are the factorial function) but I have a tough time seeing how I can apply the concepts in my code from examples like that.

BigRedDot
Mar 6, 2008

Dooey posted:

Can anyone show me an example of template metaprogramming use in the "real world"? I've heard quite a bit about it and seen lots of examples (90% of which are the factorial function) but I have a tough time seeing how I can apply the concepts in my code from examples like that.
The Boost Graph Library is fantastically useful.

litghost
May 26, 2004
Builder

Dooey posted:

Can anyone show me an example of template metaprogramming use in the "real world"? I've heard quite a bit about it and seen lots of examples (90% of which are the factorial function) but I have a tough time seeing how I can apply the concepts in my code from examples like that.

A core set of useful stuff can be found in boost mpl. Boost variant is pretty cool example of metaprogramming. If you want to go over the deep end, check out boost spirit, phoenix, and proto.

Dooey
Jun 30, 2009
Thanks for all the examples from boost guys but I'm more looking for ways to apply template metaprogramming in my own code. Like, right now I'm working on a project analyzing a video feed from a webcam, then sending some instructions to an arduino over a serial connection, and pretty much my only use of templates is in my point class, which isn't really template metaprogramming (unless I'm misunderstanding the term)

I can see how its very powerful in libraries and such but I want to do some template metaprogramming myself dammit, not just look at what others have done, and I don't see anywhere that its useful to me, yet.

litghost
May 26, 2004
Builder

Dooey posted:

Thanks for all the examples from boost guys but I'm more looking for ways to apply template metaprogramming in my own code. Like, right now I'm working on a project analyzing a video feed from a webcam, then sending some instructions to an arduino over a serial connection, and pretty much my only use of templates is in my point class, which isn't really template metaprogramming (unless I'm misunderstanding the term)

I can see how its very powerful in libraries and such but I want to do some template metaprogramming myself dammit, not just look at what others have done, and I don't see anywhere that its useful to me, yet.

Metaprogramming is mostly for code that writes code. That kind of style is found in the more functional world, not so much the imperative or OO world. Pick up "The Little Schemer" or other functional programming texts to get an introduction to that kind of style. After working in a functional language, you will begin to see applications where metaprogramming becomes important. If you are always just writing code that mungs data, metaprogramming doesn't really give you too much.

Dooey
Jun 30, 2009
Alright I'll have a read then. Thanks :)

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
As a concrete example: my project has a hashtable implementation optimized for use with pointer keys. That template could just require that its keys be actual pointers, but that would suck: we have a lot of classes lying around that have storage characteristics similar to pointers — generally they're pointers with flags mangled into the low bits — and there's no good reason that we can't use the hashtable for these. With TMP, we can make the hashtable work for an arbitrary class that's willing to say it works like a pointer, and after optimization there's no overhead. Similarly, TMP lets us tell a vector implementation that objects of a particular class type are address-invariant, i.e. they can be safely moved with a memcpy as long as the old object isn't destructed.

We also use the CRTP a lot; it's really convenient to make a CRTP visitor that walks over a complicated hierarchy and tells you about exactly the nodes you care about, without paying out the nose for half a dozen opaque virtual calls per node.

POKEMAN SAM
Jul 8, 2004

Dooey posted:

Thanks for all the examples from boost guys but I'm more looking for ways to apply template metaprogramming in my own code.

This book is awesome and will probably inspire you: http://www.amazon.com/Modern-Design-Generic-Programming-Patterns/dp/0201704315

evensevenone
May 12, 2001
Glass is a solid.
It should be said, it's silly to shoehorn a programming technique into a project that doesn't call for it. Especially C++ metaprogramming, because it's kind of trick that wasn't designed into the language but more of a side effect of how the language works. Obviously it can be used to do some really cool things, but you should think about whether you actually need it and are willing to trade of things like reduced compiler compatibility and making the code less readable to others who might not be as familiar.

Like in your project, I would ask, is there a chance that someone would want to move your vision code to an embedded system or an FPGA or something else weird? What are the chances that the compiler for that system will be full-featured?

Vanadium
Jan 8, 2005

The trick with getting to use all the crazy C++ design techniques is to write everything as a library and only have trivial programs calling into them~

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
While on the topic of templates I thought I'd vent about how my nice and pretty code just got a good violating when I found out constructors in a template don't politely follow along to the derived classes. So now for each of these derived classes I get to cram in a one-liner constructor that refers to the templated one. That's not the end of the world but... gah.

That Turkey Story
Mar 30, 2003

Rocko Bonaparte posted:

While on the topic of templates I thought I'd vent about how my nice and pretty code just got a good violating when I found out constructors in a template don't politely follow along to the derived classes. So now for each of these derived classes I get to cram in a one-liner constructor that refers to the templated one. That's not the end of the world but... gah.

That's not because of templates. That's true of all types. C++0x will make things a little easier for you though via inheriting constructors.

pr0metheus
Dec 5, 2010
We are learning about pointers and I decided to write my own smart pointer class in C++! I have tested it on simple stuff and it works. Can more experienced users let me know if I'm doing anything stupid?

code:
#include <map>
 
static std::map<void*, unsigned int> counters;
 
template <class T>
class SharedPtr
{
        private:
                T * ptr;
 
        public:
                SharedPtr( )
                {
                                ptr = NULL;
                }
 
                SharedPtr( T * a )
                {
                        this->ptr = a;
                        counters[a]++;
                }
 
                SharedPtr( const SharedPtr<T> & other )
                {
                        ptr = other.ptr;
                        counters[ptr]++;
                }
 
                ~SharedPtr()
                {
                        counters[ptr]--;
                        if( counters[ptr] == 0 )
                        {
                                delete ptr;
                        }
                }
 
                T& operator*()
                {
                        return *ptr;
                }
 
};

Scaevolus
Apr 16, 2007

You need to implement the assignment operator.

litghost
May 26, 2004
Builder

pr0metheus posted:

We are learning about pointers and I decided to write my own smart pointer class in C++! I have tested it on simple stuff and it works. Can more experienced users let me know if I'm doing anything stupid?

code:
#include <map>
 
static std::map<void*, unsigned int> counters;
 
template <class T>
class SharedPtr
{
        private:
                T * ptr;
 
        public:
                SharedPtr( )
                {
                                ptr = NULL;
                }
 
                SharedPtr( T * a )
                {
                        this->ptr = a;
                        counters[a]++;
                }
 
                SharedPtr( const SharedPtr<T> & other )
                {
                        ptr = other.ptr;
                        counters[ptr]++;
                }
 
                ~SharedPtr()
                {
                        counters[ptr]--;
                        if( counters[ptr] == 0 )
                        {
                                delete ptr;
                        }
                }
 
                T& operator*()
                {
                        return *ptr;
                }
 
};

If you use this in a multi-threaded env, you will want to use atomic operations and/or guards when manipulating global state (in this case your counter list). You may also want to remove the counters entry when it hits zero, or you'll leak counts.

litghost fucked around with this message at 08:53 on Dec 5, 2010

pr0metheus
Dec 5, 2010
What do you mean by "leak counts"?

litghost
May 26, 2004
Builder

pr0metheus posted:

What do you mean by "leak counts"?

Well, the map will continue to hold (deleted-pointer,0) entries with your current design. You never actually removed them from the map. Basically you will leak sizeof(TreeNode<void*, int>) bytes for every unique pointer that comes through that smart pointer.

That Turkey Story
Mar 30, 2003

pr0metheus posted:

We are learning about pointers and I decided to write my own smart pointer class in C++! I have tested it on simple stuff and it works. Can more experienced users let me know if I'm doing anything stupid?

A few things. comparison is only fully specified with pointers when they are in the same array, in the same object, or if they are both pointing to the same object. As well, all relational operators on void* are unspecified unless the pointers are equal or if you are doing a != comparison. In particular, I'm not immediately certain if it is valid to use a map of pointers like that because I don't think the standard even guarantees that such operations on unrelated pointers are transitive (someone correct me if I'm wrong here). Either way, your map is completely unnecessary as you should be likely coupling the count in some manner with the object (either directly or indirectly).

Don't use NULL in C++, just use 0. NULL is a #define that you must include certain headers for to get and it has no functional benefit over using the constant value 0. It was helpful in C because it could have been defined as ((void*)0), but that is not the case in C++ due to changes in implicit conversion rules between void* and other pointer types.

Your constructor that takes a T* should be explicit if it is to exist at all in a smart pointer type.

Your map currently "leaks" memory. After an object is no longer referenced you are reducing the reference count to 0, however, it is still allocated in the map. You should be erasing the element from the map when the count reaches 0 (though again, you really shouldn't be using a map at all).

Your operator*() should be const. cv-qualification of a pointer does not affect the cv-qualification of a pointee.

You should define an operator ->.

You should define an assignment operator. Right now, an incorrect implicit assignment operation has been generated. If you do an assignment operation between two of your smart pointers it will compile fine but fail miserably at runtime.

Once you update your code to not use map, you will need to special case null pointers as well (right now they are "handled" in a way that will work, but exhibits odd internal behavior).

pr0metheus
Dec 5, 2010
What data structure should I consider to replace map? A hash_map?

That Turkey Story
Mar 30, 2003

pr0metheus posted:

What data structure should I consider to replace map? A hash_map?

No. You probably don't want to use a datastructure there at all. Instead, couple the reference count and the object in the same allocation (their lifetime is shared, unless you get into a more complicated smart pointer concept with "shared" and "weak" pointers). You may also have to take it a step further if you ever want to support certain conversion operations.

That Turkey Story fucked around with this message at 09:31 on Dec 5, 2010

Luminous
May 19, 2004

Girls
Games
Gains
edit: was thinking of the wrong thing.

User0015
Nov 24, 2007

Please don't talk about your sexuality unless it serves the ~narrative~!
This isn't so much a C/C++ coding question but a C/C++ IDE question. Namely, I've been learning MSVC-10.0 lately, and one thing about it really bothers me (at least). It leaves its garbage around in my local include folder such as object files, makefiles, and MSVC specific files (.dev, .layout, etc..).

How can I make MSVC clean up its act and throw that garbage in a sub-folder?

Adbot
ADBOT LOVES YOU

nielsm
Jun 1, 2009



User0015 posted:

This isn't so much a C/C++ coding question but a C/C++ IDE question. Namely, I've been learning MSVC-10.0 lately, and one thing about it really bothers me (at least). It leaves its garbage around in my local include folder such as object files, makefiles, and MSVC specific files (.dev, .layout, etc..).

How can I make MSVC clean up its act and throw that garbage in a sub-folder?

Design your project files accordingly.

Start by creating an empty project somewhere else. Set the various output file locations for the project configurations to something useful, I prefer making them relative to the solution directory. Then when you've got all of that fixed, add your source files to the project. MSVC won't pollute any other folders than those you've explicitly given then.
Also learn how to use property files to make re-usable project configuration shards.
If you want to get really advanced, look into the MSBuild project file format, it can do a whole lot of things.

Oh, and of course you can move your project and solution files around outside the IDE to put them in locations that fit your needs better. They're just text files you can edit, with a bit of care.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply