如何在C ++中创建一个条件typedef

如何在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!