C++14. Declare a function with same-type-and-fixed-length argument list
Asked Answered
A

1

8

Is there a possible way to implement sort of helper struct using C++14 which takes as a template argument a Number, return type Ret and input type T and would contain a member type std::function<Ret(T...)> where sizeof...(T) == Number?

Ahlgren answered 15/3, 2021 at 11:54 Comment(4)
This is an interesting question in itself, but do you have an application of this in mind? There might be other ways to solve the actual problem you are trying to solve.Fatty
Hi @G.Sliepen, I am trying to implement bool expression evaluator struct. It should take number of variables as a template parameter and a functor(which takes bool variables and holds expression calculation logic) as constructor argument and evaluates the expression for each possible set of those bool arguments. (e.g. a && b -> false && false, false && true, true && false, true && true). This is useful for writing unit tests to automate test case generation.Ahlgren
@MikayelSmbatyan - Good. Starting from C++14 you have std::make_index_sequence/std::index_sequence that are very useful for this sort of problems.Quantize
@StoryTeller A good quality integer sequence is a real pain to write. The naive O(n^2) memory one is easier, but blows up compile times rather quickly. C++14 comes (in practice) with a built-in integer sequence, which is both faster than a good C++11 integer sequence and doesn't require the rather painful work you need to make it good. You can answer "here is a bad implementation of integer sequence, don't use it, actually use C++14's one unless your number of elements is always small", but explanation and code literally doubles the answer length, and 99% of the time unneeded.Housemaid
Q
9

I suppose the following C++14 code can show you a way

#include <utility>
#include <functional>
#include <type_traits>

template <typename T, std::size_t>
using use_type = T;

template <typename...>
struct bar;

template <typename Ret, typename T, std::size_t ... Is>
struct bar<Ret, T, std::index_sequence<Is...>>
 { std::function<Ret(use_type<T, Is>...)> func; };

template <std::size_t N, typename Ret, typename T>
struct foo : public bar<Ret, T, std::make_index_sequence<N>>
 { };

int main ()
 {
   using T1 = std::function<void(int, int, int)>;
   using T2 = decltype(foo<3u, void, int>::func);

   static_assert( std::is_same<T1, T2>::value, "!" );
 }
Quantize answered 15/3, 2021 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.