Reputation: 944
I have a function template that must be allow only certain types. I've seen other questions but they used boost and primitve types. In this case, no boost, and it's a user defined class.
Ex:
template<typename T>
myfunc(T&)
{ ... }
template<>
myfunc(Foo&)
{
static_assert(false, "You cannot use myfunc with Foo");
}
Problem is static_assert
gets called regardless of whether I call myfunc
with a Foo
object or not.
I just want some way for compile to stop when myfunc
is called with Foo
.
How can I achieve this functionality?
Upvotes: 4
Views: 745
Reputation: 476990
With a return type R
, say:
#include <type_traits>
template <typename T>
typename std::enable_if<!std::is_same<T, Foo>::value, R>::type my_func(T &)
{
// ...
}
If you really don't want to use the standard library, you can write the traits yourself:
template <bool, typename> struct enable_if { };
template <typename T> struct enable_if<true, T> { typedef T type; };
template <typename, typename> struct is_same { static const bool value = false; };
template <typename T> struct is_same<T, T> { static const bool value = true; };
Upvotes: 1
Reputation: 234424
You can use std::is_same
for this:
#include <type_traits>
template<typename T>
return_type myfunc(T&)
{
static_assert(std::is_same<T, Foo>::value, "You cannot use myfunc with Foo");
// ...
}
Upvotes: 4