Assigning a default value to a vectorstring::size_type

Started by
1 comment, last by jouley 17 years, 2 months ago
Hello, I have a fairly obvious question, but it seems I am tired and can't find the answer. I just want to assign a default value to i to be 0, if I omnit to put a third argument in my function. The code:

bool key(const map<string, vector<string> >::const_iterator& iter, const string& key, vector<string>::size_type&)
{
	for (i = 0; i != iter->second.size(); ++i) {
		if (comparestring(iter->second.substr(0, key.size()), key))
			return 1;
	}

	return 0;
}

bool key(const std::map<std::string, std::vector<std::string> >::const_iterator&, const std::string&, std::vector<std::string>::size_type& = 0); //Function in header file


The trouble is the function header, when I use "vector<string>::size_type&" as a parameter, it works, but with "vector<string>::size_type& = 0" I just give an error. The error is: impossible to convert from 'int' in '__w64 unsigned int &'. Thanks to anyone who can help.
Advertisement
I think you have to change it to a const reference.

You cannot bind a temporary to a non-const reference, which is how default parameters are probably implemented.

This compiles for me ( under GCC ):
void foo( const std::vector< std::string >::size_type & = 0 );
The error says exactly what you need to know: you can't give a reference a default value. Since you're passing the size_type by reference, the argument can be changed inside of the function, and the changes will be reflected in the variable that was passed in. If there is no variable passed in, then what's there to change?

Your three options, as I see it, are as follows:
1) Don't pass by reference.
2) Don't have a default argument.
3) Do the following, which I don't think anybody actually recommends as a viable option:
//  When calling the function...bool bAnswer = key(mapIter, strKey, vector<string>::size_type(0));

The last option fools the compiler. Fooling the compiler is usually not a good idea, as it's there for your protection... [wink]

On a slightly different topic, what is that parameter used for, anyway?

Best of luck!
-jouley

[Edit: Zinged by rip-off. Using const works because you guarantee to the compiler that you won't change it, so it doesn't worry about having any external effects.]

This topic is closed to new replies.

Advertisement