如何在C++中创建条件typedef
How to make a conditional typedef in C++
我正在尝试这样做:
#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 "("
如何正确地生成条件typedef?
使用C++11中的std::conditional
元函数。
#include <type_traits> //include this
typedef std::conditional<sizeof(int) <= 4,
std::mt19937,
std::mt19937_64>::type Engine;
注意,如果您在sizeof
中使用的类型是模板参数,比如T
,那么您必须将typename
用作:
typedef typename std::conditional<sizeof(T) <= 4, // T is template parameter
std::mt19937,
std::mt19937_64>::type Engine;
或者使Engine
依赖于T
为:
template<typename T>
using Engine = typename std::conditional<sizeof(T) <= 4,
std::mt19937,
std::mt19937_64>::type;
这是灵活,因为现在您可以将其用作:
Engine<int> engine1;
Engine<long> engine2;
Engine<T> engine3; // where T could be template parameter!
使用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
如果您没有可用的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;
}
这将在我的系统上打印损坏的foo
的名称,因为这里的int
是4个字节。
相关文章:
- 如何在C++中创建争用条件
- 为什么此代码不创建争用条件?
- 如何在不使用宏的情况下在宏中创建条件
- 如何在 python 交易模型中创建功能时间条件
- 有没有办法创建一个花哨的迭代器和相应的新数组,以便检查每个索引的索引值的条件?
- 需要帮助创建一个休眠条件的循环,当满足条件时,它会停止,直到下一个操作
- 根据模板参数条件 C++17 创建成员别名
- 在c++中有条件地创建一个对象
- 当条件更改时,在 while 循环内创建新结构
- boost::进程间消息队列创建时的竞争条件
- 当在Web浏览器上输入某些内容时,可以创建条件
- 竞争条件:一个线程创建静态对象,另一个线程在初始化完成之前使用它.如何处理
- 如何使用字符串创建条件
- 在 C++ 中的 if 条件中创建的对象的范围
- Q等待条件,手动复位除外?(或者在Qt Concurrent之外创建QFuture对象?)
- 在条件c++语句中创建对象
- C++:创建循环条件的 int 数组时出现问题
- 只有在结构实例的构造函数中满足条件时,才能创建该实例
- 如何在C++中创建条件typedef
- 创建条件变量的共享指针时出现问题