C++ std :: enable_if在类模板中,用于成员函数

Eth*_*one 1 c++ templates c++11

问题很简单.我有一个带有包含警卫的头文件和一个实现文件.impl.头文件包括实现文件.我想做以下事情:

头文件:

template<size_t N>
class A
{
  void func();
};
Run Code Online (Sandbox Code Playgroud)

.impl文件:

template<size_t N>
typename std::enable_if<(N <= 5), void>::type A<N>::func() { ... }

template<size_t N>
typename std::enable_if<(N > 5), void>::type A<N>::func() { ... }
Run Code Online (Sandbox Code Playgroud)

然而,我还没有好,std::enable_if并且似乎找不到原型,func因为我通过更改返回类型来更改函数签名.如何为用户提供一个界面功能,我可以有不同的实现.

这本质上是MCU寄存器修改器,它在两个寄存器上运行,因为一个寄存器没有容量.我宁愿不在函数内使用基于N的任何脏偏移,而是依赖于普通结构.另外,我宁愿不使用辅助函数,如果没有它们,可能会使事情复杂化.

小智 7

您可以使用标签调度:

template <size_t N>
class A
{
    void func()
    {
        do_func(std::integral_constant<bool, (N > 5)>{});
    }

    void do_func(std::true_type) { /* handles the N > 5 case */ }
    void do_func(std::false_type) { /* handles the N <= 5 case */ }
};
Run Code Online (Sandbox Code Playgroud)