我想做这样的事情:
#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)
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)
如果您没有可用的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个字节.
| 归档时间: |
|
| 查看次数: |
12746 次 |
| 最近记录: |