【发布时间】:2017-05-16 13:23:40
【问题描述】:
我有一种情况,我需要将输入参数应用于函数而不关心它是否是元组。如果是元组,需要解包,所以不需要函数参数检测。
这是我尝试过的:
template <typename Callable, typename Tuple>
auto geniune_apply(Callable&& callable, Tuple&& tuple)
{
return std::apply(std::forward<Callable>(callable), std::forward<Tuple>(tuple));
}
template <typename Callable, typename T, typename = typename std::enable_if<!shino::is_tuple_like<std::decay_t<T>>::value>::type>
auto geniune_apply(Callable&& callable, T&& arg)
{
return std::forward<Callable>(callable)(std::forward<T>(arg));
}
这会导致模棱两可,这正是我的预期。然后我尝试对元组的大小进行 SFINAE,但我无法防止非元组类型的编译错误。
这是我正在使用的测试用例:
#include <cassert>
#include <iostream>
#include <stdexcept>
#include <vector>
int dummy_x(const std::tuple<int, int>&)
{
return 1;
}
int dummy_y(int y)
{
return y;
}
int main()
{
shino::geniune_apply(&dummy_x, std::tuple<int, int>(1, 1));
shino::geniune_apply(dummy_y, 1);
shino::geniune_apply(dummy_y, std::make_tuple(1));
}
如果需要,类似元组的代码。它基本上测试它是std::array还是std::tuple:
template <typename T>
struct is_straight_tuple
{
static constexpr bool value = false;
constexpr operator bool()
{
return value;
}
};
template <typename ... Ts>
struct is_straight_tuple<std::tuple<Ts...>>
{
static constexpr bool value = true;
constexpr operator bool()
{
return value;
}
};
template <typename T>
struct is_std_array
{
static constexpr bool value = false;
};
template <typename T, std::size_t size>
struct is_std_array<std::array<T, size>>
{
static constexpr bool value = true;
constexpr operator bool()
{
return value;
}
};
template <typename T>
struct is_tuple_like
{
static constexpr bool value = is_std_array<T>::value || is_straight_tuple<T>::value;
constexpr operator bool()
{
return value;
}
};
【问题讨论】:
-
std::apply 是 C++17,但我不知道如何启用 if constexpr,所以我决定将问题标记为 C++14
标签: c++ c++14 template-meta-programming overload-resolution