简体   繁体   中英

C++ variadic templates

I'm using a vector definition:

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

using the following code works (defined inside the class):

 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...}) {}

using this other leads to compilation error (defined outside the class):

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...})
{
}

the compiler (gcc version 10.2.1 20210110 (Debian 10.2.1-6)) returns:

error: no matching function for call to 'std::vector<const std::type_info*>::vector()' 374 |
: parameters({(&args...}) note: candidate: 'std::vector<_Tp, _Alloc>::vector(std::initializer_list<_Tp>, const allocator_type&) [with _Tp = const std::type_info*; _Alloc = std::allocator<const std::type_info*>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<const std::type_info*>]' 625 |
vector(initializer_list<value_type> __l, ... | ^~~~~~ /usr/include/c++/10/bits/stl_vector.h:625:43: note: no known conversion for argument 1 from '' to 'std::initializer_list<const std::type_info*>'

I think that two codes are semantically equivalent, why does the second give an error?

I need to add another constructor:

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

but it lead to the same error above.

Your code has two simple problems:

  1. You can't redefine template default arguments, ie, you'll need to drop the = sizeof...(T) rom the definition of the ctor. It can only be present in the first declraation.

  2. There is an excess '(' when calling the parameters ctor. It should be

    : parameters({&args...})

This Compiler Explorer link shows the code compiling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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