Reputation: 3716
I start apologising if I am stupid enough to not find the answer if it is so obvious.
I have seen dozens of pages talking about having specific template specialization for pointer parameters.
I'd like to be able, though, of preventing a template to specialize pointer parameters, but I can't figure out how to do this.
template< class T >
void function( T arg )
{
//...
}
int main( )
{
int i = 42;
function( i ); // Ok
function( &i ); // Die bastart with a compiler error!
}
Is it possible?
Thanks.
Upvotes: 9
Views: 2900
Reputation: 45948
I'm myself a template metaprogramming rookie, but I think
template<typename T>
void function(typename std::enable_if<!std::is_pointer<T>::value,T>::type arg)
{
//...
}
should work, as this function should only exist for non-pointer parameters. Of course this requires C++11 or at least TR1 or boost's type traits facilities.
Upvotes: 7
Reputation:
In C++11, you can use static_assert
in a way like this:
template<class T>
void func(T arg) {
static_assert(!std::is_pointer<T>::value,
"The argument to func must not be a pointer.");
// Do something after the static_assert.
// Now you are sure that T isn't a pointer.
}
An example can be found here on Ideone.
I recommend this because it will give more useful error messages when somebody tries to call your function with a pointer (linker errors can be very confusing in this case). Also, linker errors will not show up before linkage occurs.
Upvotes: 14
Reputation: 133082
You can declare the specialization(in this case it's technically just an overload) but not define it :)
template<typename T >
void function( T arg )
{
//...
}
template<typename T >
void function( T* arg ); //no definition
int main()
{
int i = 42;
function( i ); // Ok
function( &i ); //ERROR
}
Upvotes: 15