【问题标题】:C++ compile code depending on the concrete type of autoC++ 编译代码取决于 auto 的具体类型
【发布时间】:2019-09-30 15:35:36
【问题描述】:

我有一段 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++


【解决方案1】:

而 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>{}
                  /*, ...*/);
}

【讨论】:

  • 我必须在std::integral_constant&lt;bool, std::is_void&lt;decltype(m_func(x, y, z))&gt;::value&gt; 中添加一个{} ,然后它就像一个魅力,我们的非C++ 程序员仍然可以阅读。
  • 缺少{} 已添加。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多