我试图写一个函数,将采取任何形式的int或枚举。 我试过提供两个版本:编写一个函数,使用INT或枚举参数
template<typename E>int bit_num (const E bitPatA)
template<typename E>int bit_num (enum bitPatA)
枚举版本不编译。
我发现is_enum和enable_if但一直未能拿出一个咒语做到以下几点:
template <typename E>int bit_num <E bitPatA)
{
if is_enum typedef typename std::underlying_type<E>::type int_T;
if !is_enum typedef E int_T;
...
}
所有is_enum的案例似乎刚刚打印出的文本,而不是像做有用控制模板的生成。
我发现,工会会做什么,我想要做的
<template E>int bit_num (E bitPatA)
{
union {uintmax_t i; enum e;} bitpat;
bitPat.i = 0; // clear cruft
bitPat.e = bitPatA; // load from enum
// use from int
if ((bitPat.i == 0) || ((bitPat.i & ~(bitPat.i - 1)) != bitPat.i)) return -1;
...
}
一部分,但是这并没有让我得到底层那种为int。
我想探索各种大小的编译器优化。
[代码和注释错误]
using namespace std;
int bit_num (const enum bitPatA)
{
return -1;
}
template <typename T>
struct identity
{
using type=T;
};
template <typename E>
typename enable_if< /* is_enum<E>{} ||*/ is_integral<E>{}, int>::type
bit_num (const E bitPatA)
{
return -1;
}
误差
||=== Build: Debug in Bit_num (compiler: GNU GCC Compiler) ===| /home/jfw/Documents/Bit_num/BitTools.cpp|13|error: use of enum ‘bitPatA’ without previous declaration|
如果您告诉我们错误,并创建一个[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)向我们展示如何使用这些函数,那么我们将会更好来帮你。 – 2015-02-06 19:40:28
如果您使用的是C++ 11,那么您可以尝试查看['static_assert'](http://en.cppreference.com/w/cpp/language/static_assert)和[''](http:/ /en.cppreference.com/w/cpp/header/type_traits)限制生成 –
Conduit
2015-02-06 19:43:48
@Joachim using namespace std; int bit_num(const enum bitPatA){return -1; } template struct identity {using type = T;}; 模板 类型名称enable_if * is_enum {} || */is_integral {},int>的::类型Bit_Num说(常量ËbitPatA) { 返回-1; }错误是|| ===构建:Bit_num中的调试(编译器:GNU GCC编译器)=== | /home/jfw/Documents/Bit_num/BitTools.cpp|13|error:使用没有预先声明的枚举'bitPatA'| –
jfwfmt
2015-02-07 00:31:24