c++ - 如何检查模板的参数类型是否完整?

标签 c++ templates

在一些 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/

相关文章:

c++ - cdb.exe 位于 Visual Studio 2013 中的什么位置?

c++ - 将文本文件中的数据提取到结构中

c++ - 如果模板模板参数是 vector ,则需要不同的行为

c++ - 成员数量可变的结构或类

c++ - gcc 中的模糊重载,适用于 msvc

c++ - qt-通过线程更新用户界面

c++ - C++ 中 cin.fail() 的含义?

c++ - C++静态数据成员的实现

c++ - 将可能的左值引用模板转换为左值

c++ - 模板元编程是否比等效的 C 代码更快?