在变差函数的不同参数包中推导两个不同的已知类型变量

deduce two different known type variables in different parameter packs within a variadic function

本文关键字:两个 类型变量 包中推 函数 参数      更新时间:2023-10-16

我有以下代码:

template <typename... Type1, typename... Type2>
void foo(const Type1&&... t1, Type2&&... t2)
{
    int len = sizeof...(Type1);
    cout << len << endl;
    int len1 = sizeof...(Type2);
    cout << len1 << endl;
}
int main()
{
    foo(1, 2, 4.5, 5.5);
    return 0;
}

调用foo()会推断Type1为空,Type2{int, int, double, double},而我希望Type1{int, int}Type2{double, double}。如果不涉及std::tuple,只调用上面代码中的foo()函数,这可能吗?

编辑


为了更清楚地说明我想要实现什么,这里有一个解释。我想创建一个函数,用户可以每次以偶数对的方式传递任意数量的两种类型变量。假设foo(Type1 x, Type1 y, Type1 z, Type1 ..., Type2 XX, Type2 YY, Type2 ZZ, Type2 ...);Type1的变量将始终是const引用,而Type2的变量只是引用,因此函数将以以下形式结束:foo(const Type1& x, const Type1& y, ..., Type2& XX, Type2& YY, ...)。在函数中,我将使用Type1变量进行一些计算,并通过Type2变量返回相应的结果。我知道使用任何容器结构都会让我的生活更轻松,但不幸的是,我不能接受这种解决方案。所以,虽然我不是一个经验丰富的人,但我认为使用变差函数是可行的,对吗?

不,编译器无法读懂你的想法。

你可以把一包类型分成两半:

template<class...>struct types{using type=types;};
template<class lhs, class rhs>struct cat;
template<class lhs, class rhs>using cat_t=typename cat<lhs,rhs>::type;
template<class...lhs, class...rhs>
struct cat<types<lhs...>,types<rhs...>>:
  types<lhs...,rhs...>
{};
template<class types, size_t n>
struct split {
private:
  using s0 = split<types,n/2>;
  using r0 = typename s0::lhs;
  using r1 = typename s0::rhs;
  using s1 = split<r1,n-n/2>;
  using r2 = typename s1::lhs;
public:
  using lhs = cat_t<r0,r2>;
  using rhs = typename s1::rhs;
};
template<class Types>
struct split<Types, 0>{
  using lhs=types<>;
  using rhs=Types;
};
template<class T0,class...Ts>
struct split<types<T0,Ts...>,1>{
  using lhs=types<T0>;
  using rhs=types<Ts...>;
};

然后我们使用它将foo参数拆分为两个包:

template<class types>
struct foo2_t;
template<class... T0s>
struct foo2_t<types<T0s...>>{
  template<class... T1s>
  void operator()(T0s&&... t0s, T1s&&... t1s) const {
    std::cout << sizeof...(T0s) << 'n';
    std::cout << sizeof...(T1s) << 'n';
  }
};
template <class... Ts>
void foo(Ts&&... ts) {
  using s = split< types<Ts...>, sizeof...(Ts)/2 >;
  foo2_t<typename s::lhs>{}( std::forward<Ts>(ts)... );
}

实例

如果你想让编译器做不同的魔术(比如,在相同的类型上聚集,或者你想做的任何其他事情),一种不同的(但相似的)技术会起作用。

尝试更简单的方法。以两个向量作为自变量。

template<typename T, typename A>
void foo( std::vector<T,A> const& t1, std::vector<T,A> const& t2 ) {
//do wtever you want
}