Can I pass a reference type to a template to specify the following types of non-piggy template parameters?

Consider an example:

#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");
}

This compiles with clang, but not with gcc. The problem is the line:

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

where the compiler assumes that it has_duplicates<int&, a, a, b>is an incomplete type:

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");
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

So ... which compiler is right?

Edit:

To clarify that I am not trying to check whether the runtime values ​​for the variables passed to do not exceed has_duplicatesduplicates, only if duplicated links are passed to this attribute ... For example. The code below compiles successfully in both gcc and clang:

template <int &X>
struct a { };

int b;

int main() {
   a<b> c;
}
+4
source share
1 answer

-, gcc. , , 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, [temp.class.spec.match] [temp.deduct].

, , :

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> // ...
+5

Source: https://habr.com/ru/post/1653184/


All Articles