I have some code that builds for different targets. It also has some legacy functions that take uint32_t instead of size_t - which is annoying when I want to cast size_t types to it - with the levels of warnings that we have set (lots of gcc warnings).
So here is a contrived example:
val32 = static_cast<uint32_t>(strings.size());
val64 = static_cast<uint64_t>(strings.size()); // ERROR
Depending on which arch this runs on, one of the two lines above will complain with useless cast warning (which we treat as errors). Now I know there are some ways around this like, change the code to take size_t... but, that is not my question. My question is, when this situation arises, how can I best tackle this.
I have come up with a solution - but it requires reference passing of variables:
template<typename TO, typename FROM>
TO static_cast_if_different(const FROM &value)
{
if constexpr (std::is_same_v<TO, FROM>)
return value;
else
return static_cast<TO>(value);
}
Now this works, but I feel there is a better way (perhaps built in to the standard - or an improvement of what I have done here)?
See the full example code here: https://godbolt.org/z/87hao1aTb
full list of warning flags for gcc: -Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wunreachable-code -Wlogical-op -Wshadow -Wmissing-include-dirs -Wparentheses -Wmisleading-indentation -Werror -Wno-psabi -Wno-error=deprecated-declarations -Wnon-virtual-dtor -Wuseless-cast -Wduplicated-cond -Wnull-dereference
Note: I don't want to remove the useless-cast warning flag as that is useful else where