C++ STL type_traits问题

Kim*_*-wu 3 c++ templates stl type-traits

我正在观看最新的C9讲座并注意到一些有趣的东西......

在他对type_traits的介绍中,Stephan使用了以下(正如他所说的,做作的)示例:

template <typename T> void foo(T t, true_type)
{
    std::cout << t << " is integral";
}
template <typename T> void foo(T t, false_type)
{
    std::cout << t << " is not integral";
}

template <typename T> void bar(T t) { foo(t, typename is_integral<T>::type()); }

这看起来要复杂得多:

template <typename T> void foo(T t)
{
    if(std::is_integral<T>::value)
        std::cout << "integral";
    else
        std::cout << "not integral";
}

这样做的方法有问题吗?他的方式更好吗?为什么?

谢谢.

max*_*000 14

基本上,第一个选项在编译时使用关于类型的"完整性"的知识,第二个选项 - 将此知识移动到运行时.

这意味着我们可以使用不可编译为非整数类型的整数类型代码.


Tom*_*mek 9

下面的例子应该说明不同之处.让我们添加struct X:

struct X
{
  X(int)
  {
  }
};
Run Code Online (Sandbox Code Playgroud)

并修改一个foo如下:

template <typename T> void foo(T t, true_type)
{
    std::cout << t << " is integral";
    X x(t);
}
template <typename T> void foo(T t, false_type)
{
    std::cout << t << " is not integral";
}
Run Code Online (Sandbox Code Playgroud)

然后:

template <typename T> void bar(T t)
{
    foo(t, typename is_integral<T>::type());
}
Run Code Online (Sandbox Code Playgroud)

仍然会为所有T类型编译(包括整数类型;它可能会导致警告,但会编译).

其他等效代码:

template <typename T> void foo(T t)
{
    if(std::is_integral<T>::value)
    {
        std::cout << "integral";
        X x(t);
    }
    else
        std::cout << "not integral";
}
Run Code Online (Sandbox Code Playgroud)

往往不能编译,你将不能够实例化X的类型具有操作INT()等则积分,最终的浮点和用户定义的类(操作员短()或运营长()不会做).