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

Mar*_*dik 87 c++ c++11

我想做这样的事情:

#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;
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

error: missing binary operator before token "("
Run Code Online (Sandbox Code Playgroud)

我怎样才能正确地创建条件typedef?

Naw*_*waz 135

使用std::conditionalC++ 11中的元函数.

#include <type_traits>  //include this

typedef std::conditional<sizeof(int) <= 4,
                         std::mt19937,
                         std::mt19937_64>::type Engine;
Run Code Online (Sandbox Code Playgroud)

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

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

Engine依赖于T:

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

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

Engine<int>  engine1;
Engine<long> engine2;
Engine<T>    engine3; // where T could be template parameter!
Run Code Online (Sandbox Code Playgroud)

  • +1 Minor nitpick:检查`sizeof(int)<= 4`可能不是一种非常便携的方式,因为在64位Windows机器上,GCC(MinGW)x64编译器给出`sizeof(int)= sizeof(long)= 4`.更好的方法是`sizeof(void*)<= 4`. (4认同)
  • @Nawaz:当然不是:)我的意思是第一个代码片段中的`std :: conditional <sizeof(void*)<= 4,std :: mt19937,std :: mt19937_64>`. (2认同)

Rap*_*ptz 34

使用std::conditional你可以这样做:

using Engine = std::conditional<sizeof(int) <= 4, 
                               std::mt19937, 
                               std::mt19937_64
                               >::type;
Run Code Online (Sandbox Code Playgroud)

如果你想做一个typedef,你也可以这样做.

typedef std::conditional<sizeof(int) <= 4, 
                         std::mt19937, 
                         std::mt19937_64
                         >::type Engine
Run Code Online (Sandbox Code Playgroud)

  • 当您正确缩进代码时,您将获得+1!:) (2认同)

Jas*_*n R 6

如果您没有可用的C++ 11(虽然您计划使用它时会出现这种情况std::mt19937),那么您可以使用Boost元编程库(MPL)在没有C++ 11支持的情况下实现相同的功能.这是一个可编辑的例子:

#include <boost/mpl/if.hpp>
#include <iostream>
#include <typeinfo>

namespace mpl = boost::mpl;

struct foo { };
struct bar { };

int main()
{
    typedef mpl::if_c<sizeof(int) <= 4, foo, bar>::type Engine;

    Engine a;
    std::cout << typeid(a).name() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这将foo在我的系统上打印出受损的名称,int此处为4个字节.