本文介绍了具有可变参数模板构造函数的推导指南和可变参数类模板-参数包长度不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下定义和:

Consider the following class definition and deduction guide:

template <typename... Ts>
struct foo : Ts...
{
    template <typename... Us>
    foo(Us&&... us) : Ts{us}... { }
};

template <typename... Us>
foo(Us&&... us) -> foo<Us...>;






如果我尝试实例化 foo 具有显式的 template参数,代码将正确编译:


If I try to instantiate foo with explicit template arguments, the code compiles correctly:

foo<bar> a{bar{}}; // ok






如果我尝试实例化 foo 通过扣除指南 ...

foo b{bar{}};




  • g ++ 7会产生编译器错误:

    • g++7 produces a compiler error:

      prog.cc: In instantiation of 'foo<Ts>::foo(Us ...) [with Us = {bar}; Ts = {}]':
      prog.cc:15:16:   required from here
      prog.cc:5:27: error: mismatched argument pack lengths while expanding 'Ts'
           foo(Us... us) : Ts{us}... { }
                                 ^~~
      


    • clang ++ 5爆炸:

    • clang++5 explodes:

      #0 0x0000000001944af4 PrintStackTraceSignalHandler(void*) (/opt/wandbox/clang-head/bin/clang-5.0+0x1944af4)
      #1 0x0000000001944dc6 SignalHandler(int) (/opt/wandbox/clang-head/bin/clang-5.0+0x1944dc6)
      #2 0x00007fafb639a390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
      #3 0x0000000003015b30 clang::Decl::setDeclContext(clang::DeclContext*) (/opt/wandbox/clang-head/bin/clang-5.0+0x3015b30)
      ...
      clang-5.0: error: unable to execute command: Segmentation fault
      


    • 虽然clang ++绝对是错误的(报告为问题), g ++拒绝我的代码正确吗? 我的代码格式不正确吗?

      While clang++ is definitely bugged (reported as issue #32673), is g++ correct in rejecting my code? Is my code ill-formed?

      推荐答案

      为进一步简化您的示例,看来GCC确实可以不在推导指南中实现可变参数模板参数:

      To simplify your example further, it appears that GCC does not implement variadic template arguments in deduction guides:

      我没有在标准或cppreference的演绎指南措辞中明确提及可变参数模板.com。我看不到不允许这样做的标准的解释。因此,我认为这是一个错误。

      I didn't see any explicit mention of variadic templates in the wording for deduction guides in the standard or on cppreference.com. I see no interpretation of the standard that disallows this. Therefore I think this is a bug.

      这篇关于具有可变参数模板构造函数的推导指南和可变参数类模板-参数包长度不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 07:00