我有一段C++代码
auto returnvalue = m_func(x, y, z); 其中m_func的类型取决于模板参数。然后,我处理returnvalue,它工作得很好,直到m_func是一个返回空的函数。但我需要一个机制来调用
m_func(x,y,z)如果m_func的返回值为空,而上面的版本不为空。总的来说,在伪代码中,它需要看起来像这样
if ( returnvalue of m_func is void )
call m_func directly
else
auto retval = m_func(...)
handle the return value如何使用C++11/14来完成这些工作?
编辑:
m_func可以是:
void func(type1 arg1, type2 arg, ...) 或
std::tuple<...> func(type1 arg1, type2 arg, ...) 发布于 2019-10-01 00:13:41
虽然C++17有if constexpr来简单地处理它,但C++11/C++14必须使用一些重载来通过SFINAE或标记分派或专门化来处理它,下面是一个标记分派版本:
void internal_impl(std::true_type/*, ... */) {
m_func(x, y, z);
}
void internal_impl(std::false_type/*, ... */) {
auto value = m_func(x, y, z);
foo(value);
}
void internal(/*... */) {
internal_impl(std::integral_constant<bool,
std::is_void<decltype(m_func(x, y, z))>::value>{}
/*, ...*/);
}发布于 2019-09-30 23:55:12
在C++17之前,您可以使用模板专门化:
template<class R>
struct handle {
template<class F>
static void the_return_value(F m_func) {
auto retval = m_func(x, y, z);
// handle the return value
}
};
template<>
struct handle<void> {
template<class F>
static void the_return_value(F m_func) {
m_func(x, y, z);
}
};
// usage
using R = decltype(m_func(x, y, z));
handle<R>::the_return_value(m_func);在C++17中,您可以改用if constexpr:
using R = decltype(m_func(x, y, z));
if constexpr (std::is_void_v<R>) {
m_func(x, y, z);
} else {
auto retval = m_func(x, y, z);
// handle the return value
}https://stackoverflow.com/questions/58171101
复制相似问题