含非类型参数包的模板实例化不明确 class

Ambiguous class template instantiation with nontype parameter packs

我正在尝试专攻 Expr:

#include <tuple>
#include <type_traits>
#include <iostream>

template<class Tp, class List> 
struct Expr {
    Expr(){std::cout << "0"<< std::endl;};
};

//specialization #1
template<class Tp, int...i>
struct Expr<Tp,std::tuple<std::integral_constant<int,i>...>> {

    Expr(){std::cout << "1"<< std::endl;};
};

//specialization #2
template<int...i>
struct Expr<double,std::tuple<std::integral_constant<int,i>...>> {

    Expr(){std::cout << "2"<< std::endl;};
};

int main() {

    typedef std::tuple<std::integral_constant<int,1>> mylist;

    Expr<double,mylist> test{};

    return 0;
}

但是,我遇到了以下编译器错误:

[x86-64 gcc 6.3] error: ambiguous template instantiation for 'struct Expr<double, std::tuple<std::integral_constant<int, 1> > >'
[x86-64 gcc 6.3] error: variable 'Expr<double, std::tuple<std::integral_constant<int, 1> > > test' has initializer but incomplete type

在这里,尤其是第一个错误困扰着我。我试图弄清楚为什么这是一个模棱两可的实例化。

编译器不应该选择specialization #2吗?

如果我避免将非类型参数包 int...i 包装在 std::integral_constant 中,它编译没有任何问题,并且选择了第二个专业化。以下示例有效:

#include <tuple>
#include <type_traits>
#include <iostream>

template<class Tp, class List> 
struct Expr {
    Expr(){std::cout << "0"<< std::endl;};
};

//specialization #1
template<class Tp, class...args>
struct Expr<Tp,std::tuple<args...>> {

    Expr(){std::cout << "1"<< std::endl;};
};

//specialization #2
template<class...args>
struct Expr<double,std::tuple<args...>> {

    Expr(){std::cout << "2"<< std::endl;};
};

int main() {

    typedef std::tuple<std::integral_constant<int,1>> mylist;

    Expr<double,mylist> test{};

    return 0;
}

这不对。这是一个 gcc 错误(我找不到它的错误报告,也许还没有报告?)。

你说得对,必须选择专业#2。因为有 2 个匹配的特化,部分排序选择最特化的一个,在你的情况下是 #2(double 作为第一个参数比任何类型作为第一个参数都更特化)。

此外,clang 会编译您的代码 without any problems