如何在C ++中创建一个条件typedef [英] How to make a conditional typedef in C++

查看:140
本文介绍了如何在C ++中创建一个条件typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

#include <iostream>
#include <random>

typedef int Integer;

#if sizeof(Integer) <= 4
    typedef std::mt19937     Engine;
#else
    typedef std::mt19937_64  Engine;
#endif

int main()
{
    std::cout << sizeof(Integer) << std::endl;
    return 0;
}

但我收到此错误:

error: missing binary operator before token "("



How can I correctly make the conditional typedef?

推荐答案

使用 std :: conditional 来自C ++ 11的元函数。

Use the std::conditional meta-function from C++11.

#include <type_traits>  //include this

typedef std::conditional<sizeof(int) <= 4,
                         std::mt19937,
                         std::mt19937_64>::type Engine;

请注意,如果您在 sizeof 中使用的类型是模板参数,请说 T ,那么您必须使用 typename as:

Note that if the type which you use in sizeof is a template parameter, say T, then you have to use typename as:

typedef typename std::conditional<sizeof(T) <= 4, // T is template parameter
                                  std::mt19937,
                                  std::mt19937_64>::type Engine;

或使 Engine 依赖 T as:

template<typename T>
using Engine = typename std::conditional<sizeof(T) <= 4, 
                                         std::mt19937,
                                         std::mt19937_64>::type;

这是灵活,因为现在你可以使用它:

That is flexible, because now you can use it as:

Engine<int>  engine1;
Engine<long> engine2;
Engine<T>    engine3; // where T could be template parameter!

这篇关于如何在C ++中创建一个条件typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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