首页 > 解决方案 > C++ 编译代码取决于 auto 的具体类型

问题描述

我有一段 C++ 代码

auto returnvalue = m_func(x, y, z); 

其中 m_func 的类型取决于模板参数。之后我处理returnvalue哪个工作正常,直到m_func一个函数返回 void。但我需要一种机制来调用

m_func(x,y,z)

如果 m_func 的返回值为 void 而上述版本不是。总的来说,在伪代码中它需要看起来像

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, ...) 

标签: c++

解决方案


在 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
}

推荐阅读