有没有办法只在函数声明处编写这样的复杂返回类型?
template<typename Xa_t, typename Ya_t, typename Xb_t>
auto interpolate(const Func<Xa_t, Ya_t> & f, const std::vector<Xb_t> & vec) ->
Func<std::common_type_t<Xa_t, Xb_t>,
std::conditional_t<std::is_floating_point<Ya_t>::value,
Ya_t,
float
>
>;
如果我想在声明函数后定义该函数,我也必须将返回类型粘贴到那里,从而在整个代码中创建大量冗余。
我对 c++11 和 c++14 方式都持开放态度。 (首选 MSVC)
我猜想使用预处理器宏可以实现类似的结果,但不知道如何做到这一点。
最佳答案
假设使用 C++11,解决方法是使用 alias template ,例如您的情况:
template<typename Xa_t, typename Ya_t, typename Xb_t>
using interpolate_return_type = Func<
std::common_type_t<Xa_t, Xb_t>,
std::conditional_t<std::is_floating_point<Ya_t>::value,
Ya_t,
float
>
>;
然后您可以在声明和定义中使用此别名模板:
template<typename Xa_t, typename Ya_t, typename Xb_t>
interpolate_return_type<Xa_t, Ya_t, Xb_t> interpolate(const Func<Xa_t, Ya_t> & f, const std::vector<Xb_t> & vec);
/* ... stuff ...*/
template<typename Xa_t, typename Ya_t, typename Xb_t>
interpolate_return_type<Xa_t, Ya_t, Xb_t>
interpolate(const Func<Xa_t, Ya_t> & f, const std::vector<Xb_t> & vec) {
/* more stuff */
}
关于c++ - 如何避免在函数定义时重复长后缀返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32460933/