问题描述
在具有两个模板参数 T 和 U 的模板类中,如果 U 本身不是元组(T 永远不是元组)或元组 {,我想定义一个别名,即元组 {T,U} T,U0,...,Un} 如果 U 是元组 {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>)
。
有什么简单的方法可以实现吗?
解决方法
大概是这样的:
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>()));
};