在有两个模板参数T和U的模板类中,我想定义一个别名,如果U本身不是元组(T永远不是元组),则别名是元组{T,U};如果U是元组{U0,...,Un},则定义别名是元组{T,U0,...,Un}。我尝试了以下不能编译的代码(对于非元组U):
#include <type_traits>
#include <tuple>
//!
//! Template to check whether a type is a tuple.
//! From : https://stackoverflow.com/questions/13101061/detect-if-a-type-is-a-stdtuple
//!
template <typename T>
constexpr bool IsTuple = false;
template<typename ... types>
constexpr bool IsTuple<std::tuple<types...>> = true;
template<typename T, typename U>
class A
{
using TU = typename std::conditional<IsTuple<U>, decltype(std::tuple_cat(std::declval<std::tuple<T>>(), std::declval<U>())), std::tuple<T,U>>::type;
TU myTuple;
public:
A() = default;
};
int main()
{
A<int,int> a; // Fails compiling
// Would compile with A<int,std::tuple<int>>
} 这会导致编译失败,因为std::conditional中的两个类型都必须存在,而tuple_cat无法处理(std::tuple<int>, int>)。
有什么简单的方法可以做到这一点吗?
发布于 2021-04-14 07:51:26
也许是这样的:
template<typename T, typename U>
class A {
template <typename X, typename Y>
static std::tuple<X, Y> Helper(Y&&);
template <typename X, typename ... Elems>
static std::tuple<X, Elems...> Helper(std::tuple<Elems...>&&);
using TU = decltype(Helper<T>(std::declval<U>()));
};https://stackoverflow.com/questions/67083623
复制相似问题