Jump to content
  • Advertisement
Sign in to follow this  

Assigning a default value to a vectorstring::size_type

This topic is 4325 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post

Link to post
Share on other sites
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 );

Share this post

Link to post
Share on other sites
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!

[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.]

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!