C ++模板类问题中的类型条件 [英] Type condition in C++ template class problem

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

问题描述

使用GCC 4.2. 我有这个用于条件类型的元模板:

Using GCC 4.2. I have this metatemplate for conditional type:

template <bool condition, typename Then, typename Else>
struct IF
{
    typedef Then RET;
};

template <class Then, class Else>
struct IF<false, Then, Else>
{
    typedef Else RET;
};

当我像这样使用它时:

template <typename T>
class Param
{
    IF< sizeof(int)<sizeof(long), long, int>::RET  i;
};

它可以工作,但是当我像这样使用它(尝试使用模板参数)时:

it works, but when I use it like this (trying to use template parameters):

template <typename T>
class Param
{
    IF< sizeof(int)<sizeof(long), T&, T* >::RET mParam;
};

我收到此错误代码:

error: type 'IF<false, T&, T*>' is not derived from type 'Param<T>'

为什么会这样?怎么解决呢? 预先感谢!

Why is it happening? How to solve it? Thanks in advance!

推荐答案

在第二种情况下,RET是什么,取决于模板类型T.需要确保编译器在所有可能的实例化中都将是一种类型(并且可能不是IF某些实例化的静态成员).您可以使用typename关键字来实现.

In the second case, what RET is, depends on the template type T. The compiler needs to be assured that it is going to be a type in all possible instantiations (and not perhaps a static member of some instantiation of IF). You do so with the typename keyword.

template <typename T>
class Param
{
    typename IF< sizeof(int)<sizeof(long), T&, T* >::RET mParam;

};

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

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