繁体   English   中英

为什么这个带有可变参数模板参数的构造函数不匹配?

[英]Why is this constructor with variadic template arguments not a match?

我有一个处理管道实现,但我想改进它像这样:

#include <iostream>

// buffers
struct src{}; struct b1{}; struct snk{};
// filters
struct f1
{
    f1( const src &, b1 & ) { std::cout << "f1( src, b1 )" << std::endl; }
};
struct f2
{
    f2( const b1 &, snk & ) { std::cout << "f2( b1, snk )" << std::endl; }
};
// the pipeline
template< typename... Filters >
struct pipeline
{
    template< typename LastB >
    pipeline( const LastB & )
    {}
};
template < typename T1, typename... T >
struct pipeline< T1, T... > : pipeline< T... >
{
    template< typename... Buffs, typename Bin, typename Bout >
    pipeline( Buffs &... buffs, Bin & bin, Bout & bout ) :
        pipeline< T... >( buffs..., bin ),
        filter( bin, bout )
    {
    }

    T1 filter;
};

int main()
{
    src ba; b1  bb; snk bc;

    pipeline< f1 > p1( ba, bb );
    pipeline< f1, f2 > p2( ba, bb, bc ); // the problem is in this line!
}

不幸的是,上面的例子会产生下一个错

sda_variadic.cpp: In function 'int main()':
sda_variadic.cpp:40:39: error: no matching function for call to 'pipeline<f1, f2>::pipeline(src&, b1&, snk&)'
sda_variadic.cpp:40:39: note: candidates are:
sda_variadic.cpp:26:5: note: template<class ... Buffs, class Bin, class Bout> pipeline<T1, T ...>::pipeline(Buffs& ..., Bin&, Bout&)
sda_variadic.cpp:23:8: note: constexpr pipeline<f1, f2>::pipeline(const pipeline<f1, f2>&)
sda_variadic.cpp:23:8: note:   candidate expects 1 argument, 3 provided
sda_variadic.cpp:23:8: note: constexpr pipeline<f1, f2>::pipeline(pipeline<f1, f2>&&)
sda_variadic.cpp:23:8: note:   candidate expects 1 argument, 3 provided

这个错误的原因是什么?
怎么解决?

只是一个小小的解释。 我希望上面的例子首先创建一个非特化pipeline<>( snk )的对象,然后是专用对象pipeline< f1 >(b1,snk) ,然后是专用对象pipeline< f1, f2 >(src,b1,snk)
顺便说一下,上面的例子适用于1个过滤器( pipeline< f1 )。

template< typename... Buffs, typename Bin, typename Bout >
pipeline( Buffs &... buffs, Bin & bin, Bout & bout ) :
    pipeline< T... >( buffs..., bin ),
    filter( bin, bout )
{
}

由于函数参数包( Buffs )不在最后位置,因此无法推断出。 从14.8.2.1中减去函数调用[temp.deduct.call]第1段中的模板参数:

  1. [...]对于未在参数声明列表末尾出现的函数参数包,参数包的类型是非推导的上下文。 [...]

由于您无法将模板参数显式传递给构造函数,因此根本无法调用它(不过它对您的问题很重要)。

我建议使用std::tuple来操作可变参数,这样你就像这样调用构造函数: pipeline(std::forward_as_tuple(b0, b1, b2), in, out)和一个空元组将被传递给最后一个阶段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM