功能模板,不允许某些类型

时间:2012-08-03 15:59:53

标签: c++ templates c++11

我有一个功能模板,必须只允许某些类型。我见过其他问题,但他们使用了boost和primitve类型。在这种情况下,没有提升,它是用户定义的类。

例如:

template<typename T>
myfunc(T&)
{ ... }

template<>
myfunc(Foo&)
{
   static_assert(false, "You cannot use myfunc with Foo");
}

无论是否使用static_assert对象调用myfunc,问题都会被Foo调用。

我只是想在使用myfunc调用Foo时停止编译 我怎样才能实现这个功能?

2 个答案:

答案 0 :(得分:4)

您可以使用std::is_same

#include <type_traits>

template<typename T>
return_type myfunc(T&)
{
   static_assert(std::is_same<T, Foo>::value, "You cannot use myfunc with Foo");

   // ...
}

答案 1 :(得分:1)

返回类型为R,请说:

#include <type_traits>

template <typename T>
typename std::enable_if<!std::is_same<T, Foo>::value, R>::type my_func(T &)
{
    // ...
}

如果您真的不想使用标准库,可以自己编写特征:

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; };