C ++ STL type_traits问题 [英] C++ STL type_traits question

查看:174
本文介绍了C ++ STL type_traits问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



Stephan使用下面的,contrived)example:

  template < typename T>  void foo(T t,true_type)
{
std :: cout<< t<< 是整体;
}
模板< typename T> void foo(T t,false_type)
{
std :: cout ;& t<< 不是整数;
}



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



这似乎比: >

 模板< typename T>  void foo(T t)
{
if( std :: is_integral< T> :: value
std :: cout< 积分;
else
std :: cout<< 不整合;
}



后一种做法有什么问题吗?他的方式更好吗?为什么?



感谢。

解决方案

区别。让我们添加struct X:

  struct X 
{
X(int)
{
}
};

并修改一个foo,如下所示:

  template< typename T> void foo(T t,true_type)
{
std :: cout< t<< 是整体;
X x(t);
}
template< typename T> void foo(T t,false_type)
{
std :: cout< t<< 不是整数;
}

然后:

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

仍然会为所有T类型(包括整数类型)编译;但会编译)。



其他等效代码:

 模板< typename T> void foo(T t)
{
if(std :: is_integral< T> :: value)
{
std :: cout< 积分;
X x(t);
}
else
std :: cout<< 不整合;
}

通常无法编译,因为您无法实例化X其他然后整数和最终的浮点和用户定义的类有operator int()(operator short()或operator long()不会做)。


I was watching the latest C9 lecture and noticed something interesting..

In his introduction to type_traits, Stephan uses the following (as he says, contrived) example:

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()); }

This seems to be far more complicated than:

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

Is there something wrong with the latter way of doing it? Is his way better? Why?

Thanks.

解决方案

The example below should illustrate the difference. Let's add struct X:

struct X
{
  X(int)
  {
  }
};

and modify one foo as below:

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";
}

Then:

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

Will still compile for all T types (including integer types; it may cause warning but will compile).

The other equivalent code:

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

will often fail to compile as you will not be able to instantiate X for types other then integral and eventually floating point and user defined classes which have operator int() (operator short() or operator long() will not do).

这篇关于C ++ STL type_traits问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆