这样做的方式std::enable_if是以某种形状或形式使用.然后将支持类型的选择器用作返回类型.例如:
template <typename T> struct is_supported { enum { value = false }; };
template <> struct is_supported<int> { enum { value = true }; };
template <> struct is_supported<float> { enum { value = true }; };
template <> struct is_supported<double> { enum { value = true }; };
template <typename T>
typename std::enable_if<is_supported<T>::value, T>::type
restricted_template(T const& value) {
return value;
}
Run Code Online (Sandbox Code Playgroud)
显然,你想给这些特征一个更好的名字is_supported.std::enable_if是C++ 2011的一部分,但如果您使用的标准库不可用,它很容易实现或从boost获得.
通常,由于模板实现通常具有隐式限制,因此通常不必强加显式限制.但是,有时禁用或启用某些类型会很有帮助.