c++ - 编写一个使用 int 或 enum 参数的函数

标签 c++ templates enable-if

我正在尝试编写一个可以采用任何形式的 int 或 enum 的函数。 我尝试提供两个版本:

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 的例子似乎只是打印出文本,而不是做一些有用的事情,比如控制模板的生成。

我发现 union 会做我想做的一部分

<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| 

最佳答案

您可能正在寻找 enable_if结合type traits :

template <typename T>
typename std::enable_if<std::is_enum<T>{} || std::is_integral<T>{}, int>::type
 bit_num (T t);

如果参数是枚举或整数类型,则此函数将仅作为重载决策的候选对象。

您尝试在问题中设置的 typedef 可以使用辅助特征来实现:

template <typename T> struct identity {using type=T;};

用法是

using int_T = typename std::conditional<std::is_enum<T>{}, 
                                        std::underlying_type<E>,
                                        identity<E>>::type::type;

关于c++ - 编写一个使用 int 或 enum 参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28373417/

相关文章:

c++ - g++: 没有那个文件或目录?

c++ - 如何根据 operator() 参数泛化一个类?

c# - C# 中的模板函数 - 返回类型?

c++ - 如果 vector 是特定长度,则使用 C++11 std::enable_if 启用成员函数

c++ - 无法使用enable_if和is_base_of来区分模板特化

c++ - 需要帮助清理斐波那契数列请使用 C++

C++ 可以不继承成员吗?

c++ - 变量模板特化

c++ - 当函数不存在时 SFINAE 回退

c++ - 为什么没有 InterlockedExchange Subtract 64?