I have a sanitization function that I want to run on (traditional) pointer types only.
My problem is with function templates I can get as far as limiting the function to only pointers, however because of casting rule differences between function pointers and regular pointers, I run into problems.
The Sanitize()
function needs to run against a whole slew of types, some of which are pointers and need to be sanitized, others of which are function pointers of varying arity and parameter types and should not be sanitized, and some of which are non-pointer data types which also should not be sanitized.
Anything obvious I'm missing?
template<typename T>
T* Sanitize(T* value)
{
return (T*)SanitizePointer(value); //SanitizePointer returns void*, so cast is necessary
}
template<typename T>
T Sanitize(T value)
{
return value; //Non-pointers can be passed without sanitization
}
int main()
{
int a;
int* b;
int (*c)();
Sanitize(a);
Sanitize(b);
Sanitize(c); //<- ERROR
return 0;
}
Am I missing something? The following code compiles fine ( on VS2008)
While this problem could be solved manually, its easiest to utilize Boosts type traits and SFINAE helper to selectively disable the overload for pointers if
T*
is a function pointer:How about this? Tested online using Comeau C/C++.
As an explanation: you are trying to create a partial specialization of a function template. C++ just doesn’t allow that, full stop. Partial specializations only exist for class templates.
gf has posted the solution: use SFINAE (preferably via Boost).
I met similar problem in g++. I solved on a standard way, but I knew the possible function signatures. What I did, I created some template specialization for the possible function pointers.
Output:
I hope I could help...