问题描述
问题很简单。我有一个头文件包含保护和实现文件.impl。头文件包括实现文件。我要执行以下操作:
The problem is simple. I have a header file with include guards and a implementation file .impl. Header file includes implementation file. I want to do the following:
头文件:
template<size_t N>
class A
{
void func();
};
.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() { ... }
然而,我还是不能用 std :: enable_if
,它似乎找不到原型 func
,因为我通过更改返回类型更改函数签名。
However I am yet to be good with std::enable_if
and it seems to fail to find the prototype for func
because I change the function signature by changing the return type. How can I have different implementations while providing the user with one function for the interface.
这实际上是MCU寄存器修改器,它对两个寄存器进行操作,因为它们没有容量。我宁愿不使用任何脏偏移量基于N在函数内部,并依赖于平面结构。
This is essentially MCU register modifier that operates on two registers because one does not have the capacity. I'd rather not use any dirty offsets based on N inside the function and depend on plain structure. Also I'd rather not use helper functions which would complicate things if it is possible without them.
推荐答案
你可以委托:
#include <iostream>
template<std::size_t N>
class A
{
private:
template <std::size_t I>
typename std::enable_if<(I <= 5)>::type
f() { std::cout << "Small\n"; }
template <std::size_t I>
typename std::enable_if<(I > 5)>::type
f() { std::cout << "Big\n"; }
public:
void func() { f<N>(); }
};
int main()
{
A<1> small;
small.func();
A<10> big;
big.func();
}
如果您信任编译器优化:
And if you trust your compiler optimizations:
template<std::size_t N>
class A
{
private:
void small() { std::cout << "Small\n"; }
void big() { std::cout << "Big\n"; }
public:
void func() {
if(N <= 5) small();
else big();
}
};
这篇关于C ++ std :: enable_if在类模板中,用于成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!