使用可变参数包实例化函数模板

Ash*_*tti 4 c++ c++11 c++14

假设我说这个代码:

template<int... Us>
struct Matrix{};

template<int... U1, int... U2>
auto compute(Matrix<U1...>, Matrix<U2...>){return 0;}

Matrix<1> a; Matrix<2,3> b;
Matrix<1,2> c; Matrix<3> d;

int main(){   
    compute(a,b);
    compute(c,d);
    auto fp = &compute<1,2,3>;
    fp(a,b);
    fp(c,d);
}
Run Code Online (Sandbox Code Playgroud)

两个compute()调用是否只实例化一个函数模板,即计算<1,2,3>,还是会有两个不同的实例,具体取决于参数?

我想通过获取指向特定实例的函数指针来确认这一点,看看我是否可以使用相同的函数指针调用具有2个不同参数集的函数,但是我在调​​用fp的行中得到以下错误(a, b):

[x86-64 gcc 8.2 #1] error: could not convert 'a' from
'Matrix<#'nontype_argument_pack' not supported by
dump_expr#<expression error>>' to 'Matrix<#'nontype_argument_pack' not
supported by dump_expr#<expression error>>'
Run Code Online (Sandbox Code Playgroud)

Yak*_*ont 6

参数包很贪婪.

&compute<1,2,3>是伪代码的&compute< U1={1,2,3}, U2={} >.

获取指向各个计算的指针很烦人.

template<class U1s, class U2s>
struct get_computer;
template<int...U1, int...U2>
struct get_computer<std::integer_sequence<int, U1...>, std::integer_sequence<int, U2...>> {
  using compute_type = int(*)(Matrix<U1...>, Matrix<U2...>);
  compute_type operator()() const { return compute; }
};
Run Code Online (Sandbox Code Playgroud)

我们可以做

auto fp1 = get_computer<std::integer_sequence<int, 1>, std::integer_sequence<int, 2, 3>>{}();
auto fp2 = get_computer<std::integer_sequence<int, 1, 2>, std::integer_sequence<int, 3>>{}();
Run Code Online (Sandbox Code Playgroud)

fp1fp2是不同的类型.