【问题标题】:C++ variadic templatesC++ 可变参数模板
【发布时间】:2022-01-23 21:09:03
【问题描述】:

我正在使用矢量定义:

     vector<lmlink_out> os{
       lmlink_out(typeid(string &)),
       lmlink_out(),
       lmlink_out(typeid(int),typeid(char))
       };

使用以下代码可以工作(在类中定义):

 class lmlink_out {
     vector<const type_info*> parameters;  
     ...
    public:
     template<typename... T, std::size_t N = sizeof...(T)>
     lmlink_out(const T&... args) : parameters({&args...}) {}

使用其他会导致编译错误(在类外定义):

class lmlink_out {
     vector<const type_info*> parameters;  
     ...
    public:
     template<typename... T, std::size_t N = sizeof...(T)>
     lmlink_out(const T&... args);
    };

template<typename... T, std::size_t N = sizeof...(T)>
lmlink_out::lmlink_out(const T&... args)
  : parameters({(&args...})
{
}

编译器(gcc 版本 10.2.1 20210110 (Debian 10.2.1-6))返回:

错误:没有匹配函数调用‘std::vector::vector()’ 374 |
: 参数({(&args...}) 注意: 候选: 'std::vector<_tp _alloc>::vector(std::initializer_list<_tp>, const allocator_type&) [with _Tp = const std::type_info*; _Alloc = std::allocator; std::vector<_tp _alloc>::allocator_type = std::allocator]’ 625 |
向量(initializer_list __l, ... | ^~~~~~ /usr/include/c++/10/bits/stl_vector.h:625:43: 注意:没有已知的参数 1 从 '' 到 'std::initializer_list 的转换'

我认为两个代码在语义上是等价的,为什么第二个会报错?

我需要添加另一个构造函数:

template<typename... T, std::size_t N = sizeof...(T)>
lmlink_out(const string &name, const T&... args) : name(name), parameters({&args...}) {}

但它会导致上述相同的错误。

【问题讨论】:

  • 请显示minimal reproducible example,以便我们重现相同的错误。
  • 顺便说一句,在: parameters({(&amp;args...}) 你有一个不平衡的括号。应该是: parameters({&amp;args...})
  • 谢谢,没错。

标签: c++ variadic-templates


【解决方案1】:

您的代码有两个简单的问题:

  1. 您不能重新定义模板默认参数,即,您需要删除 ctor 定义的 = sizeof...(T) rom。它只能出现在第一个声明中。

  2. 调用parameters ctor时有多余的'('。应该是

    : parameters({&args...})
    

这个Compiler Explorer link 显示代码正在编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    • 2017-08-04
    相关资源
    最近更新 更多