在一些std模板函数的描述中,我看到了类似的东西:
如果模板参数是整数类型,则行为是这样的.
否则,就是这样等等.
我怎么做类似的测试?也许dynamic_cast?
由于我写的功能仅供我个人使用,我可以依靠自己只提供正确的参数,但为什么错过学习的机会呢?:)
除了其他答案之外,应该注意的是,测试可以在运行时使用,也可以在编译时使用,以根据类型是否完整来选择正确的实现:
运行时版本:
// Include either <boost/type_traits/is_integral.hpp> (if using Boost)
// or <type_traits> (if using c++1x)
// In the following, is_integral shoudl be prefixed by either boost:: or std::
template <typename T>
void algorithm(const T & t)
{
// some code
if (is_integral<T>::value)
{
// operations to perform if T is an integral type
}
else
{
// operations to perform if T is not an integral type
}
// some other code
}
Run Code Online (Sandbox Code Playgroud)
但是,当算法的实现很大程度上依赖于测试时,可以改进此解决方案。在这种情况下,我们将在函数顶部进行测试,然后是一个大块then和一个大块else。在这种情况下,一种常见的方法是重载函数并使编译器使用 SFINAE 选择正确的实现。一个简单的方法是使用boost::enable_if:
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>
template <typename T>
typename boost::enable_if<boost::is_integral<T> >::type
algorithm(const T & t)
{
// implementation for integral types
}
template <typename T>
typename boost::disable_if<boost::is_integral<T> >::type
algorithm(const T & t)
{
// implementation for non integral types
}
Run Code Online (Sandbox Code Playgroud)
调用该algorithm函数时,编译器将根据模板参数是否为整数来“选择”正确的实现。