Search Results

Search found 63 results on 3 pages for 'functor'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • C++ Boost bind value type

    - by aaa
    hello. I look in documentation and source code but cannot figure out how to get return value type of boost bind functor. I am trying to accomplish following: 35 template<typename T,size_t N, class F> 36 boost::array<typename F::value_type, N> make_array(T (&input)[N], F unary) { 37 boost::array<typename F::value_type, N> array; 38 std::transform(input, input + N, array.begin(), unary); 39 return array; 40 } where F can be bind functor. the above does not work because functor does not have value_type. for that matter, is there standard interface for unary/binary functor as far as return value. Thanks

    Read the article

  • C++ Boost bind value type {solved}

    - by aaa
    hello. I look in documentation and source code but cannot figure out how to get return value type of boost bind functor. I am trying to accomplish following: 35 template<typename T,size_t N, class F> 36 boost::array<typename F::value_type, N> make_array(T (&input)[N], F unary) { 37 boost::array<typename F::value_type, N> array; 38 std::transform(input, input + N, array.begin(), unary); 39 return array; 40 } where F can be bind functor. the above does not work because functor does not have value_type. for that matter, is there standard interface for unary/binary functor as far as return value. solution: it should be result_type. also equivalent defined are argument_type and first/second_argument_type for binary functions Thanks

    Read the article

  • Type classes or implicit parameters? What do you prefer and why? [closed]

    - by Petr Pudlák
    I was playing a bit with Scalaz and I realized that Haskell's type classes are very similar to Scala's implicit parameters. While Haskell passes the methods defined by a type class using hidden dictionaries, Scala allows a similar thing using implicit parameters. For example, in Haskell, one could write: incInside :: (Functor f) => f Int -> f Int incInside = fmap (+ 1) and the same function using Scalaz: import scalaz._; import Scalaz._; def incInside[F[_]](x: F[Int])(implicit fn: Functor[F]): F[Int] = fn.fmap(x, (_:Int) + 1); I wonder: If you could choose (i.e. your favorite language would offer both), what would you pick - implicits or type classes? And what are your pros/cons?

    Read the article

  • Step by Step / Deep explain: The Power of (Co)Yoneda (preferably in scala) through Coroutines

    - by Mzk
    some background code /** FunctorStr: ? F[-]. (? A B. (A -> B) -> F[A] -> F[B]) */ trait FunctorStr[F[_]] { self => def map[A, B](f: A => B): F[A] => F[B] } trait Yoneda[F[_], A] { yo => def apply[B](f: A => B): F[B] def run: F[A] = yo(x => x) def map[B](f: A => B): Yoneda[F, B] = new Yoneda[F, B] { def apply[X](g: B => X) = yo(f andThen g) } } object Yoneda { implicit def yonedafunctor[F[_]]: FunctorStr[({ type l[x] = Yoneda[F, x] })#l] = new FunctorStr[({ type l[x] = Yoneda[F, x] })#l] { def map[A, B](f: A => B): Yoneda[F, A] => Yoneda[F, B] = _ map f } def apply[F[_]: FunctorStr, X](x: F[X]): Yoneda[F, X] = new Yoneda[F, X] { def apply[Y](f: X => Y) = Functor[F].map(f) apply x } } trait Coyoneda[F[_], A] { co => type I def fi: F[I] def k: I => A final def map[B](f: A => B): Coyoneda.Aux[F, B, I] = Coyoneda(fi)(f compose k) } object Coyoneda { type Aux[F[_], A, B] = Coyoneda[F, A] { type I = B } def apply[F[_], B, A](x: F[B])(f: B => A): Aux[F, A, B] = new Coyoneda[F, A] { type I = B val fi = x val k = f } implicit def coyonedaFunctor[F[_]]: FunctorStr[({ type l[x] = Coyoneda[F, x] })#l] = new CoyonedaFunctor[F] {} trait CoyonedaFunctor[F[_]] extends FunctorStr[({type l[x] = Coyoneda[F, x]})#l] { override def map[A, B](f: A => B): Coyoneda[F, A] => Coyoneda[F, B] = x => apply(x.fi)(f compose x.k) } def liftCoyoneda[T[_], A](x: T[A]): Coyoneda[T, A] = apply(x)(a => a) } Now I thought I understood yoneda and coyoneda a bit just from the types – i.e. that they quantify / abstract over map fixed in some type constructor F and some type a, to any type B returning F[B] or (Co)Yoneda[F, B]. Thus providing map fusion for free (? is this kind of like a cut rule for map ?). But I see that Coyoneda is a functor for any type constructor F regardless of F being a Functor, and that I don't fully grasp. Now I'm in a situation where I'm trying to define a Coroutine type, (I'm looking at https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/coroutines-for-streaming/part-2-coroutines for the types to get started with) case class Coroutine[S[_], M[_], R](resume: M[CoroutineState[S, M, R]]) sealed trait CoroutineState[S[_], M[_], R] object CoroutineState { case class Run[S[_], M[_], R](x: S[Coroutine[S, M, R]]) extends CoroutineState[S, M, R] case class Done[R](x: R) extends CoroutineState[Nothing, Nothing, R] class CoroutineStateFunctor[S[_], M[_]](F: FunctorStr[S]) extends FunctorStr[({ type l[x] = CoroutineState[S, M, x]})#l] { override def map[A, B](f : A => B) : CoroutineState[S, M, A] => CoroutineState[S, M, B] = { ??? } } } and I think that if I understood Coyoneda better I could leverage it to make S & M type constructors functors way easy, plus I see Coyoneda potentially playing a role in defining recursion schemes as the functor requirement is pervasive. So how could I use coyoneda to make type constructors functors like for example coroutine state? or something like a Pause functor ?

    Read the article

  • C++ design question on traversing binary trees

    - by user231536
    I have a binary tree T which I would like to copy to another tree. Suppose I have a visit method that gets evaluated at every node: struct visit { virtual void operator() (node* n)=0; }; and I have a visitor algorithm void visitor(node* t, visit& v) { //do a preorder traversal using stack or recursion if (!t) return; v(t); visitor(t->left, v); visitor(t->right, v); } I have 2 questions: I settled on using the functor based approach because I see that boost graph does this (vertex visitors). Also I tend to repeat the same code to traverse the tree and do different things at each node. Is this a good design to get rid of duplicated code? What other alternative designs are there? How do I use this to create a new binary tree from an existing one? I can keep a stack on the visit functor if I want, but it gets tied to the algorithm in visitor. How would I incorporate postorder traversals here ? Another functor class?

    Read the article

  • Creating rapid function overloads in C++

    - by DeadMG
    template<typename Functor, typename Return, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> class LambdaCall : public Instruction { public: LambdaCall(Functor func ,unsigned char constructorarg1 ,unsigned char constructorarg2 ,unsigned char constructorarg3 ,unsigned char constructorarg4 ,unsigned char constructorarg5 ,unsigned char constructorarg6 ,unsigned char constructorarg7 ,unsigned char constructorarg8 ,unsigned char constructorarg9 ,unsigned char constructorarg10) : arg1(constructorarg1) , arg2(constructorarg2) , arg3(constructorarg3) , arg4(constructorarg4) , arg5(constructorarg5) , arg6(constructorarg6) , arg7(constructorarg7) , arg8(constructorarg8) , arg9(constructorarg9) , arg10(constructorarg10) , function(func) {} void Call(State& state) { state.Push<Return>(func(*state.GetRegisterValue<Arg1>(arg1) ,*state.GetRegisterValue<Arg1>(arg1) ,*state.GetRegisterValue<Arg2>(arg2) ,*state.GetRegisterValue<Arg3>(arg3) ,*state.GetRegisterValue<Arg4>(arg4) ,*state.GetRegisterValue<Arg5>(arg5) ,*state.GetRegisterValue<Arg6>(arg6) ,*state.GetRegisterValue<Arg7>(arg7) ,*state.GetRegisterValue<Arg8>(arg8) ,*state.GetRegisterValue<Arg9>(arg9) ,*state.GetRegisterValue<Arg10>(arg10) )); } Functor function; unsigned char arg1; unsigned char arg2; unsigned char arg3; unsigned char arg4; unsigned char arg5; unsigned char arg6; unsigned char arg7; unsigned char arg8; unsigned char arg9; unsigned char arg10; }; Then again for every possible number of arguments I want to support, and again for void returns. Any way to do this faster?

    Read the article

  • Multi-threaded Pooled Allocators

    - by Darren Engwirda
    I'm having some issues using pooled memory allocators for std::list objects in a multi-threaded application. The part of the code I'm concerned with runs each thread function in isolation (i.e. there is no communication or synchronization between threads) and therefore I'd like to setup separate memory pools for each thread, where each pool is not thread-safe (and hence fast). I've tried using a shared thread-safe singleton memory pool and found the performance to be poor, as expected. This is a heavily simplified version of the type of thing I'm trying to do. A lot has been included in a pseudo-code kind of way, sorry if it's confusing. /* The thread functor - one instance of MAKE_QUADTREE created for each thread */ class make_quadtree { private: /* A non-thread-safe memory pool for int linked list items, let's say that it's * something along the lines of BOOST::OBJECT_POOL */ pooled_allocator<int> item_pool; /* The problem! - a local class that would be constructed within each std::list as the * allocator but really just delegates to ITEM_POOL */ class local_alloc { public : //!! I understand that I can't access ITEM_POOL from within a nested class like //!! this, that's really my question - can I get something along these lines to //!! work?? pointer allocate (size_t n) { return ( item_pool.allocate(n) ); } }; public : make_quadtree (): item_pool() // only construct 1 instance of ITEM_POOL per // MAKE_QUADTREE object { /* The kind of data structures - vectors of linked lists * The idea is that all of the linked lists should share a local pooled allocator */ std::vector<std::list<int, local_alloc>> lists; /* The actual operations - too complicated to show, but in general: * * - The vector LISTS is grown as a quadtree is built, it's size is the number of * quadtree "boxes" * * - Each element of LISTS (each linked list) represents the ID's of items * contained within each quadtree box (say they're xy points), as the quadtree * is grown a lot of ID pop/push-ing between lists occurs, hence the memory pool * is important for performance */ } }; So really my problem is that I'd like to have one memory pool instance per thread functor instance, but within each thread functor share the pool between multiple std::list objects.

    Read the article

  • Function Composition in C++

    - by Channel72
    There are a lot of impressive Boost libraries such as Boost.Lambda or Boost.Phoenix which go a long way towards making C++ into a truly functional language. But is there a straightforward way to create a composite function from any 2 or more arbitrary functions or functors? If I have: int f(int x) and int g(int x), I want to do something like f . g which would statically generate a new function object equivalent to f(g(x)). This seems to be possible through various techniques, such as those discussed here. Certainly, you can chain calls to boost::lambda::bind to create a composite functor. But is there anything in Boost which easily allows you to take any 2 or more functions or function objects and combine them to create a single composite functor, similar to how you would do it in a language like Haskell?

    Read the article

  • Better name needed for applying a function on elements of a container

    - by stefaanv
    I have a container class (containing a multi-index container) for which I have a public "foreach" member-function, so users can pass a functor to apply on all elements. While implementing, I had a case where the functor should only be applied to some elements of a range in the container, so I overloaded the foreach, to pass some valid range. Now, in some cases, it was worthwhile to stop on a certain condition, so practically, I let the foreach stop based on the return-value of the function. I'm pleased with how the system works, but I have one concern: How should a "foreach" on a range, with stop conditions be called? Anyone knows a generic, clear and concise name?

    Read the article

  • Is this too much code for a header only library?

    - by Billy ONeal
    It seems like I had to inline quite a bit of code here. I'm wondering if it's bad design practice to leave this entirely in a header file like this: #pragma once #include <string> #include <boost/noncopyable.hpp> #include <boost/make_shared.hpp> #include <boost/iterator/iterator_facade.hpp> #include <Windows.h> #include "../Exception.hpp" namespace WindowsAPI { namespace FileSystem { class FileData; struct AllResults; struct FilesOnly; template <typename Filter_T = AllResults> class DirectoryIterator; namespace detail { class DirectoryIteratorImpl : public boost::noncopyable { WIN32_FIND_DATAW currentData; HANDLE hFind; std::wstring root; public: inline DirectoryIteratorImpl(); inline explicit DirectoryIteratorImpl(const std::wstring& pathSpec); inline void increment(); inline bool equal(const DirectoryIteratorImpl& other) const; inline const std::wstring& GetPathRoot() const; inline const WIN32_FIND_DATAW& GetCurrentFindData() const; inline ~DirectoryIteratorImpl(); }; } class FileData //Serves as a proxy to the WIN32_FIND_DATA struture inside the iterator. { boost::shared_ptr<detail::DirectoryIteratorImpl> iteratorSource; public: FileData(const boost::shared_ptr<detail::DirectoryIteratorImpl>& parent) : iteratorSource(parent) {}; DWORD GetAttributes() const { return iteratorSource->GetCurrentFindData().dwFileAttributes; }; bool IsDirectory() const { return (GetAttributes() | FILE_ATTRIBUTE_DIRECTORY) != 0; }; bool IsFile() const { return !IsDirectory(); }; bool IsArchive() const { return (GetAttributes() | FILE_ATTRIBUTE_ARCHIVE) != 0; }; bool IsReadOnly() const { return (GetAttributes() | FILE_ATTRIBUTE_READONLY) != 0; }; unsigned __int64 GetSize() const { ULARGE_INTEGER intValue; intValue.LowPart = iteratorSource->GetCurrentFindData().nFileSizeLow; intValue.HighPart = iteratorSource->GetCurrentFindData().nFileSizeHigh; return intValue.QuadPart; }; std::wstring GetFolderPath() const { return iteratorSource->GetPathRoot(); }; std::wstring GetFileName() const { return iteratorSource->GetCurrentFindData().cFileName; }; std::wstring GetFullFileName() const { return GetFolderPath() + GetFileName(); }; std::wstring GetShortFileName() const { return iteratorSource->GetCurrentFindData().cAlternateFileName; }; FILETIME GetCreationTime() const { return iteratorSource->GetCurrentFindData().ftCreationTime; }; FILETIME GetLastAccessTime() const { return iteratorSource->GetCurrentFindData().ftLastAccessTime; }; FILETIME GetLastWriteTime() const { return iteratorSource->GetCurrentFindData().ftLastWriteTime; }; }; struct AllResults : public std::unary_function<const FileData&, bool> { bool operator()(const FileData&) { return true; }; }; struct FilesOnly : public std::unary_function<const FileData&, bool> { bool operator()(const FileData& arg) { return arg.IsFile(); }; }; template <typename Filter_T> class DirectoryIterator : public boost::iterator_facade<DirectoryIterator<Filter_T>, const FileData, std::input_iterator_tag> { friend class boost::iterator_core_access; boost::shared_ptr<detail::DirectoryIteratorImpl> impl; FileData current; Filter_T filter; void increment() { do { impl->increment(); } while (! filter(current)); }; bool equal(const DirectoryIterator& other) const { return impl->equal(*other.impl); }; const FileData& dereference() const { return current; }; public: DirectoryIterator(Filter_T functor = Filter_T()) : impl(boost::make_shared<detail::DirectoryIteratorImpl>()), current(impl), filter(functor) { }; explicit DirectoryIterator(const std::wstring& pathSpec, Filter_T functor = Filter_T()) : impl(boost::make_shared<detail::DirectoryIteratorImpl>(pathSpec)), current(impl), filter(functor) { }; }; namespace detail { DirectoryIteratorImpl::DirectoryIteratorImpl() : hFind(INVALID_HANDLE_VALUE) { } DirectoryIteratorImpl::DirectoryIteratorImpl(const std::wstring& pathSpec) { std::wstring::const_iterator lastSlash = std::find(pathSpec.rbegin(), pathSpec.rend(), L'\\').base(); root.assign(pathSpec.begin(), lastSlash); hFind = FindFirstFileW(pathSpec.c_str(), &currentData); if (hFind == INVALID_HANDLE_VALUE) WindowsApiException::ThrowFromLastError(); while (!wcscmp(currentData.cFileName, L".") || !wcscmp(currentData.cFileName, L"..")) { increment(); } } void DirectoryIteratorImpl::increment() { BOOL success = FindNextFile(hFind, &currentData); if (success) return; DWORD error = GetLastError(); if (error == ERROR_NO_MORE_FILES) { FindClose(hFind); hFind = INVALID_HANDLE_VALUE; } else { WindowsApiException::Throw(error); } } DirectoryIteratorImpl::~DirectoryIteratorImpl() { if (hFind != INVALID_HANDLE_VALUE) FindClose(hFind); } bool DirectoryIteratorImpl::equal(const DirectoryIteratorImpl& other) const { if (this == &other) return true; return hFind == other.hFind; } const std::wstring& DirectoryIteratorImpl::GetPathRoot() const { return root; } const WIN32_FIND_DATAW& DirectoryIteratorImpl::GetCurrentFindData() const { return currentData; } } }}

    Read the article

  • Problem with boost::find_format_all, boost::regex_finder and custom regex formatter (bug boost 1.42)

    - by Nikko
    I have a code that has been working for almost 4 years (since boost 1.33) and today I went from boost 1.36 to boost 1.42 and now I have a problem. I'm calling a custom formatter on a string to format parts of the string that match a REGEX. For instance, a string like: "abc;def:" will be changed to "abc\2Cdef\3B" if the REGEX contains "([;:])" boost::find_format_all( mystring, boost::regex_finder( REGEX ), custom_formatter() ); The custom formatter looks like this: struct custom_formatter() { template< typename T > std::string operator()( const T & s ) const { std::string matchStr = s.match_results().str(1); // perform substitutions return matchStr; } } This worked fine but with boost 1.42 I know have "non initialized" s.match_results() which yield to boost::exception_detail::clone_implINS0_::error_info_injectorISt11logic_errorEEEE - Attempt to access an uninitialzed boost::match_results< class. This means that sometimes I am in the functor to format a string but there is no match. Am I doing something wrong? Or is it normal to enter the functor when there is no match and I should check against something? for now my solution is to try{}catch(){} the exception and everything works fine, but somehow that doesn't feel very good. EDIT1 Actually I have a new empty match at the end of each string to parse. EDIT2 : one solution inspired by ablaeul template< typename T > std::string operator()( const T & s ) const { if( s.begin() == s.end() ) return std::string(); std::string matchStr = s.match_results().str(1); // perform substitutions return matchStr; } *EDIT3 Seems to be a bug in (at least) boost 1.42 *

    Read the article

  • Function syntax puzzler in scalaz

    - by oxbow_lakes
    Following watching Nick Partidge's presentation on deriving scalaz, I got to looking at this example, which is just awesome: import scalaz._ import Scalaz._ def even(x: Int) : Validation[NonEmptyList[String], Int] = if (x % 2 ==0) x.success else "not even: %d".format(x).wrapNel.fail println( even(3) <|*|> even(5) ) //prints: Failure(NonEmptyList(not even: 3, not even: 5)) I was trying to understand what the <|*|> method was doing, here is the source code: def <|*|>[B](b: M[B])(implicit t: Functor[M], a: Apply[M]): M[(A, B)] = <**>(b, (_: A, _: B)) OK, that is fairly confusing (!) - but it references the <**> method, which is declared thus: def <**>[B, C](b: M[B], z: (A, B) => C)(implicit t: Functor[M], a: Apply[M]): M[C] = a(t.fmap(value, z.curried), b) So I have a few questions: How come the method appears to take a monad of one type parameter (M[B]) but can get passed a Validation (which has two type paremeters)? How does the syntax (_: A, _: B) define the function (A, B) => C which the 2nd method expects? It doesn't even define an output via =>

    Read the article

  • optimize output value using a class and public member

    - by wiso
    Suppose you have a function, and you call it a lot of times, every time the function return a big object. I've optimized the problem using a functor that return void, and store the returning value in a public member: #include <vector> const int N = 100; std::vector<double> fun(const std::vector<double> & v, const int n) { std::vector<double> output = v; output[n] *= output[n]; return output; } class F { public: F() : output(N) {}; std::vector<double> output; void operator()(const std::vector<double> & v, const int n) { output = v; output[n] *= n; } }; int main() { std::vector<double> start(N,10.); std::vector<double> end(N); double a; // first solution for (unsigned long int i = 0; i != 10000000; ++i) a = fun(start, 2)[3]; // second solution F f; for (unsigned long int i = 0; i != 10000000; ++i) { f(start, 2); a = f.output[3]; } } Yes, I can use inline or optimize in an other way this problem, but here I want to stress on this problem: with the functor I declare and construct the output variable output only one time, using the function I do that every time it is called. The second solution is two time faster than the first with g++ -O1 or g++ -O2. What do you think about it, is it an ugly optimization?

    Read the article

  • SFINAE and detecting if a C++ function object returns void.

    - by Tom Swirly
    I've read the various authorities on this, include Dewhurst and yet haven't managed to get anywhere with this seemingly simple question. What I want to do is to call a C++ function object, (basically, anything you can call, a pure function or a class with ()), and return its value, if that is not void, or "true" otherwise. #include <stdio.h> struct Foo { void operator()() {} }; struct Bar { bool operator()() { return false; } }; Foo foo; Bar bar; bool baz() { return false; } void bang() {} const char* print(bool b) { printf(b ? "true, " : "false, "); } template <typename Functor> bool magicCallFunction(Functor f) { return true; // lots of template magic occurs here... } int main(int argc, char** argv) { print(magicCallFunction(foo)); print(magicCallFunction(bar)); print(magicCallFunction(baz)); print(magicCallFunction(bang)); printf("\n"); }

    Read the article

  • Difference between std::result_of and decltype

    - by Luc Touraille
    I have some trouble understanding the need for std::result_of in C++0x. If I understood correctly, result_of is used to obtain the resulting type of invoking a function object with certain types of parameters. For example: template <typename F, typename Arg> typename std::result_of<F(Arg)> invoke(F f, Arg a) { return f(a); } I don't really see the difference with the following code: template <typename F, typename Arg> auto invoke(F f, Arg a) -> decltype(f(a)) //uses the f parameter { return f(a); } or template <typename F, typename Arg> auto invoke(F f, Arg a) -> decltype(F()(a)); //"constructs" an F { return f(a); } The only problem I can see with these two solutions is that we need to either: have an instance of the functor to use it in the expression passed to decltype. know a defined constructor for the functor. Am I right in thinking that the only difference between decltype and result_of is that the first one needs an expression whereas the second does not?

    Read the article

  • Is do-notation specific to "base:GHC.Base.Monad"?

    - by yairchu
    The idea that the standard Monad class is flawed and that it should actually extend Functor or Pointed is floating around. I'm not necessarily claiming that it is the right thing to do, but suppose that one was trying to do it: import Prelude hiding (Monad(..)) class Functor m => Monad m where return :: a -> m a join :: m (m a) -> m a join = (>>= id) (>>=) :: m a -> (a -> m b) -> m b a >>= t = join (fmap t a) (>>) :: m a -> m b -> m b a >> b = a >>= const b So far so good, but then when trying to use do-notation: whileM :: Monad m => m Bool -> m () whileM iteration = do done <- iteration if done then return () else whileM iteration The compiler complains: Could not deduce (base:GHC.Base.Monad m) from the context (Monad m) Question: Does do-notation work only for base:GHC.Base.Monad? Is there a way to make it work with an alternative Monad class? Extra context: What I really want to do is replace base:Control.Arrow.Arrow with a "generalized" Arrow class: {-# LANGUAGE TypeFamilies #-} class Category a => Arrow a where type Pair a :: * -> * -> * arr :: (b -> c) -> a b c first :: a b c -> a (Pair a b d) (Pair a c d) second :: a b c -> a (Pair a d b) (Pair a d c) (***) :: a b c -> a b' c' -> a (Pair a b b') (Pair a c c') (&&&) :: a b c -> a b c' -> a b (Pair a c c') And then use the Arrow's proc-notation with my Arrow class, but that fails like in the example above of do-notation and Monad. I'll use mostly Either as my pair type constructor and not the (,) type constructor as with the current Arrow class. This might allow to make the code of my toy RTS game (cabal install DefendTheKind) much prettier.

    Read the article

  • How to pass operators as parameters

    - by Rodion Ingles
    I have to load an array of doubles from a file, multiply each element by a value in a table (different values for different elements), do some work on it, invert the multiplication (that is, divide) and then save the data back to file. Currently I implement the multiplication and division process in two separate methods. Now there is some extra work behind the scenes but apart from the specific statements where the multiplication/division occurs, the rest of the code is identical. As you can imagine, with this approach you have to be very careful making any changes. The surrounding code is not trivial, so its either a case of manually editing each method or copying changes from one method to the other and remembering to change the * and / operators. After too many close calls I am fed up of this and would like to make a common function which implements the common logic and two wrapper functions which pass which operator to use as a parameter. My initial approach was to use function pointers: MultiplyData(double data) { TransformData(data, &(operator *)); } DivideData(double data) { TransformData(data, &(operator /)); } TransformData(double data, double (*func)(double op1, double op2)) { /* Do stuff here... */ } However, I can't pass the operators as pointers (is this because it is an operator on a native type?), so I tried to use function objects. Initially I thought that multiplies and divides functors in <functional> would be ideal: MultiplyData(double data) { std::multiplies<double> multFunct; TransformData(data, &multFunct); } DivideData(double data) { std::divides<double> divFunct; TransformData(data, &divFunct); } TransformData(double data, std::binary_function<double, double, double> *funct) { /* Do stuff here... */ } As you can see I was trying to use a base class pointer to pass the functor polymorphically. The problem is that std::binary_function does not declare an operator() member for the child classes to implement. Is there something I am missing, or is the solution to implement my own functor heirarchy (which really seems more trouble than it is worth)?

    Read the article

  • any stl/boost functors to call operator()

    - by Voivoid
    template <typename T> struct Foo { void operator()(T& t) { t(); } }; Is there any standart or boost functor with the similar implementation? I need it to iterate over container of functors: std::for_each(beginIter, endIter, Foo<Bar>()); Or maybe there are other way to do it?

    Read the article

  • how to group by over anonymous type with vb.net linq to object

    - by smoothdeveloper
    I'm trying to write a linq to object query in vb.net, here is the c# version of what I'm trying to achieve (I'm running this in linqpad): void Main() { var items = GetArray( new {a="a",b="a",c=1} , new {a="a",b="a",c=2} , new {a="a",b="b",c=1} ); ( from i in items group i by new {i.a, i.b} into g let p = new{ k = g, v = g.Sum((i)=>i.c)} where p.v > 1 select p ).Dump(); } // because vb.net doesn't support anonymous type array initializer, it will ease the translation T[] GetArray<T>(params T[] values){ return values; } I'm having hard time with either the group by syntax which is not the same (vb require 'identifier = expression' at some places, as well as with the summing functor with 'expression required' ) Thanks so much for your help!

    Read the article

  • Seeking Functional Programming Lexicon

    - by Randall Schulz
    Hi, Knowing the argot of a field helps me a lot, especially since it allows me to converse intelligently with those who know a lot more than I, so I would like to find a good lexicon of Functional Programming terms. E.g., I repeatedly encounter these: Functor, Arrow, Category, Kleisli, Monad, Monoid, a veritable zoo of Morphisms, etc. I also notice many of these appear with prefixes such as "covariant", "co-", "endo-" etc. Of these, I can say I actually understand Monoid and Covariant and sort of get Monad, but the rest are still gibberish to me. (Note that I don't mean this list as exhaustive and I'm not looking to have these defined or described for me here, I'm looking for learning resources.) Can someone point me towards an FP lexicon? It need not be on-line, as long as it's possible to find it (and it's not a rare volume for which I'd have to pay many tens of dollars).

    Read the article

  • How to use/manipulate return value from nested boost::bind

    - by JQ
    I have two functions: 1. A & DataSource(); 2. void DataConsumer( A * ); What I want to achieve: Using one statement to assemble them into one functor. I have tried: 1. boost::function< void() func( boost::bind( DataConsumer, & boost::bind( DataSource ) ) ); certainly it didn't work, compiler says it can not convert 'boost::_bi::bind_t ' to 'A *' 2. boost::function< void() func( boost::bind( DataConsumer, boost::addressof( boost::bind( DataSource ) ) )); compiler says cannot convert parameter 1 from 'boost::_bi::bind_t' to 'A &' Question: how to use return value from the nested boost::bind ? or if you want to use boost::lambda::bind.

    Read the article

  • How to combine template partial specialization and template argument deduction

    - by KKKoo0
    My understanding is that template argument deduction is only for function templates, but function templates does not allow partial specialization. Is there a way to achieve both? I basically want to achieve a function-like object (can be a functor) with the signature template<class InputIterator1, class InputIterator2, class OutputIterator, int distribution> void GetQuantity(InputIterator1 frist1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, double supply, double limit); Depending on the value of distribution, I want to have a couple of specializations of this template. And when I call this function,I basically do not want to specify all the type parameters, because they are many of them (and thus I need argument deduction)!

    Read the article

  • What is lifetime of lambda-derived implicit functors in C++ ?

    - by Fyodor Soikin
    The question is simple: what is lifetime of that functor object that is automatically generated for me by the C++ compiler when I write a lambda-expression? I did a quick search, but couldn't find a satisfactory answer. In particular, if I pass the lambda somewhere, and it gets remembered there, and then I go out of scope, what's going to happen once my lambda is called later and tries to access my stack-allocated, but no longer alive, captured variables? Or does the compiler prevent such situation in some way? Or what?

    Read the article

  • C++ domain specific embedded language operators

    - by aaa
    hi. In numerical oriented languages (Matlab, Fortran) range operator and semantics is very handy when working with multidimensional data. For example: A(i:j,k,:n) // represents two-dimensional slice B(i:j,0:n) of A at index k unfortunately C++ does not have range operator (:). of course it can be emulated using range/slice functor, but semantics is less clean than Matlab. I am prototyping matrix/tensor domain language in C++ and am wondering if there any options to reproduce range operator. I still would like to rely on C++/prprocessor framework exclusively. So far I have looked through boost wave which might be an suitable option. is there any other means to introduce new operators to C++ DSL?

    Read the article

< Previous Page | 1 2 3  | Next Page >