logo
down
shadow

How to `std::bind()` a standard library algorithm?


How to `std::bind()` a standard library algorithm?

By : rexxar06
Date : November 17 2020, 04:28 AM
will help you When trying to std::bind() an overloaded function the compiler can't determine which overload to use: at the time the bind()-expression is evaluated the function arguments are unknown, i.e., overload resolution can't decide which overload to pick. There is no direct way in in C++ [yet?] to treat an overload set as an object. Function templates simply generate an overload set with one overload for each possible instantiation. That is, the entire problem of not being able to std::bind() any of the standard C++ library algorithms revolves around the fact that the standard library algorithms are function templates.
One approach to have the same effect as std::bind()ing an algorithm is to use C++14 generic lambdas to do the binding, e.g.:
code :
auto copy = [](auto&&... args){
    return std::transform(std::forward<decltype(args)>(args)..., identity());
};
namespace nstd {
    auto const transform = [](auto&&... args){
        return std::transform(std::forward<decltype(args)>(args...));
    };
}
auto copy = std::bind(nstd::transform, P::_1, P::_2, P::_3, identity());
struct transform_t {
    template <typename... Args>
    auto operator()(Args&&... args) const
        -> decltype(std::transform(std::forward<decltype(args)>(args)...)) {
        return std::transform(std::forward<decltype(args)>(args)...);
    }
};
constexpr transform_t transform{};
template <typename Fun, typename Bound>
auto curry_last(Fun&& fun, Bound&& bound) {
    return [fun = std::forward<Fun>(fun),
            bound = std::forward<Bound>(bound)](auto&&... args){
        return fun(std::forward<decltype(args)>(args)..., bound);
    };
}
auto const copy = curry_last(nstd::transform, identity());


Share : facebook icon twitter icon
Standard library partition algorithm

Standard library partition algorithm


By : user7009786
Date : March 29 2020, 07:55 AM
will help you Your version is close to Nico Lomuto partition. Such partition works on ForwardIterators and is semi-stable (first part is stable, which can be useful in some circumstances).
Version from implementation of standard library which you quoted is close to partition described by C. A. R. Hoare at his paper "Quicksort". It works on BidirectionalIterators, and does not imply any stability.
code :
FTTTT
FTTTT
TFTTT
TTFTT
TTTFT
TTTTF
FTTTT
TTTTF
#include <initializer_list>
#include <forward_list>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
using namespace std;

int counter = 0;

struct T
{
    int value;
    T(int x = 0) : value(x) {}
    T(const T &x)
    {
        ++counter;
        value = x.value;
    }
    T &operator=(const T &x)
    {
        ++counter;
        value = x.value;
        return *this;
    }
};
auto pred = [](const T &x){return x.value;};

template<typename Container>
void test()
{
    Container l = {0, 1, 1, 1, 1};
    counter = 0;
    partition(begin(l), end(l), pred);
    cout << "Moves count: " << counter << endl;
}

int main()
{
    test<forward_list<T>>();
    test<list<T>>();
}
Moves count: 12
Moves count: 3
Is there a subsequence algorithm in the Standard Library?

Is there a subsequence algorithm in the Standard Library?


By : Adnan Ali
Date : March 29 2020, 07:55 AM
like below fixes the issue std::search in
std::search at cplusplus.com
std::function/bind like type-erasure without Standard C++ library

std::function/bind like type-erasure without Standard C++ library


By : maxming2333
Date : March 29 2020, 07:55 AM
I wish this helpful for you A solid, efficient, std::function replacement isn't hard to write.
As we are embedded, we want to avoid allocating memory. So I'd write a small_task< Signature, size_t sz, size_t algn >. It creates a buffer of size sz and alignment algn in which it stores its erased objects.
code :
template<class Sig, size_t sz, size_t algn>
struct small_task;

template<class R, class...Args, size_t sz, size_t algn>
struct small_task<R(Args...), sz, algn>{
  struct vtable_t {
    void(*mover)(void* src, void* dest);
    void(*destroyer)(void*);
    R(*invoke)(void const* t, Args&&...args);
    template<class T>
    static vtable_t const* get() {
      static const vtable_t table = {
        [](void* src, void*dest) {
          new(dest) T(std::move(*static_cast<T*>(src)));
        },
        [](void* t){ static_cast<T*>(t)->~T(); },
        [](void const* t, Args&&...args)->R {
          return (*static_cast<T const*>(t))(std::forward<Args>(args)...);
        }
      };
      return &table;
    }
  };
  vtable_t const* table = nullptr;
  std::aligned_storage_t<sz, algn> data;
  template<class F,
    class dF=std::decay_t<F>,
    // don't use this ctor on own type:
    std::enable_if_t<!std::is_same<dF, small_task>{}>* = nullptr,
    // use this ctor only if the call is legal:
    std::enable_if_t<std::is_convertible<
      std::result_of_t<dF const&(Args...)>, R
    >{}>* = nullptr
  >
  small_task( F&& f ):
    table( vtable_t::template get<dF>() )
  {
    // a higher quality small_task would handle null function pointers
    // and other "nullable" callables, and construct as a null small_task

    static_assert( sizeof(dF) <= sz, "object too large" );
    static_assert( alignof(dF) <= algn, "object too aligned" );
    new(&data) dF(std::forward<F>(f));
  }
  // I find this overload to be useful, as it forces some
  // functions to resolve their overloads nicely:
  // small_task( R(*)(Args...) )
  ~small_task() {
    if (table)
      table->destroyer(&data);
  }
  small_task(small_task&& o):
    table(o.table)
  {
    if (table)
      table->mover(&o.data, &data);
  }
  small_task(){}
  small_task& operator=(small_task&& o){
    // this is a bit rude and not very exception safe
    // you can do better:
    this->~small_task();
    new(this) small_task( std::move(o) );
    return *this;
  }
  explicit operator bool()const{return table;}
  R operator()(Args...args)const{
    return table->invoke(&data, std::forward<Args>(args)...);
  }
};

template<class Sig>
using task = small_task<Sig, sizeof(void*)*4, alignof(void*) >;
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;
using size_t=decltype(sizeof(int));
template<class T>
T&& move(T&t){return static_cast<T&&>(t);}
template<class T>
struct remove_reference:tag<T>{};
template<class T>
struct remove_reference<T&>:tag<T>{};
template<class T>using remove_reference_t=type_t<remove_reference<T>>;

template<class T>
T&& forward( remove_reference_t<T>& t ) {
  return static_cast<T&&>(t);
}
template<class T>
T&& forward( remove_reference_t<T>&& t ) {
  return static_cast<T&&>(t);
}
template<class T>
struct remove_const:tag<T>{};
template<class T>
struct remove_const<T const>:tag<T>{};

template<class T>
struct remove_volatile:tag<T>{};
template<class T>
struct remove_volatile<T volatile>:tag<T>{};

template<class T>
struct remove_cv:remove_const<type_t<remove_volatile<T>>>{};


template<class T>
struct decay3:remove_cv<T>{};
template<class R, class...Args>
struct decay3<R(Args...)>:tag<R(*)(Args...)>{};
template<class T>
struct decay2:decay3<T>{};
template<class T, size_t N>
struct decay2<T[N]>:tag<T*>{};

template<class T>
struct decay:decay2<remove_reference_t<T>>{};

template<class T>
using decay_t=type_t<decay<T>>;
template<class T>
T declval(); // no implementation

template<class T, T t>
struct integral_constant{
  static constexpr T value=t;
  constexpr integral_constant() {};
  constexpr operator T()const{ return value; }
  constexpr T operator()()const{ return value; }
};
template<bool b>
using bool_t=integral_constant<bool, b>;
using true_type=bool_t<true>;
using false_type=bool_t<false>;

template<class...>struct voider:tag<void>{};
template<class...Ts>using void_t=type_t<voider<Ts...>>;

namespace details {
  template<template<class...>class Z, class, class...Ts>
  struct can_apply:false_type{};
  template<template<class...>class Z, class...Ts>
  struct can_apply<Z, void_t<Z<Ts...>>, Ts...>:true_type{};
}
template<template<class...>class Z, class...Ts>
using can_apply = details::can_apply<Z, void, Ts...>;

namespace details {
  template<class From, class To>
  using try_convert = decltype( To{declval<From>()} );
}
template<class From, class To>
struct is_convertible : can_apply< details::try_convert, From, To > {};
template<>
struct is_convertible<void,void>:true_type{};
template<bool, class=void>
struct enable_if {};
template<class T>
struct enable_if<true, T>:tag<T>{};
template<bool b, class T=void>
using enable_if_t=type_t<enable_if<b,T>>;
namespace details {
  template<class F, class...Args>
  using invoke_t = decltype( declval<F>()(declval<Args>()...) );

  template<class Sig,class=void>
  struct result_of {};
  template<class F, class...Args>
  struct result_of<F(Args...), void_t< invoke_t<F, Args...> > >:
    tag< invoke_t<F, Args...> >
  {};
}
template<class Sig>
using result_of = details::result_of<Sig>;
template<class Sig>
using result_of_t=type_t<result_of<Sig>>;
template<size_t size, size_t align>
struct alignas(align) aligned_storage_t {
  char buff[size];
};
template<class A, class B>
struct is_same:false_type{};
template<class A>
struct is_same<A,A>:true_type{};
How to use std::bind with the standard library and save the return type?

How to use std::bind with the standard library and save the return type?


By : Heather Knowlton
Date : March 29 2020, 07:55 AM
wish help you to fix your issue
Note: I don't want to use an external library like boost and I don't know what's the kind of function the user will pass it.
code :
#include <iostream>
#include <functional>
#include <memory>


struct ACmd
{
  virtual void exec() = 0;
  virtual ~ACmd(){}
};

template <class F>
struct Cmd;

template <class R, class ... Args>
struct Cmd<R(Args...)> : ACmd
{
  R result_;
  std::function<R()> func_;

  template <class F>
  Cmd(F&& func, Args&&... args): result_(), func_()
  {
    auto f = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
    func_ = [f](){
      return f();
    };
  }

  virtual void exec(){
    result_ = func_();
  }

  const R& getResult() const {return result_;}
};

// Make function for convenience, could return by value or ptr - 
//  - your choice
template <class R, class F, class ...Args>
Cmd<R(Args...)>* cmd(F&& func, Args&&... args)
{
  return new Cmd<R(Args...)>(func, std::forward<Args>(args)...);
}

//... And overload for void...

int foo(int arg) {
  return arg;   
}

int main() {

  auto x = cmd<int>(foo, 10);
  x->exec();
  std::cout << x->getResult() << std::endl;
  return 0;
}
With which algorithm exponential functions are computed in the GNU C++ Standard Library?

With which algorithm exponential functions are computed in the GNU C++ Standard Library?


By : TraydenT
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , It doesn't use any intricate algorithm at all. Note that std::exp is only defined for a very limited number of types: float, double and long double + any Integral type that is castable to double. That makes it not necessary to implement complicated maths.
Currently, it uses the builtin __builtin_expf as can be verified from the source code. This compiles to a call to expf on my machine which is a call into libm coming from glibc. Let's see what we find in their source code. When we search for expf we find that this internally calls __ieee754_expf which is a system-dependant implementation. Both i686 and x86_64 just include a glibc/sysdeps/ieee754/flt-32/e_expf.c which finally gives us an implementation (reduced for brevity, the look into the sources
code :
static inline uint32_t
top12 (float x)
{
  return asuint (x) >> 20;
}

float
__expf (float x)
{
  uint64_t ki, t;
  /* double_t for better performance on targets with FLT_EVAL_METHOD==2.  */
  double_t kd, xd, z, r, r2, y, s;

  xd = (double_t) x;
  // [...] skipping fast under/overflow handling

  /* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k.  */
  z = InvLn2N * xd;

  /* Round and convert z to int, the result is in [-150*N, 128*N] and
     ideally ties-to-even rule is used, otherwise the magnitude of r
     can be bigger which gives larger approximation error.  */
  kd = roundtoint (z);
  ki = converttoint (z);
  r = z - kd;

  /* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */
  t = T[ki % N];
  t += ki << (52 - EXP2F_TABLE_BITS);
  s = asdouble (t);
  z = C[0] * r + C[1];
  r2 = r * r;
  y = C[2] * r + 1;
  y = z * r2 + y;
  y = y * s;
  return (float) y;
}
Related Posts Related Posts :
  • Vector of pointers: some clarification needed
  • scaling a bitmap without losing quality
  • How to evaluate a function directly?
  • QNetworkAccessManager: How to change post data at createRequest function
  • Returning std::move of a local variable
  • Is there a fast linear SVM library with a good C++ interface?
  • What is the purpose of name mangling in C++?
  • C++ Why the void function is not working eventhough I called it?
  • How the pointer and the pointer's adress can share the same memory adress?
  • error C2220: warning treated as error - no 'object' file generated
  • exception of strcpy function in c++ console program
  • How to access USB barcode scanner data directly from USB port using C/C++ without driver
  • Under which circumstances will std::vector.clear() call a destructor?
  • Template partial specialisation and dependent names
  • best way to share data between c codes
  • C++ ignores if statement conditions
  • How to set the argv[ ] to be case-insensitive in a Win32 Console Application?
  • How to fix error "clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)"?
  • C++ How do I print a .txt file verbatim?
  • Creating two dimensional array of class
  • How do I correctly use COMMTIMEOUTS with OVERLAPPED IO mode reading from a Serial port
  • An assert macro which expands to static_assert when possible?
  • How to write a copyconstructor for a class which has HANDLE as a member in win32 c++ application?
  • C++ saving info such as tree in a file
  • Transforming an expression template tree
  • How to overload an operator with multiple parameters like a + b + c?
  • C++ 11 with Raspberry Pi performances
  • Make a C++ class look like a numpy array using swig
  • Postfix incrementer overloading for nested enumerated types
  • Is there a tidy way of associating metadata with functions in C++
  • QObject::installEventFilter(): Cannot filter events for objects in a different thread
  • LNK2005 error with Zxing C++
  • C++ Doubly Linked List with Pointers: Object of class isn't constructed properly
  • Using a random string generator in c++ constructor
  • What should I use instead of void as one of the alternative types in an variant?
  • C++ return value from multithreads using reference
  • How to connect multiple TCP IP clients to same server port using c++
  • Defaul compiler generates the reference operator (In C++)?
  • Unable to change directory time stamp after using FILE_FLAG_BACKUP_SEMANTICS
  • vector handling displaying output
  • WSAGetLastError returns WSAENOTSOCK - Cause?
  • C++: How to overload pow for user type?
  • C++ using arrays as multidimensional despite initalising it as 1D with pointer
  • How negate std::is_integral for use in tag dispatch?
  • Retrieve serial number from USB memory (Windows environment c++)
  • g++ error: invalid preprocessing directive #INCLUDE
  • C++ What is the std::for_each() function parameter type?
  • C++: Read individual lines from text file, sort words alphabetically
  • Saving 'this' address into a variable
  • c++ command line arguments in ubuntu terminal
  • Convert "Cartesian coordinates" to "polar coordinates with respect to user specified origin"
  • In what order are local scoped objects destructed?
  • How to use SDL_MapRGB with SDL 2.0
  • how compiler and interpreter work in case of array declaration
  • GSL integration behaves strange
  • Cropping an image with OpenCV and C
  • Find the last line in text file and select the first 10 char and print to a new file?
  • Created many CCSprits but when triggering ccTouchBegan gives the last one allways
  • seekp and seekg don't work with fstream
  • Taking input in Sublime Text 3
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org