是否可以将引用类型传递给模板以指定以下非类型模板参数的类型?

Can I pass a reference type to a template to specify following non-type template parameters' types?

本文关键字:类型 参数 是否 引用类型      更新时间:2023-10-16

考虑一个例子:

#include <type_traits>
template <class T, T>
struct has_duplicates_info { };
template <class T, T...>
struct has_duplicates;
template <class T, T First, T... Others>
struct has_duplicates<T, First, Others...>:
          has_duplicates<T, Others...>,
          has_duplicates_info<T, First> {
   static constexpr bool value =
      std::is_base_of<has_duplicates_info<T, First>, has_duplicates<T, Others...>>::value
        || has_duplicates<T, Others...>::value;
};
template <class T, T Last>
struct has_duplicates<T, Last>: has_duplicates_info<T, Last>, std::false_type { };
int a, b;
int main() {
   static_assert(!has_duplicates<int, 0, 1, 2>::value, "has_duplicates<int, 0, 1, 2>::value");
   static_assert(has_duplicates<int, 1, 2, 2, 3>::value, "!has_duplicates<int, 1, 2, 2, 3>::value");
   static_assert(has_duplicates<int&, a, a, b>::value, "!has_duplicates<int&, a, a, b>::value");
}

在clang中可以很好地编译,但在gcc中不行。问题在一行:

static_assert(has_duplicates<int&, a, a, b>::value, "has_duplicates<int&, a, a, b>::value");

编译器提示has_duplicates<int&, a, a, b>是不完全类型:

has_duplicates.cc:26:18: error: incomplete type ‘has_duplicates<int&, a, a, b>’ used in nested name specifier
    static_assert(has_duplicates<int&, a, a, b>::value, "has_duplicates<int&, a, a, b>::value");
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

所以…哪个编译器是正确的?

编辑:

澄清一下,我是不是试图检查传递给has_duplicates的变量背后的运行时值是否包含重复,只有当有重复的引用传递给这个trait时…例如,下面的代码可以在gcc和clang中成功编译:

template <int &X>
struct a { };
int b;
int main() {
   a<b> c;
}

首先,这肯定是gcc中的一个bug。您对错误本质的诊断几乎是正确的,但并不是gcc不接受引用类型的非类型模板参数,而是gcc无法识别引用类型的非类型模板参数作为类模板的部分专门化,其中引用类型是上一个模板参数:

template<int, class T, T> struct S;  // #1
template<class T, T A> struct S<0, T, A> {};  // #2
int i;
S<0, int&, i> s;  // #3 error: aggregate 'S<0, int&, i> s' has incomplete type

#2#1的完全合法的部分专门化,应该由实例化#3匹配,per [temp.class.spec]。匹配]和[temp.扣除].

幸运的是,有一个简单的解决方法,那就是为引用类型提供进一步的部分专门化:

template<class R, R& A> struct S<0, R&, A> {};

像clang这样的正确的编译器也会很好。

在您的情况下,进一步的部分专门化将是:

template <class R, R& First, R&... Others>
struct has_duplicates<R&, First, Others...> // ...
template <class R, R& Last>
struct has_duplicates<R&, Last> // ...