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

W.F*_*.F. 5 c++ templates non-type c++14

考虑一个例子:

#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");
}
Run Code Online (Sandbox Code Playgroud)

这与clang编译好,但不与gcc编译.问题在于:

static_assert(has_duplicates<int&, a, a, b>::value, "has_duplicates<int&, a, a, b>::value");
Run Code Online (Sandbox Code Playgroud)

编译器建议这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");
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

那么...哪个编译器是对的?

编辑:

为了澄清我没有尝试检查传递给变量的运行has_duplicates时值是否仅包含重复项,只有在传递给此特征的重复引用时...例如,以下代码在gcc和clang中成功编译:

template <int &X>
struct a { };

int b;

int main() {
   a<b> c;
}
Run Code Online (Sandbox Code Playgroud)

eca*_*mur 5

首先,它肯定是gcc中的一个bug.你在你的bug性质的诊断几乎是正确的,但它不是GCC不接受引用类型的非类型模板参数,它宁可GCC不承认引用类型的非类型模板参数作为class template部分特化,其中引用类型是以前的模板参数:

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
Run Code Online (Sandbox Code Playgroud)

#2是一个完全合法的部分特#1#3,并且应该与实例化匹配,每个[temp.class.spec.match]和[temp.deduct].

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

template<class R, R& A> struct S<0, R&, A> {};
Run Code Online (Sandbox Code Playgroud)

像clang这样的正确编译器也可以.

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

template <class R, R& First, R&... Others>
struct has_duplicates<R&, First, Others...> // ...
template <class R, R& Last>
struct has_duplicates<R&, Last> // ...
Run Code Online (Sandbox Code Playgroud)

  • @WF找不到任何东西; 已提交https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77435 (2认同)