1

我在这里发布关于检查可变参数模板参数的唯一性 检查可变参数模板参数的唯一性

我的问题:为什么不编译以下代码?它是错误编译器还是标准是不允许的?

#include <iostream>


template< class ... > struct pack{};
template< class  > struct id{};
template< class  > struct base_all;
template< class ...T>
struct base_all< pack<T...> > : id<T> ... {using type = int;}; // <-- error with `int`, `char`, `int`  parameters.

template< class ...T>
struct is_unique
{
    template< class P,  std::size_t = sizeof(base_all<P>)  >
    struct check;

    template< class P >
    static constexpr bool test( check< P > * ) noexcept { return true ;}

    template< class P >
    static constexpr bool test( ... ) noexcept{ return false; }

    static constexpr bool value = test< pack<T...> >( nullptr );
};

int main()
{
    constexpr bool b = is_unique<int, float, double>::value;

    constexpr bool c = is_unique<int, char, int >::value; //<--- error 

    std::cout << std::boolalpha << "b = " << b << "\nc = " << c << std::endl;
}

错误编译器 gcc 4.8.1:

is_unique_args.cpp:16:42:   required by substitution of ‘template<class P> static constexpr bool is_unique<T>::test(is_unique<T>::check<P>*) [with P = P; T = {int, char, int}] [with P = pack<int, char, int>]’
4

1 回答 1

1

我像这样编译了你的例子:

g++ -Wall -Wextra -std=c++11 -rdynamic -pedantic garbage.cpp

并得到不同的错误:

garbage.cpp: In instantiation of ‘struct base_all<pack<int, char, int> >’:
garbage.cpp:17:27:   required by substitution of ‘template<class P> static constexpr bool is_unique::test(is_unique<T>::check<P>*) [with P = P; T = {int, char, int}] [with P = pack<int, char, int>]’
garbage.cpp:22:63:   required from ‘constexpr const bool is_unique<int, char, int>::value’
garbage.cpp:29:52:   required from here
garbage.cpp:8:8: error: duplicate base type ‘id<int>’ invalid

再次突出显示错误:

重复的基类型“id”无效

很清楚这意味着什么。c++ 禁止拥有更多相同类型的基类。所以,这是标准禁止的:

struct A
{};
struct B : A, A
{};

这就是您在上面尝试做的。

于 2013-09-27T08:59:09.687 回答