Implicit Conversion Avoidance for Non-Constructing Functions
Consider a non-constructing function that expects an integer parameter but allows implicit casting from other types such as characters, booleans, and longs. To prevent this unintended behavior and ensure that the function only accepts parameters of the specified type, we can employ the following techniques:
C 11 and Later Method:
The most direct approach is to define a function template that matches all other types:
void function(int); // this will be selected for int only template <class T> void function(T) = delete; // C++11
This works because non-template functions with direct matching take precedence.
Pre-C 11 Technique:
Prior to C 11, an alternative solution involved creating a helper class to enforce the desired behavior:
// because this ugly code will give you compilation error for all other types class DeleteOverload { private: DeleteOverload(void*); }; template <class T> void function(T a, DeleteOverload = 0); void function(int a) {}
This technique relies on overloading multiple functions with similar signatures, where the function with the expected type takes precedence.
C 23 Update:
C 23 introduces a more concise and informative way to handle this situation:
void function(int) {} // this will be selected for int only template <class T> void function(T) { // since C++23 static_assert(false, "function shall be called for int only"); }
Using static_assert within a function template provides a clear error message when calling the function with an unexpected parameter type.
The above is the detailed content of How Can I Prevent Implicit Conversions in Non-Constructing Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!