简体   繁体   中英

Type condition in C++ template class problem

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

and when I use it like this:

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

I am getting this error code:

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

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

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;

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM