How to create the ideal forwarding constructor for an alternating type of variational class

I am trying to create something similar to a tuple, but I ran into a problem for writing my constructor.

Here is the code:

#include <tuple>

template <typename... Ts>
struct B {
    template <typename... ArgTypes>
    explicit B(ArgTypes&&... args)
    {
        static_assert(sizeof...(Ts) == sizeof...(ArgTypes),
            "Number of arguments does not match.");
    }
};

struct MyType {
    MyType() = delete;
    MyType(int x, const char* y) {}
};

int main()
{
   B         <int, char>               a{2, 'c'};                      // works
   B         <int, bool, MyType, char> b{2, false, {4, "blub"}, 'c'};  // fails
   std::tuple<int, bool, MyType, char> t{2, false, {4, "blub"}, 'c'};  // works
}

Now this works fine if you pass simple types as initializers, but it doesn’t, if I try to pass arguments to the initializer list, enclosed in brackets, for a non-trivial object.

GCC-4.7 emits the following:

vararg_constr.cpp:21:67: error: no matching function for call to 'B<int, bool, MyType, char>::B(<brace-enclosed initializer list>)'
vararg_constr.cpp:21:67: note: candidates are:
vararg_constr.cpp:6:14: note: B<Ts>::B(ArgTypes&& ...) [with ArgTypes = {}; Ts = {int, bool, MyType, char}]
vararg_constr.cpp:6:14: note:   candidate expects 0 arguments, 4 provided

Clang-3.1 is the following:

vararg_constr.cpp:21:40: error: no matching constructor for initialization of
      'B<int, bool, MyType, char>'
   B         <int, bool, MyType, char> b{2, false,{4, "blub"}, 'c'};  // fails
                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
vararg_constr.cpp:6:14: note: candidate constructor not viable: requires 2
      arguments, but 4 were provided
    explicit B(ArgTypes&&... args)

Well, now I am very, very curious that he works for a tuple! According to the standard (20.4.2.1), it has a constructor that is very similar to mine.

template <class... Types>
class tuple {
public:
    // ...

    template <class... UTypes>
    explicit tuple(UTypes&&...);

    // ...
};

When building a tuple object in the same way, it works!

Now I would like to know:

A) ? std:: tuple , ?

B) ?

+5
1

A) , {4, "blub"} MyType, tuple<int, const char*>?

B) ArgTypes Ts :

explicit B(Ts&&... args)

Tuple :

  explicit constexpr tuple(const _Elements&... __elements);

EDIT: , const & , R-. :

template <typename... Ts>
struct B {
  explicit B(const Ts&... elements) { std::cout << "A\n"; }
  template<typename... As,
           typename = typename std::enable_if<sizeof...(As) == sizeof...(Ts)>::type>
  explicit B(As&&... elements) { std::cout << "B\n" ;}
};

int main()
{
  MyType m {1, "blub"};
  B<int, char>           a{2, 'c'};                            // prints B
  B<bool, MyType, char>  b{false, {4, "blub"}, 'c'};           // prints A
  B<bool, MyType, MyType>c{false, {4, "blub"}, std::move(m)};  // prints A
}
+6

All Articles