【发布时间】:2017-10-31 20:11:00
【问题描述】:
我有一个模板类,它有一个方法,模板参数指示该方法的输入和输出,如下所示:
template <typename In, typename Out>
class Foo
{
Out fn(const In& in)
{
Out out;
return out;
}
}
所以我尝试了这个,但是当尝试将void 用于In 或Out 时会出现错误(可能很明显)。所以我尝试添加多个方法,这些方法是这个主题的变体,希望它们的替换能够启用相关功能并禁用无效功能:
template <std::enable_if_t<std::is_void<InputType>::value>* = nullptr>
OutputType fn()
{
OutputType out;
return out;
}
template <std::enable_if<(!std::is_void<OutputType>::value) && (!std::is_void<InputType>::value)>* = nullptr>
OutputType fn(InputType& t)
{
OutputType out;
return out;
}
template <std::enable_if<std::is_void<OutputType>::value>* = nullptr>
void fn(InputType& t)
{}
这让我回到“无效引用无效”领域,或者签名冲突。
我应该如何优雅地处理这些情况,以便从模板中只创建以下签名之一:
/*In == void && Out != void*/
Out fn(/* no input here to keep compiler happy*/) { return Out; }
/*In != void && Out != void, standard case*/
Out fn(const In& in) { return Out; }
/*In != void && Out == void*/
void fn(const In& in) { /* No returns here to keep compiler happy*/; }
【问题讨论】:
-
你可以make the variant with the multiple templated methods work。但我不建议你走这条路。
标签: c++ templates c++14 sfinae