1
votes

I have written a template function which takes int32, bool and int16 as an input. However for bool, I am getting this warning. Any ideas, how can I resolve it.

template<class T>
void GameControl::assignValues(char *gaff, T &output)
{
   output = T(atoi(gaff));
}

The function calls are as follows:

int32 intout;
assignValues("1234", intout);
bool boolout;
assignValues("1234", boolout);

can anyone tell, how to get rid of the warning?

EDIT: This worked, but not sure of the consequences. I just suppressed the warning.

#pragma warning( push )
#pragma warning( disable : 4101)
// Your function
#pragma warning( pop )
2
Perhaps specialize the function for bool?Some programmer dude
On an unrelated note, the atoi function is usually discouraged, as it's impossible to differ between a valid input "0" and an invalid input which results in 0 being returned. I recommend std::strtol or std::stoi instead.Some programmer dude
Why isn't this returning a value, instead of using an output "parameter"? Your code could just read int23 intout = assignValues("1234");juanchopanza
Building on the comment by @juanchopanza, for bool it would be bool boolout = assignValues("1234") != 0;Some programmer dude
This is just a dummy function I have created for the issue, the original function is already returning a value and is different, but only this functionality is causing the issue. I just want to avoid code duplicationYash Kapoor

2 Answers

3
votes

Your first job is to change the function parameter list to a const char* gaff since standard C++ does not allow the decay of a const char[N] to a char*. Ironic it is that your compiler doesn't issue a diagnostic but complains about the dubious cast!

As for that warning, you can force the issue with

output = static_cast<T>(atoi(gaff));

Most compilers then will assume that you know what you're doing. If you still get a warning, then specialise the template function for the bool case; a solution which, on balance, I think I prefer (other than the pragmatic approach of switching off the warning for that particular function):

template<>
void assignValues(const char *gaff, bool &output)
{
   output = atoi(gaff) != 0;
}
0
votes

You can fully specialize the function template for bool:

template<>
void GameControl::assignValues<bool>(char *gaff, boot &output)
{
   output = !!atoi(gaff);
}