FAQ Database Discussion Community

## Convert a recursive variadic template function into iterative

Say I have the following stuct #include <functional> template <typename ...T> struct Unpack; // specialization case for float template <typename ...Tail> struct Unpack<float, Tail...> { static void unpack(std::function<void(float, Tail...)> f, uint8_t *dataOffset) { float val; memcpy(&val, dataOffset, sizeof(float)); auto g = [&](Tail&& ...args) { f(val, std::forward<Tail>(args)...); }; Unpack<Tail...>::unpack(std::function<void(Tail...)>{g}, dataOffset +...

## Correct function signature template for member function

Following up on a question I recently asked, there might be some unnecessary stuff in there but the example is small, what I want to do (and of course if you can think of other cool ways to do this, please share your thoughts), is to allow the user to...

## How can I detect parameter types of a function passed as a parameter?

Problem I have to write a function that will be used as: obj.transform([](x& a, y& b) { ... }); obj.transform([](x& a) { ... }); obj.transform([](y const& a, x& b, z const& c) { ... }); obj.transform([a, b](z const& c) { ... }); ... and inside the function declaration, I need...

## Insert/remove type into variadic template list (parameter pack)

What is the best way of implementing index-based insertion and deletion of a type in a variadic template type list (parameter pack)? Desired code/behavior: template<typename...> struct List { /* ... */ }; static_assert(is_same < List<int, char, float>::Insert<int, 0>, List<int, int, char, float> >()); static_assert(is_same < List<int, char, float>::Insert<int, 2>, List<int,...

## c++ class template can be instantiated but a function template instantiation with the same template parameters fails

I have a wrapper class for binded function calls (a helper class to fight some legacy code issues): template <class Result, class... Args> class FunctionWrapper { std::function<Result()> func_; public: FunctionWrapper(std::function<Result(Args...)> f, Args&&... args) : func_(std::bind(f, std::forward<Args>(args)...)) { } //...some methods using that func_ }; I can write the following code,...

I want to write a class method that takes a template parameter pack, but zero arguments, and "iterate" over the types: struct Bar { template <typename T, typename... Ts> void foo() { // something with T that involves Bar's members foo<Ts...>(); } }; What is the preferred way to implement...

## Calling a stateless lambda without an instance (only type)

I'm trying to write a wrapper for a "register callback" type of interface from a C library. The issue is quite complicated by the fact that, the library lets you register "variadic" functions by accepting a list of parameter definitions. Then at callback time, the function is expected to extract...

## Bug in gcc, or extention in clang/MSVS

The following snippet compiles in clang and MSVS, but not in gcc. template<typename T> class clone_ptr; template<typename T, typename U, typename ...Args> clone_ptr<T> make_cloned( Args ...args ); // note: everything not needed for example cut out, so // this class is neither complete nor correct template<typename T> class clone_ptr {...

## How to parallel variadic function with TBB parallel_for?

I have a template variadic function like this that need to parallelize with TBB parallel_for function template<typename T1, typename T2, typename... T3> void func(T1 t1, T2 t2, std::size_t n, T3... t3) I first tried to use lambda function, it is able to catch the variadic arguments. It compiled with clang...

## Get types of function parameters

Is there a standard way to get the types of a function's arguments and pass around these types as a template parameter pack? I know that this is possible in C++ because it has been done before. I was hoping that with C++14 or the upcoming C++1z, there would be...

## Indices trick used for several components

Consider this fully working code: #include <type_traits> template <typename T, typename IndexPack> struct Make; template <typename T, template <T...> class P, T... Indices> struct Make<T, P<Indices...>> { using type = P<(Indices+1)..., (-3*Indices)..., (Indices-1)...>; }; template <int...> class Pack; int main() { static_assert (std::is_same<Make<int, Pack<1,2,3,4>>::type, Pack<2,3,4,5, -3,-6,-9,-12, 0,1,2,3>>::value, "false"); } What...

## How can I expand call to variadic template base classes?

I have a set of non-orthogonal policies, all of them implementing a common named method, the policies add safety checks. I want users to be able to combine the policies to allow more complex validation without creating policies for each combination case by hand. My approach is creating a new...

## How can I get the index of a type in a variadic class template?

I have a variadic Engine template class: template <typename ... Components> class Engine; I'd like to assign a number to each component at compile time which is equivalent to their ordering. This would be returned when making the following call: template <typename Component> int ordinal(); So for example if: Engine<PositionComponent,...

## C++: Using type as map key introduces template substitution errors

I'm using a tuple as a key to track elements in a map, and then later iterating over the map to produce a string version of the map. To help me with the conversion, I have a template convenience function that will concatenate the tuple used as the key (inspired...

## Compilation issue with instantiating function template

Consider the following code: #include <iostream> struct S { void f(const char* s) { std::cout << s << '\n'; } }; template <typename... Args, void(S::*mem_fn)(Args...)> void invoke(S* pd, Args... args) { (pd->*mem_fn)(args...); } int main() { S s; void(*pfn)(S*, const char*) = invoke<const char*, &S::f>; pfn(&s, "hello"); } When compiling...

## How to set the same type for all arguments in this example?

Just for practice I'm trying to write a variadic template that inputs some values into vector. I wrote the following: template <class T> void add(vector<T> *v, T n){ v->push_back(n); } template <class T, class... T2> void add(vector<T> *v, T n, T2... rest){ v->push_back(n); add(v, rest...); } To test these I...

## Is there any option to defer the evaluation of a function call in a variadic template

Suppose a variadic template: void f(T value, Args... args) As one of the arguments a function is passed which returns a value. Example: f(1, getName()); Is there a simple way to defer the evaluation of the function, so getName() is invoked inside f() and is not executed if not required....

## Variadic template unrolling to std::tuple

I have a filter class that takes two template parameters, the number of inputs and the number of outputs. template<int Ins, int Outs> class Filter { // implementation }; Sometimes I need to chain multiple filters in series so I was thinking to wrap them in a class template<int... args>...

## can't understand variadic templates in c++

I was reading about variadic templates and I came across this example. The book mentions that to end the recursion process, the function print() is used. I really can't understand its use. Why does the author use this empty print() function? void print () // can't get why this function...

## C++11 variadic template function storage

I am currently reworking my callback system to C++11 variadic templates. Basically what I am trying to do is to store a function with a return value and any number of arguments. Afterwards this function should be called and parameters are loaded from a boost::archive and return value should be...

## Iterating on a tuple… again

It's been a while that I've been doing C++ but I'm not familiar with templates. Recently, I tried to write a class that wrap a std::vector<std::tuple<Types...>>. This class must have member functions, and I really need to be able to iterate over the tuple. In fact, if I am able...

## Call void function for each template type in a variadic templated function?

My goal is to write a simple generic function for registering converters for arbitrary C++ types. For simplicity I'll just print C++ type names. I'd like to be able to call my generic print_type_name function for any types, including multiple types at once (variadic): template <typename T> void print_type_name(void) {...

## variadic template for forward list initialization of std::array

I have a geometry structure describing a point in N dimensions template <typename T, std::size_t N> class point : public std::array<T, N> Among the many constructors / methods I'd like to add to this class, I cannot figure out how to build a variadic constructor. I've tried template<typename ...Args> point(Args&&...t)...

## Filling an array on compiletime under some predicate

Is there a way to make a constexpr-Array of unsigned integers which fulfill some predicate given by the constexpr boolean function pred(std::size_t)? I tried a lot around, especially with the indices trick, just to find out that my data is too huge, such that it exceeds the recursive template instantiation...

## Can I force variadic template to take a specific type of argument

In C++ templates there is a concept called explicit template argument specification, which means that I can force the compiler to create a template function of the given type. e.g. template <class T1, class T2> void foo(T1 t1prm, T2 t2prm) { /* function body */ } foo<double, double>(1,2); Can I...

## Custom Container emplace with variadic templates

I am implementing a simple circular vector class. I want to implement an emplace member function, but I am getting an error which I don't understand. It might be a simple fix for something I am doing wrong, but since I don't have much experience with variadic templates, I can't...

## Boost template error using inter-process map

EDIT: Although not strictly the the answer I was looking for, that is because I was asking the wrong question. I have marked this question as "answered" because it helped me see what I was doing wrong (when put back in context, the class structure doesn't make sense and needs...

## Variadic template function name lookup fails to find specializations

I am attempting to program a string concatenation function which utilizes my 3D library's string conversion functions, implemented with a variadic template. The library's conversion function behaves unusually if a string (either const char[] literal or std::string) is passed to it. as it does not actually possess functions for those...

## Separate definitions of variadic templates

(Final question at the bottom) Recently, I asked a question concerning how I would fix linker errors (on duplicate symbols concerning multiple definitions of a template void. Because I was using the functions in multiple source files, I was suggested to use the keyword inline to allow declarations in the...

## sort a pair by common top and bottom

Imagine that you have n sets of elements in a tuple. For example the tuple could be std::tuple<topBottomStr, topBottomStr, topBottomStr> or std::tuple<fraction, fraction, fraction> So maybe there is some template that represents "topbottomthings" template<typename T> class TopBottomThing { private: T top; T bottom; }; The point is that what is...

## Create hash queue with variadic template

I want to build a hash code queue using variadic template. The minimal example code is template<typename T> void hash_queue(queue<size_t>& q){ q.push( typeid(T).hash_code() ); } template<typename T, typename... Ts> void hash_queue(queue<size_t>& q){ hash_queue<Ts...>(q); q.push( typeid(T).hash_code() ); } int main(){ queue<size_t> q; hash_queue<int, float, double>(q); return 0; } On compile I...

## Polymorphism, variadic template inheritance, slicing, boost::any type cast

This program compiles, but the boost::any cast fails. I suspect that slicing a template class this way confuses pointer arithmetic. The idea is that what is stored in the container std::vector<boost::any> pressures; are of different types, for example Pressure<Printer>, or Pressure<Printer, Printer> etc. Since I lose the type by storing...

## Saving the results of a tuple_cat

I have code that I have taken from another source. The rest of the code works great. I am trying to append to a tuple using the following code: // Because std::make_tuple can't be passed // to higher order functions. constexpr struct MakeTuple { template< class ...X > constexpr std::tuple<X...>...

## Variadic template method and std::function - compilation error [duplicate]

This question already has an answer here: C++11 does not deduce type when std::function or lambda functions are involved 1 answer I'm sure the error is very simple and silly, but I can't see one. Here's the code: #include <future> template <typename ResultType> class Foo { public: template <typename...

## Expanding container to parameter pack

Let's say I have a variadic function I can't change like so: void Func(int count, ...) { /*etc.*/ } And I'm writing a variadic template like so to wrap that function and make it safer to use: template<typename... T> void ToString(T... args) { std::vector<CString> vstrArgs = { args... }; Func(sizeof...(args),...

## Folding over arbitrarily many variadic packs

I'm reading through Eric Niebler's post on his tiny metaprogramming library. In trying to implement the pieces that he omits / lists as challenges, I am left with the following implementation of transform: template <typename F, typename... As> using meta_apply = typename F::template apply<As...>; template <typename... > struct typelist_transform; //...

## Create an optional tuple

I don't understand why there is no optional tuple, and I mean by that, something like this ; optional<int,string,char> that would combine an optional int, optional string and optional char. You can think of it like an optimized std::tuple<boost::optional<T>...> where the booleans used by the optionals would be all together...

## Can default function arguments “fill in” for expanded parameter packs?

The following code fails to compile : #include <iostream> template<typename F, typename ...Args> static auto wrap(F func, Args&&... args) { return func(std::forward<Args>(args)...); } void f1(int, char, double) { std::cout << "do nada1\n"; } void f2(int, char='a', double=0.) { std::cout << "do nada2\n"; } int main() { wrap(f1, 1, 'a', 2.);...

## Terminating class template recursion

I initially had the following recursive variadic template code #include <functional> #include <iostream> // end of recursion void apply(std::function<void()> f, int) { f(); } // base recursive template <typename Head, typename ...Tail> void apply(std::function<void(Head, Tail...)> f, int i) { auto g = [=](Tail&& ...args) { f(i, std::forward<Tail>(args)...); }; apply(std::function<void(Tail...)>{g}, ++i);...

## deduce entire vector space at compile time

Inspired by this question : c++ generate (xyz) points in range I began to wonder whether there is a form of template code that can, from this statement: using X = axis_limits<-10, +10>; using Y = axis_limits<-10, +10>; using Z = axis_limits<-10, +10>; auto space = std::vector<point>{ generate_point_space<X, Y, Z>...

## Calling a function inside an initializer list with an empty parameter pack function argument

I have void foo(double &arg, uint8_t *data) { // ... } template <class T> void foo(T &arg, uint8_t *data) { // ... } and I call it in template <class ...T> void bar(T... arg) { uint8_t *data = new uint8_t[SOME_VALUE]; // guaranteed to be executed in order auto list =...

## Getting nth variadic argument value (not type)

Ignore the missing perfect forwarding. (Assume arguments are perfectly forwarded in the real implementation.) // Base case: no args template<typename TF> void forEach2Args(TF) { } // Recursive case: some args template<typename TF, typename... Ts> void forEach2Args(TF mFn, Ts... mXs) { mFn(getNth<0>(mXs...), getNth<1>(mXs...)); forEach2Args(mFn, getAllAfter<2>(mXs...)); } int main() { int result{0};...

## Check traits for all variadic template arguments

Background : I've created the following class C, whose constructor should take N variables of type B& : class A; class B { A* getA(); }; template<size_t N> class C { public: template<typename... Args> inline C(Args&... args) : member{args.getA()...} {} private: std::array<A*, N> member; }; Problem : my problem is...

## How to implement an easy_bind() that automagically inserts implied placeholders? *With member pointers*

I have come upon this interesting solution (here with an example here) to make a std::bind type function without having to explicitly put placeholders. Quest To implement a similar bind function without the capability to put values in the bind call (I don't need it.) and to add the capability...

## Generate a C++ class from an other one

I want to generate class Y from class X : class X{ T e; optional<T1> e1; optional<T2> e2; optional<T3> e3; T4 e4; // Member functions ... }; class Y{ T e; T1 e1; T2 e2; T3 e3; T4 e4; bool b1; bool b2; bool b3; // Member functions ... }...

## How to instantiate template from mpl::vector

I have a mpl::vector & want to instantiate a template using the vector elements as template arguments. How is this done? Can a argument pack be used to consolidate extra mpl::vector elements? For example: struct A; struct B; struct C; struct D; using args = mpl::vector<A, B, C, D>; template<typename...

## A variadic template method to accept a given number of doubles?

template <unsigned int N> class myclass { public: template <typename... Args> void mymethod(Args... args) { // Do interesting stuff } }; I want mymethod to be called only with exactly N doubles. Is that possible? That is, say that I have: myclass <3> x; x.mymethod(3., 4., 5.); // This works...

## C++, match custom placeholders with function arguments

I am trying to write the piece of code which will do the following: let's assume we have a call of custom bind function auto bind_obj = bind(some_func, _1, "test") and after we have auto res = bind_obj(42) where the function some_func: int some_func(int val, string test) How can it...

## Create n-dimensional vector with given sizes

So, what I want is to create multidimensional vector of given type where the first dimension will have size of the first argument of a function call, etc, for example if I do std::size_t n = 5; auto x = make_vector<int>(n + 1, n * 2, n * 3); x...

## Including Array of same type in Variadic Templates

I am trying to write a variadic template in c++ which can deduce the type at compile time and provide me with any specified operation. For example, I wish to sum elements of same type passed as argument. This is where I have come so far - template <typename T>...

## Template specialization and SFINAE on VS2013

I'm using VS2013 (update 4), and I'm having trouble compiling the following variadic template code: #include <iostream> #include <string> // Variadic template "multiwrite" for writing a string to multiple different streams template <typename T> void mwrite(T value, std::ostream& os) { os << value; } template <typename T, typename... SS> void...

## Avoiding to defer “child” object construction with `operator<<`

Let's say I have a container object that stores an std::vector of polymorphic children. struct Child { Child(Parent& mParent) { /* ... */ } virtual ~Child() { } }; class Parent { private: std::vector<std::unique_ptr<Child>> children; template<typename T, typename... TArgs> auto& mkChild(TArgs&&... mArgs) { // `static_assert` that `T` is derived from...

## Applying a lambda to template arguments pack; lambda arguments not captured

I want to write a function that will accept any number of numeric arguments and return their mean. Using an expansion trick from Wikipedia: namespace detail { template<typename... Args> void iterate_template_pack(Args&&...) {} } template <typename ResultType, typename... Args> ResultType arithmeticMean(Args&&... args) { ResultType acc = ResultType(0); size_t n = 0;...

I have a scene graph which contains nodes. Each node has a transform and several components. I have a 2d scene editor and am currently doing the following to select a component to edit: //Within the node class I can grab a list of components template<typename ComponentType = Component> std::vector<SafeComponent<ComponentType>>...

## Schwarz Counter and variadic template

For people who never heard of "Schwarz Counter", please refer to this wikibook page. I'm trying to implement this idiom with C++11 template, everything works fine except when the template argument ISN'T default constructible. Here is my implementation: (See the code comments for the question) #include <type_traits> template<typename T> class...

## A structure that stores its fields by size

I would like to know how can I do the following in C++: Consider these classes : C1 < C2 < C3 < ... < Cn, Ci < Cj means sizeof(Ci) < sizeof(Cj) I want a structure that uses variadic templates as a sequence of Ci's, OrderBySize<AnySequenceOfCis>, for example :...

## Why is this nested variadic template an invalid argument?

If I define a struct template Bar which accepts a template argument: template <template <int,bool,char> class> struct Bar {}; I can instantiate it using a struct template such as Zod: template <int,bool,char> struct Zod {}; Bar<Zod> a; I can also instantiate it using a nested struct template such as JKL:...

## Unpack ts… to t0.a(), t0.b(), t1.a(), t1.b(),

I want to call one variadic function from another variadic function in the following manner: template <typename ...Ts> void f(Ts const & ...) { /* ... */ } template <typename ...Args> void g(Args const & ...args) { // shall call f(arg0.a(), arg0.b(), arg1.a(), arg1.b(), ...) } I have done it...

## Preserving referenceness when passing variadic arguments

Consider the following code snippet: class Base { public: template <typename...Ts> void fun(Ts... vs) { cout << "Base::fun" << endl; cout << __FUNCSIG__ << endl; } }; template <typename...Ts> class Derived : public Base { public: void dfun(Ts... vs) { cout << "Derived::dfun" << endl; cout << __FUNCSIG__ << endl;...

## Factory pattern using variadic template?

I have an abstract class template <class T> struct A { /* virtual methods */ }; and several concrete derived classes with various constructors // The constructor of B takes 1 input template <class T> struct B : public A<T> { B() { /* default ctor */ } B( T...

Recently I asked this question but now I would like to expand it. I wrote the following class: template <class T> class X{ public: vector<T> v; template <class T> X(T n) { v.push_back(n); } template <class T, class... T2> X(T n, T2... rest) { v.push_back(n); X(rest...); } }; When creating...

## decltype for the return type of recursive variadic function template

Given the following code(taken from here): #include <cstddef> #include <type_traits> #include <tuple> #include <iostream> #include <utility> #include <functional> template<typename ... Fs> struct compose_impl { compose_impl(Fs&& ... fs) : functionTuple(std::forward_as_tuple(fs ...)) {} template<size_t N, typename ... Ts> auto apply(std::integral_constant<size_t, N>, Ts&& ... ts) const { return apply(std::integral_constant<size_t, N - 1>(), std::get<N>...

I want to prepare list of pairs of values from structure using variadic templates. #include <vector> struct foo { foo(int a, int b) : a(a), b(b) {} int a; int b; }; struct Msg { std::vector<int> valueArray; }; template<typename... Args> Msg func(Args... args) { Msg msg; msg.valueArray = { sizeof...(args),...

## How to handle a case of empty parameter pack

I have the following code that I use to get size of all primitive types in the pack (I treat floats and doubles in a special way), but my program fails to compile when the pack is empty. // terminating general case for T being anything else template <class T>...

## type deduction from char array to std::string

I'm trying to write sum function using variadic template. In the code I would write something like sum(1, 2., 3) and it will return most general type of the sum (in this case - double). The problem is with characters. When I call it like sum("Hello", " ", "World!") template...

## Variadic template recursive return type deduction compilation error

Why the code below does not compile? template <typename T> T sum(T t){ return t; } template <typename T, typename ...U> auto sum(T t, U... u) -> decltype(t + sum(u...)) { return t + sum(u...); } int main() { sum(1, 1.5, 2); } Compilation error: error: no matching function for...

## variadic boost bind type resolution

I'm trying to write an async logger which accepts variadic arguments that are then strung together using a variadic stringer and then pushed onto a single producer single consumer queue. I'm stuck in my enqueue function part of my Log struct which looks as follows: template <typename T> std::string Log::stringer(T...

## Variadic Template Parameter Packs with Alternating Types

I was wondering if it is possible to capture an alternating parameter pattern using a parameter pack. For example, template<typename T, size_t U, typename... Args> class foo<T, U, Args...> { public: foo() : my_T(nullptr), my_U(U) {} private: T* my_T; size_t my_U; foo<Args...> my_next_foo; } So this doesn't work since Args...

## Generating all subpacks of size N from a template pack

NSubsets<N, Pack<Types...>>::type is to be the pack of packs consisting of all subsets of Types... of size N. For example, NSubsets<2, Pack<int, char, double>>::type is to be Pack<Pack<int, char>, Pack<int, double>, Pack<char, double>> One method is to simply take the output of the PowerSet solution from Obtaining all subpacks from...

## How to derive from a variadic template class in C++ [closed]

I have variadic template class which is just a wrapper for std::tuple : template <typename ... Child> class Tpl { public: Tpl() {} Tpl(Child ...args) : child(args...) {} template <typename T> T& Get() { return std::get<T>(child); } template <typename T> const T& GetConst() { return std::get<T>(child); } private: std::tuple<Child ...>...

## C++11 Class template method specialization and variadic templates

I am trying to construct the following kind of templated method using GCC and C++11: class Foo { private: //Device handle cudnnHandle_t handle_; //Batch sizes std::vector<int> batch_; public: Foo(cudnnHandle_t handle, std::vector<int> batch) : handle_(handle), batch_(batch) {} template<typename T, typename... Args> T create(Args&&... args) { if(std::is_base_of<Element,T>::value) return T(handle_,args...); if(std::is_same<Block,T>::value) return T(handle_,batch_,args...);...

## Ambiguity in variadic function template

I recently started trying out various template tricks. In this case I tried to implement a class holding a sequence of numbers supplied by a variadic template utilizing a parameter pack. However, I run into some problems that do not occur on the compiler I use (Intel C++ 14), but...