【问题标题】:check-variadic-templates-parameters-for-uniqueness2 [duplicate]check-variadic-templates-parameters-for-uniqueness2 [重复]
【发布时间】:2013-09-27 06:40:44
【问题描述】:

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

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

#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>]’

【问题讨论】:

  • SFINAE 仅考虑直接上下文,基本上是功能站点上“可见”(您可以看到)的所有内容,以及 using-aliases 内部的内容。无效的基本成员不计算在内,这是一个间接错误。
  • @g-makulik。它不是重复的,它是连续的......))
  • 好的!我看到您似乎取得了一些进展(尽管如此我已经编辑和更新了原始问题,并且可能开始了赏金)。我不确定这是否对您有任何帮助,我最近一直在问一个问题,如何处理std::tuple 参数包以在编译时进行一些计算:Creating an array initializer from a tuple or variadic template parameters。也许这可以给你一个方向。

标签: c++ c++11 variadic-templates


【解决方案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
{};

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

【讨论】:

  • 我认为这就是 OP 尝试使用 SFINAE 预先检查的内容。
  • @g-makulik 是的,但他尝试的方式行不通。我解释了原因
  • 这就是我一直在投票的原因 ;)
猜你喜欢
  • 2015-10-18
  • 2022-12-02
  • 2016-01-15
  • 2020-10-27
  • 2015-12-27
  • 2012-05-31
  • 2022-12-01
  • 2017-08-05
  • 1970-01-01
相关资源
最近更新 更多