首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >check-variadic-templates-parameters-for-uniqueness2

check-variadic-templates-parameters-for-uniqueness2
EN

Stack Overflow用户
提问于 2013-09-27 14:40:44
回答 1查看 149关注 0票数 1

我在这里发布了关于检查各种模板参数的唯一性check variadic templates parameters for uniqueness

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

代码语言:javascript
复制
#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:

代码语言:javascript
复制
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>]’
EN

回答 1

Stack Overflow用户

发布于 2013-09-27 16:59:10

我把你的例子编译成这样:

代码语言:javascript
复制
g++ -Wall -Wextra -std=c++11 -rdynamic -pedantic garbage.cpp

并得到不同的错误:

代码语言:javascript
复制
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++禁止具有更多相同类型的基类。所以,这是标准所禁止的:

代码语言:javascript
复制
struct A
{};
struct B : A, A
{};

这就是你上面想要做的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19044256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档