我正在尝试这样做:
#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 "("
我怎样才能正确地创建条件类型定义函数呢?
发布于 2013-07-25 17:45:05
使用std::conditional
,你可以这样做:
using Engine = std::conditional<sizeof(int) <= 4,
std::mt19937,
std::mt19937_64
>::type;
如果你想做一个typedef
,你也可以这样做。
typedef std::conditional<sizeof(int) <= 4,
std::mt19937,
std::mt19937_64
>::type Engine
发布于 2013-07-25 20:35:26
如果您没有可用的C++11 (尽管如果您计划使用std::mt19937
,则似乎有),那么您可以使用Boost Metaprogramming Library (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;
}
这将在我的系统上打印出损坏的foo
名称,因为这里的int
是4个字节。
https://stackoverflow.com/questions/17854407
复制相似问题