What exactly are functions...

Was playing around with boost multi-threading (storing all files in a folder and it's sub-folders in a vector) and while I understand the core concepts there was one thing that I didn't quite get (and didn't' find online documentation for). Take below code snippet...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
#include <vector>
using namespace std;
using namespace boost;
using namespace boost::this_thread;
using namespace boost::filesystem;

boost::mutex mute; 
vector<path> files;
void getFiles( const path & dir_path)           
	{
		if ( !exists( dir_path ) ) { 
			return;
		}
		directory_iterator end_itr;
		for ( directory_iterator itr( dir_path );itr != end_itr;itr++ )
		{
			/*if a directory then loop through it recursively*/
			if(!is_directory(itr->status())) {
				mute.lock();
				files.push_back(itr->path());
				mute.unlock();
			} else {
				boost::thread t(&getFiles,itr->path());
			}
		}
		return;
	}

int main()
{
	
	boost::thread t(&getFiles,"C:/cygwin/usr/");
	return 0;
}


What does &getFiles mean exactly?
Last edited on
It is used get a pointer to the getFiles function.
But why not just getFiles?
Ah I see. A bit like a goto?
You could write just getFiles, the compiler would generate a pointer to that function if it can't find a way to use the reference. It's very much like how pointers are constructed from arrays sometimes.
Last edited on
For those interested here is a good example of how functions can be passed just like params. The format is:

return type (pointer to function)(param types delimited by comma).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdafx.h"
#include <iostream>

void functionThatTakesAFunctionAsParam(void (*address)(int,char),int Integer, char Char) {
	address(Integer,Char);
}


void t(int Integer, char Char) {
	std::cout << "int:" << Integer << " char:" << Char;

}
int main()
{
	functionThatTakesAFunctionAsParam(&t,5,'h');
	std::cin.get();
	return 0;
}
You could also pass-by-reference if you like
1
2
3
4
5
6
7
void functionThatTakesAFunctionAsParam(void (&ref)(int,char),int Integer, char Char) {
	ref(Integer,Char);
}

...

        functionThatTakesAFunctionAsParam(t,5,'h');
Topic archived. No new replies allowed.