在一些 std 模板函数的描述中,我看到了类似这样的内容:
if the template parameter is of integral type, the behavior is such and such.
otherwise, it is such and such.
我怎样才能做类似的测试?也许是 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
}
但是,当算法的实现极大地依赖于测试时,可以改进此解决方案。在这种情况下,我们会在函数的顶部进行测试,然后是一个大的 then
block 和一个大的 else
block 。在这种情况下,一种常见的方法是重载函数并让编译器使用 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
}
当调用algorithm
函数时,编译器将根据模板参数是否为整数“选择”正确的实现。
关于c++ - 如何检查模板的参数类型是否完整?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3458510/