I know you can use C++ keyword ‘explicit’ for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion of parameters for a class method?
I have two class members, one which takes a bool as a param, the other an unsigned int. When I called the function with an int, the compiler converted the param to a bool and called the wrong method. I know eventually I’ll replace the bool, but for now don’t want to break the other routines as this new routine is developed.
No, you can’t use explicit, but you can use a templated function to catch the incorrect parameter types.
With C++11, you can declare the templated function as
deleted. Here is a simple example:This gives the following error message if you try to call
Thing::Foowith asize_tparameter:In pre-C++11 code, it can be accomplished using an undefined private function instead.
The disadvantage is that the code and the error message are less clear in this case, so the C++11 option should be selected whenever available.
Repeat this pattern for every method that takes the
boolorunsigned int. Do not provide an implementation for the templatized version of the method.This will force the user to always explicitly call the bool or unsigned int version.
Any attempt to call
Methodwith a type other thanboolorunsigned intwill fail to compile because the member is private, subject to the standard exceptions to visibility rules, of course (friend, internal calls, etc.). If something that does have access calls the private method, you will get a linker error.