如何使用SFINAE启用返回“自动"的成员函数 [英] how to SFINAE for enabling member function returning `auto`
问题描述
在模板元编程中,可以对返回类型使用SFINAE来选择某个模板成员函数,即
In template meta programming, one can use SFINAE on the return type to choose a certain template member function, i.e.
template<int N> struct A {
int sum() const noexcept
{ return _sum<N-1>(); }
private:
int _data[N];
template<int I> typename std::enable_if< I,int>::type _sum() const noexcept
{ return _sum<I-1>() + _data[I]; }
template<int I> typename std::enable_if<!I,int>::type _sum() const noexcept
{ return _data[I]; }
};
但是,如果有问题的函数(在上面的示例中为_sum()
)具有自动检测到的返回类型(例如在此示例中为_func()
),则此方法将不起作用
However, this won't work if the function in question (_sum()
in above example) has auto-detected return type, such as _func()
in this example
template<int N> class A
{
/* ... */
private:
// how to make SFINAE work for _func() ?
template<int I, typename BinaryOp, typename UnaryFunc>
auto _func(BinaryOp op, UnaryFunc f) const noexcept -> decltype(f(_data[0]))
{ return op(_func<I-1>(op,f),f(_data[I])); }
};
要在这里获得SFINAE还可以做些什么?
What else can be done to get SFINAE here?
推荐答案
在DavidRodríguez-dribeas之后,以下代码按预期工作:
Following David Rodríguez - dribeas, the following code worked as intended:
template<int N> class A
{
int min_abs() const noexcept
{
return _func<N-1>([](int x, int y)->int { return std::min(x,y); },
[](int x)->int { return std::abs(x); });
}
private:
int _data[N];
template<int I, typename BinaryOp, typename UnaryFunc>
auto _func(BinaryOp op, UnaryFunc f) const noexcept
-> typename std::enable_if< I>,decltype(f(_data[0]))>::type
{ return op(_func<I-1>(op,f),f(_data[I])); }
template<int I, typename BinaryOp, typename UnaryFunc>
auto _func(BinaryOp op, UnaryFunc f) const noexcept
-> typename std::enable_if<!I>,decltype(f(_data[0]))>::type
{ return f(_data[I]); }
};
严格来说,我们还必须确保二进制运算符op
返回正确的类型.为了使答案简洁明了,我将其留给读者自己弄清楚...
strictly speaking, we must also ensure that the binary operator op
returns the correct type. For simplicity and brevity of the answer, I leave that for the reader to figure out ...
这篇关于如何使用SFINAE启用返回“自动"的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!