推导出一个元组的类型

use*_*108 5 c++ templates language-lawyer template-argument-deduction c++14

我有这样的代码:

template <typename T>
inline typename ::std::enable_if<
  is_std_tuple<T>{},
  T
>::type
get()
{
  // pull tuple's elements from somewhere
}
Run Code Online (Sandbox Code Playgroud)

为了推导出元组实例化的模板类型参数,我做了这个演员:

static_cast<T*>(nullptr)
Run Code Online (Sandbox Code Playgroud)

并将其作为参数传递给函数

template <typename ...A>
void deduce_tuple(::std::tuple<A...>* const);
Run Code Online (Sandbox Code Playgroud)

我承诺UB吗?有没有更好的办法?

Col*_*mbo 5

这里的缺点是我们不能部分专门化功能模板.你的方式很好,因为我们没有取消引用空指针; 我更喜欢使用指定的标签:

template <typename...> struct deduction_tag {};

template <typename... Ts>
std::tuple<Ts...> get(deduction_tag<std::tuple<Ts...>>) {
    // […]
}
template <typename T>
std::enable_if_t<is_std_tuple<T>{}, T> get() {
    return get(deduction_tag<T>{});
}
Run Code Online (Sandbox Code Playgroud)