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

时间:2016-08-31 15:24:17

标签: c++ templates c++14 non-type

考虑一个例子:

#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的变量后面的运行时值是否包含重复项,只有在传递给该特征的重复引用时... ...下面的代码在gcc和clang中成功编译:

template <int &X>
struct a { };

int b;

int main() {
   a<b> c;
}

1 个答案:

答案 0 :(得分:5)

First off, it's definitely a bug in gcc. You're nearly correct in your diagnosis of the nature of the bug, but it's not that gcc doesn't accept reference-type non-type template parameters, it's rather that gcc fails to recognise reference-type non-type template parameters as a class template partial specialization where the reference type is a previous template parameter:

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 is a perfectly legitimate partial specialization of #1 and should be matched by the instantiation #3, per [temp.class.spec.match] and [temp.deduct].

Fortunately, there's a simple workaround, which is to provide a further partial specialization for reference types:

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

A correct compiler like clang will also be fine with this.

In your case the further partial specializations would be:

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