Search Results

Search found 9134 results on 366 pages for 'variadic functions'.

Page 1/366 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Functions inside page using Razor View Engine – ASP.NET MVC

    - by hajan
    As we already know, Razor is probably the best view engine for ASP.NET MVC so far. It keeps your code fluid and very expressive. Besides the other functionalities Razor has, it also supports writing local functions. If you want to write a function, you can’t just open new @{ } razor block and write it there… it won’t work. Instead, you should specify @functions { } so that inside the brackets you will write your own C#/VB.NET functions/methods. Lets see an example: 1. I have the following loop that prints data using Razor <ul> @{     int N = 10;     for (int i = 1; i<=N; i++)     {         <li>Number @i</li>     }     } </ul> This code will print the numbers from 1 to 10: Number 1 Number 2 Number 3 Number 4 Number 5 Number 6 Number 7 Number 8 Number 9 Number 10 So, now lets write a function that will check if current number is even, if yes… add Even before Number word. Function in Razor @functions{     public bool isEven(int number)     {         return number % 2 == 0 ? true : false;     } } The modified code which creates unordered list is: <ul> @{     int N = 10;     for (int i = 1; i<=N; i++)     {         if (isEven(@i)) {             <li>Even number @i</li>         }         else {             <li>Number @i</li>         }                 }             } </ul> As you can see, in the modified code we use the isEven(@i) function to check if the current number is even or not… The result is: Number 1 Even number 2 Number 3 Even number 4 Number 5 Even number 6 Number 7 Even number 8 Number 9 Even number 10 So, the main point of this blog was to show how you can define your own functions inside page using Razor View Engine. Of course you can define multiple functions inside the same @functions { } defined razor statement. The complete code: @{     Layout = null; } <!DOCTYPE html> <html> <head>     <title>ASP.NET MVC - Razor View Engine :: Functions</title> </head> <body>     <div>         <ul>         @{             int N = 10;             for (int i = 1; i<=N; i++)             {                 if (isEven(@i)) {                     <li>Even number @i</li>                 }                 else {                     <li>Number @i</li>                 }                         }                     }         </ul>         @functions{             public bool isEven(int number)             {                 return number % 2 == 0 ? true : false;             }         }     </div> </body> </html> Hope you like it. Regards, Hajan

    Read the article

  • Network programming under windows: is WSA functions can be more complete than pSock functions [on hold]

    - by Kane
    I plan to make a set of classic socket functions to simplify their usages. Since i work under windows and linux indifferently i usually make it portable (it's not my first version of this set of functions), but i want to do something different this time and dedicate one version to windows, and one other to linux. With that i wonder for the windows version, if the WSA* functions can have any interest using them instead of the psock ones. I have found nothing about a comparison between them, so if any of you have any idea, suggestion, link or benchmark ?

    Read the article

  • Construct a variadic template of unsigned int recursively

    - by Vincent
    I need a tricky thing in a C++ 2011 code. Currently, I have a metafunction of this kind : template<unsigned int N, unsigned int M> static constexpr unsigned int myFunction() This function can generate number based on N and M. I would like to write a metafunction with input N and M, and that will recursively construct a variadic template by decrementing M. For example, by calling this function with M = 3, It will construct a variadic template called List equal to : List... = myFunction<N, 3>, myFunction<N, 2>, myFunction<N, 1>, myFunction<N, 0> How to do that (if it is possible of course) ?

    Read the article

  • Why is forwarding variadic parameters invalid?

    - by awesomeyi
    Consider the variadic function parameter: func foo(bar:Int...) -> () { } Here foo can accept multiple arguments, eg foo(5,4). I am curious about the type of Int... and its supported operations. For example, why is this invalid? func foo2(bar2:Int...) -> () { foo(bar2); } Gives a error: Could not find an overload for '_conversion' that accepts the supplied arguments Why is forwarding variadic parameters invalid? What is the "conversion" the compiler is complaining about?

    Read the article

  • Mixins, variadic templates, and CRTP in C++

    - by Eitan
    Here's the scenario: I'd like to have a host class that can have a variable number of mixins (not too hard with variadic templates--see for example http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.103.144). However, I'd also like the mixins to be parameterized by the host class, so that they can refer to its public types (using the CRTP idiom). The problem arises when trying to mix the too--the correct syntax is unclear to me. For example, the following code fails to compile with g++ 4.4.1: template <template<class> class... Mixins> class Host : public Mixins<Host<Mixins>>... { public: template <class... Args> Host(Args&&... args) : Mixins<Host>(std::forward<Args>(args))... {} }; template <class Host> struct Mix1 {}; template <class Host> struct Mix2 {}; typedef Host<Mix1, Mix2> TopHost; TopHost *th = new TopHost(Mix1<TopHost>(), Mix2<TopHost>()); With the error: tst.cpp: In constructor ‘Host<Mixins>::Host(Args&& ...) [with Args = Mix1<Host<Mix1, Mix2> >, Mix2<Host<Mix1, Mix2> >, Mixins = Mix1, Mix2]’: tst.cpp:33: instantiated from here tst.cpp:18: error: type ‘Mix1<Host<Mix1, Mix2> >’ is not a direct base of ‘Host<Mix1, Mix2>’ tst.cpp:18: error: type ‘Mix2<Host<Mix1, Mix2> >’ is not a direct base of ‘Host<Mix1, Mix2>’ Does anyone have successful experience mixing variadic templates with CRTP?

    Read the article

  • How to properly use references with variadic templates

    - by Hippicoder
    I have something like the following code: template<typename T1, typename T2, typename T3> void inc(T1& t1, T2& t2, T3& t3) { ++t1; ++t2; ++t3; } template<typename T1, typename T2> void inc(T1& t1, T2& t2) { ++t1; ++t2; } template<typename T1> void inc(T1& t1) { ++t1; } I'd like to reimplement it using the proposed variadic templates from the upcoming standard. However all the examples I've seen so far online seem to be printf like examples, the difference here seems to be the use of references. I've come up with the following: template<typename T> void inc(T&& t) { ++t; } template<typename T,typename ... Args> void inc(T&& t, Args&& ... args) { ++t inc(args...); } What I'd like to know is: Should I be using r-values instead of references? Possible hints or clues as to how to accomplish what I want correctly. What guarantees does the new proposed standard provide wrt the issue of the recursive function calls, is there some indication that the above variadic version will be as optimal as the original? (should I add inline or some-such?)

    Read the article

  • helper functions as static functions or procedural functions?

    - by fayer
    i wonder if one should create a helper function in a class as a static function or just have it declared as a procedural function? i tend to think that a static helper function is the right way to go cause then i can see what kind of helper function it is eg. Database::connect(), File::create(). what is best practice?

    Read the article

  • F#: any way to use member functions as unbound functions?

    - by gatoatigrado
    Is there a way to extract member functions, and use them as F# functions? I'd like to be able to write the following: mystring |> string.Split '\n' |> Array.filter (string.Length >> (=) 0 >> not) The code above works if you [let] let mystring = "a c\nb\n" let stringSplit (y:char) (x:string) = x.Split(y) let stringLength (x:string) = x.Length mystring |> stringSplit '\n' |> Array.filter (stringLength >> (=) 0 >> not)

    Read the article

  • Python — Time complexity of built-in functions versus manually-built functions in finite fields

    - by stackuser
    Generally, I'm wondering about the advantages versus disadvantages of using the built-in arithmetic functions versus rolling your own in Python. Specifically, I'm taking in GF(2) finite field polynomials in string format, converting to base 2 values, performing arithmetic, then output back into polynomials as string format. So a small example of this is in multiplication: Rolling my own: def multiply(a,b): bitsa = reversed("{0:b}".format(a)) g = [(b<<i)*int(bit) for i,bit in enumerate(bitsa)] return reduce(lambda x,y: x+y,g) Versus the built-in: def multiply(a,b): # a,b are GF(2) polynomials in binary form .... return a*b #returns product of 2 polynomials in gf2 Currently, operations like multiplicative inverse (with for example 20 bit exponents) take a long time to run in my program as it's using all of Python's built-in mathematical operations like // floor division and % modulus, etc. as opposed to making my own division, remainder, etc. I'm wondering how much of a gain in efficiency and performance I can get by building these manually (as shown above). I realize the gains are dependent on how well the manual versions are built, that's not the question. I'd like to find out 'basically' how much advantage there is over the built-in's. So for instance, if multiplication (as in the example above) is well-suited for base 10 (decimal) arithmetic but has to jump through more hoops to change bases to binary and then even more hoops in operating (so it's lower efficiency), that's what I'm wondering. Like, I'm wondering if it's possible to bring the time down significantly by building them myself in ways that maybe some professionals here have already come across.

    Read the article

  • Reordering Variadic Parameters

    - by void-pointer
    I have come across the need to reorder a variadic list of parameters that is supplied to the constructor of a struct. After being reordered based on their types, the parameters will be stored as a tuple. My question is how this can be done so that a modern C++ compiler (e.g. g++-4.7) will not generate unnecessary load or store instructions. That is, when the constructor is invoked with a list of parameters of variable size, it efficiently pushes each parameter into place based on an ordering over the parameters' types. Here is a concrete example. Assume that the base type of every parameter (without references, rvalue references, pointers, or qualifiers) is either char, int, or float. How can I make it so that all the parameters of base type char appear first, followed by all of those of base type int (which leaves the parameters of base type float last). The relative order in which the parameters were given should not be violated within sublists of homogeneous base type. Example: foo::foo() is called with arguments float a, char&& b, const float& c, int&& d, char e. The tuple tupe is std::tuple<char, char, int, float, float>, and it is constructed like so: tuple_type{std::move(b), e, std::move(d), a, c}. Consider the struct defined below, and assume that the metafunction deduce_reordered_tuple_type is already implemented. How would you write the constructor so that it works as intended? If you think that the code for deduce_reodered_tuple_type, would be useful to you, I can provide it; it's a little long. template <class... Args> struct foo { // Assume that the metafunction deduce_reordered_tuple_type is defined. typedef typename deduce_reordered_tuple_type<Args...>::type tuple_type; tuple_type t_; foo(Args&&... args) : t_{reorder_and_forward_parameters<Args>(args)...} {} }; Edit 1 The technique I describe above does have applications in mathematical frameworks that make heavy use of expression templates, variadic templates, and metaprogramming in order to perform aggressive inlining. Suppose that you wish to define an operator that takes the product of several expressions, each of which may be passed by reference, reference to const, or rvalue reference. (In my case, the expressions are conditional probability tables and the operation is the factor product, but something like matrix multiplication works suitably as well.) You need access to the data provided by each expression in order to evaluate the product. Consequently, you must move the expressions passed as rvalue references, copy the expressions passed by reference to const, and take the addresses of expressions passed by reference. Using the technique I describe above now poses several benefits. Other expressions can use uniform syntax to access data elements from this expression, since all of the heavy-lifting metaprogramming work is done beforehand, within the class. We can save stack space by grouping the pointers together and storing the larger expressions towards the end of the tuple. Implementing certain types of queries becomes much easier (e.g. check whether any of the pointers stored in the tuple aliases a given pointer). Thank you very much for your help!

    Read the article

  • C++ overloading operator comma for variadic arguments

    - by uray
    is it possible to construct variadic arguments for function by overloading operator comma of the argument? i want to see an example how to do so.., maybe something like this: template <typename T> class ArgList { public: ArgList(const T& a); ArgList<T>& operator,(const T& a,const T& b); } //declaration void myFunction(ArgList<int> list); //in use: myFunction(1,2,3,4); //or maybe: myFunction(ArgList<int>(1),2,3,4);

    Read the article

  • c++ variadic macro argument count

    - by chedi
    Hi, is there any way to count the number of argument of a variadic macro, other than this one: #define PP_NARG(...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N()) #define PP_NARG_(...) PP_ARG_N(__VA_ARGS__) #define PP_ARG_N( \ _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \ _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \ _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \ _61,_62,_63,N,...) N #define PP_RSEQ_N() \ 63,62,61,60,59,58,57,56,55,54,53,52,51,50,49,48,47,46,45,44,43,42,41,40, \ 39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16, \ 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0

    Read the article

  • Compilation Error on Recursive Variadic Template Function

    - by Maxpm
    I've prepared a simple variadic template test in Code::Blocks, but I'm getting an error: No matching function for call to 'OutputSizes()' Here's my source code: #include <iostream> #include <typeinfo> using namespace std; template <typename FirstDatatype, typename... DatatypeList> void OutputSizes() { std::cout << typeid(FirstDatatype).name() << ": " << sizeof(FirstDatatype) << std::endl; OutputSizes<DatatypeList...>(); } int main() { OutputSizes<char, int, long int>(); return 0; } I'm using GNU GCC with -std=C++0x. Using std=gnu++0x makes no difference.

    Read the article

  • How do I compile variadic templates conditionally?

    - by FredOverflow
    Is there a macro that tells me whether or not my compiler supports variadic templates? #ifdef VARIADIC_TEMPLATES_AVAILABLE template<typename... Args> void coolstuff(Args&&... args); #else ??? #endif If they are not supported, I guess I would simulate them with a bunch of overloads. Any better ideas? Maybe there are preprocessor libraries that can ease the job?

    Read the article

  • Is it possible to have a variadic function in C with no non-variadic parameter?

    - by Tim
    I have the following function: void doStuff(int unusedParameter, ...) { va_list params; va_start(params, unusedParameter); /* ... */ va_end(params); } As part of a refactor, I'd like to remove the unused parameter without otherwise changing the implementation of the function. As far as I can tell, it's impossible to use va_start when you don't have a last non-variadic parameter to refer to. Is there any way around this? Background: It is in fact a C++ program, so I could use some operator-overloading magic as suggested here, but I was hoping not to have to change the interface at this point. The existing function does its work by requiring that the variable argument list be null-terminated, and scanning for the NULL, therefore it doesn't need a leading argument to tell it how many arguments it has.

    Read the article

  • Bug in variadic function template specialization with MSVC?

    - by Andrei Tita
    Using the Visual Studio Nov 2012 CTP, which supports variadic templates (among other things). The following code: template<int, typename... Args> void myfunc(Args... args) { } template<> void myfunc<1, float>(float) { } produces the following errors: error C2785: 'void myfunc(Args...)' and 'void myfunc(float)' have different return types error C2912: explicit specialization 'void myfunc(float)' is not a specialization of a function template (yeah, the first one is pretty funny) So my questions are: 1) Am I writing legal C++11 here? 2) If yes, is there a way to find out if this is a known bug in MSVC before submitting it?

    Read the article

  • Qt and variadic functions

    - by Noah Roberts
    OK, before lecturing me on the use of C-style variadic functions in C++...everything else has turned out to require nothing short of rewriting the Qt MOC. What I'd like to know is whether or not you can have a "slot" in a Qt object that takes an arbitrary amount/type of arguments. The thing is that I really want to be able to generate Qt objects that have slots of an arbitrary signature. Since the MOC is incompatible with standard preprocessing and with templates, it's not possible to do so with either direct approach. I just came up with another idea: struct funky_base : QObject { Q_OBJECT funky_base(QObject * o = 0); public slots: virtual void the_slot(...) = 0; }; If this is possible then, because you can make a template that is a subclass of a QObject derived object so long as you don't declare new Qt stuff in it, I should be able to implement a derived templated type that takes the ... stuff and turns it into the appropriate, expected types. If it is, how would I connect to it? Would this work? connect(x, SIGNAL(someSignal(int)), y, SLOT(the_slot(...))); If nobody's tried anything this insane and doesn't know off hand, yes I'll eventually try it myself...but I am hoping someone already has existing knowledge I can tap before possibly wasting my time on it.

    Read the article

  • What can procs and lambdas do that functions can't in ruby

    - by SecurityGate
    I've been working in Ruby for the last couple weeks, and I've come to the subject of procs, lambdas and blocks. After reading a fair share of examples from a variety of sources, I don't how they're much different from small, specialized functions. It's entirely possible that the examples I've read aren't showing the power behind procs and lambdas. def zero_function(x) x = x.to_s if x.length == 1 return x = "0" + x else return x end end zero_lambda = lambda {|x| x = x.to_s if x.length == 1 return x = "0" + x else return x end } zero_proc = Proc.new {|x| x = x.to_s if x.length == 1 puts x = "0" + x else puts x end } puts zero_function(4) puts zero_lambda.call(3) zero_proc.call(2) This function, proc, and lambda do the exact same thing, just slightly different. Is there any reason to choose one over another?

    Read the article

  • About variadic templates

    - by chedi
    Hi, I'm currently experiencing with the new c++0x variadic templates, and it's quit fun, Although I have a question about the process of member instanciation. in this example, I'm trying to emulate the strongly typed enum with the possibility of choose a random valid strong enum (this is used for unit testing). #include<vector> #include<iostream> using namespace std; template<unsigned... values> struct sp_enum; /* this is the solution I found, declaring a globar var vector<unsigned> _data; and it work just fine */ template<> struct sp_enum<>{ static const unsigned _count = 0; static vector<unsigned> _data; }; vector<unsigned> sp_enum<>::_data; template<unsigned T, unsigned... values> struct sp_enum<T, values...> : private sp_enum<values...>{ static const unsigned _count = sp_enum<values...>::_count+1; static vector<unsigned> _data; sp_enum( ) : sp_enum<values...>(values...) {_data.push_back(T);} sp_enum(unsigned v ) {_data.push_back(v);} sp_enum(unsigned v, unsigned...) : sp_enum<values...>(values...) {_data.push_back(v);} }; template<unsigned T, unsigned... values> vector<unsigned> sp_enum<T, values...>::_data; int main(){ enum class t:unsigned{Default = 5, t1, t2}; sp_enum<t::Default, t::t1, t::t2> test; cout <<test._count << endl << test._data.size() << endl; for(auto i= test._data.rbegin();i != test._data.rend();++i){cout<< *i<< ":";} } the result I'm getting with this code is : 3 1 5: can someone point me what I'm messing here ??? Ps: using gcc 4.4.3

    Read the article

  • Odd behavior when recursively building a return type for variadic functions

    - by Dennis Zickefoose
    This is probably going to be a really simple explanation, but I'm going to give as much backstory as possible in case I'm wrong. Advanced apologies for being so verbose. I'm using gcc4.5, and I realize the c++0x support is still somewhat experimental, but I'm going to act on the assumption that there's a non-bug related reason for the behavior I'm seeing. I'm experimenting with variadic function templates. The end goal was to build a cons-list out of std::pair. It wasn't meant to be a custom type, just a string of pair objects. The function that constructs the list would have to be in some way recursive, with the ultimate return value being dependent on the result of the recursive calls. As an added twist, successive parameters are added together before being inserted into the list. So if I pass [1, 2, 3, 4, 5, 6] the end result should be {1+2, {3+4, 5+6}}. My initial attempt was fairly naive. A function, Build, with two overloads. One took two identical parameters and simply returned their sum. The other took two parameters and a parameter pack. The return value was a pair consisting of the sum of the two set parameters, and the recursive call. In retrospect, this was obviously a flawed strategy, because the function isn't declared when I try to figure out its return type, so it has no choice but to resolve to the non-recursive version. That I understand. Where I got confused was the second iteration. I decided to make those functions static members of a template class. The function calls themselves are not parameterized, but instead the entire class is. My assumption was that when the recursive function attempts to generate its return type, it would instantiate a whole new version of the structure with its own static function, and everything would work itself out. The result was: "error: no matching function for call to BuildStruct<double, double, char, char>::Go(const char&, const char&)" The offending code: static auto Go(const Type& t0, const Type& t1, const Types&... rest) -> std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> My confusion comes from the fact that the parameters to BuildStruct should always be the same types as the arguments sent to BuildStruct::Go, but in the error code Go is missing the initial two double parameters. What am I missing here? If my initial assumption about how the static functions would be chosen was incorrect, why is it trying to call the wrong function rather than just not finding a function at all? It seems to just be mixing types willy-nilly, and I just can't come up with an explanation as to why. If I add additional parameters to the initial call, it always burrows down to that last step before failing, so presumably the recursion itself is at least partially working. This is in direct contrast to the initial attempt, which always failed to find a function call right away. Ultimately, I've gotten past the problem, with a fairly elegant solution that hardly resembles either of the first two attempts. So I know how to do what I want to do. I'm looking for an explanation for the failure I saw. Full code to follow since I'm sure my verbal description was insufficient. First some boilerplate, if you feel compelled to execute the code and see it for yourself. Then the initial attempt, which failed reasonably, then the second attempt, which did not. #include <iostream> using std::cout; using std::endl; #include <utility> template<typename T1, typename T2> std::ostream& operator <<(std::ostream& str, const std::pair<T1, T2>& p) { return str << "[" << p.first << ", " << p.second << "]"; } //Insert code here int main() { Execute(5, 6, 4.3, 2.2, 'c', 'd'); Execute(5, 6, 4.3, 2.2); Execute(5, 6); return 0; } Non-struct solution: template<typename Type> Type BuildFunction(const Type& t0, const Type& t1) { return t0 + t1; } template<typename Type, typename... Rest> auto BuildFunction(const Type& t0, const Type& t1, const Rest&... rest) -> std::pair<Type, decltype(BuildFunction(rest...))> { return std::pair<Type, decltype(BuildFunction(rest...))> (t0 + t1, BuildFunction(rest...)); } template<typename... Types> void Execute(const Types&... t) { cout << BuildFunction(t...) << endl; } Resulting errors: test.cpp: In function 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]': test.cpp:33:35: instantiated from here test.cpp:28:3: error: no matching function for call to 'BuildFunction(const int&, const int&, const double&, const double&, const char&, const char&)' Struct solution: template<typename... Types> struct BuildStruct; template<typename Type> struct BuildStruct<Type, Type> { static Type Go(const Type& t0, const Type& t1) { return t0 + t1; } }; template<typename Type, typename... Types> struct BuildStruct<Type, Type, Types...> { static auto Go(const Type& t0, const Type& t1, const Types&... rest) -> std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> { return std::pair<Type, decltype(BuildStruct<Types...>::Go(rest...))> (t0 + t1, BuildStruct<Types...>::Go(rest...)); } }; template<typename... Types> void Execute(const Types&... t) { cout << BuildStruct<Types...>::Go(t...) << endl; } Resulting errors: test.cpp: In instantiation of 'BuildStruct<int, int, double, double, char, char>': test.cpp:33:3: instantiated from 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]' test.cpp:38:41: instantiated from here test.cpp:24:15: error: no matching function for call to 'BuildStruct<double, double, char, char>::Go(const char&, const char&)' test.cpp:24:15: note: candidate is: static std::pair<Type, decltype (BuildStruct<Types ...>::Go(BuildStruct<Type, Type, Types ...>::Go::rest ...))> BuildStruct<Type, Type, Types ...>::Go(const Type&, const Type&, const Types& ...) [with Type = double, Types = {char, char}, decltype (BuildStruct<Types ...>::Go(BuildStruct<Type, Type, Types ...>::Go::rest ...)) = char] test.cpp: In function 'void Execute(const Types& ...) [with Types = {int, int, double, double, char, char}]': test.cpp:38:41: instantiated from here test.cpp:33:3: error: 'Go' is not a member of 'BuildStruct<int, int, double, double, char, char>'

    Read the article

  • Non-trivial functions that operate on any monad

    - by Strilanc
    I'm looking for examples of interesting methods that take an arbitrary monad and do something useful with it. Monads are extremely general, so methods that operate on monads are widely applicable. On the other hand, methods I know of that can apply to any monad tend to be... really, really trivial. Barely worth extracting into a function. Here's a really boring example: joinTwice. It just flattens an m m m t into an m t: join n = n >>= id joinTwice n = (join . join) n main = print (joinTwice [[[1],[2, 3]], [[4]]]) -- prints [1,2,3,4] The only non-trivial method for monads that I know of is bindFold (see my answer below). Are there more?

    Read the article

  • Binder and variadic template ends up in a segmentation fault

    - by phlipsy
    I wrote the following program #include <iostream> template<typename C, typename Res, typename... Args> class bind_class_t { private: Res (C::*f)(Args...); C *c; public: bind_class_t(Res (C::*f)(Args...), C* c) : f(f), c(c) { } Res operator() (Args... args) { return (c->*f)(args...); } }; template<typename C, typename Res, typename... Args> bind_class_t<C, Res, Args...> bind_class(Res (C::*f)(Args...), C* c) { return bind_class<C, Res, Args...>(f, c); } class test { public: int add(int x, int y) { return x + y; } }; int main() { test t; // bind_class_t<test, int, int, int> b(&test::add, &t); bind_class_t<test, int, int, int> b = bind_class(&test::add, &t); std::cout << b(1, 2) << std::endl; return 0; } compiled it with gcc 4.3.3 and got a segmentation fault. After spending some time with gdb and this program it seems to me that the addresses of the function and the class are mixed up and a call of the data address of the class isn't allowed. Moreover if I use the commented line instead everything works fine. Can anyone else reproduce this behavior and/or explain me what's going wrong here?

    Read the article

  • Problem passing a reference as a named parameter to a variadic function

    - by Michael Mrozek
    I'm having problems in Visual Studio 2003 with the following: void foo(const char*& str, ...) { va_list args; va_start(args, str); const char* foo; while((foo = va_arg(args, const char*)) != NULL) { printf("%s\n", foo); } } When I call it: const char* one = "one"; foo(one, "two", "three", NULL); I get: Access violation reading location 0xcccccccc on the printf() line -- va_arg() returned 0xcccccccc. I finally discovered it's the first parameter being a reference that breaks it -- if I make it a normal char* everything is fine. It doesn't seem to matter what the type is; being a reference causes it to fail at runtime. Is this a known problem with VS2003, or is there some way in which that's legal behavior? It doesn't happen in GCC; I haven't tested with newer Visual Studios to see if the behavior goes away

    Read the article

  • Functional Methods on Collections

    - by GlenPeterson
    I'm learning Scala and am a little bewildered by all the methods (higher-order functions) available on the collections. Which ones produce more results than the original collection, which ones produce less, and which are most appropriate for a given problem? Though I'm studying Scala, I think this would pertain to most modern functional languages (Clojure, Haskell) and also to Java 8 which introduces these methods on Java collections. Specifically, right now I'm wondering about map with filter vs. fold/reduce. I was delighted that using foldRight() can yield the same result as a map(...).filter(...) with only one traversal of the underlying collection. But a friend pointed out that foldRight() may force sequential processing while map() is friendlier to being processed by multiple processors in parallel. Maybe this is why mapReduce() is so popular? More generally, I'm still sometimes surprised when I chain several of these methods together to get back a List(List()) or to pass a List(List()) and get back just a List(). For instance, when would I use: collection.map(a => a.map(b => ...)) vs. collection.map(a => ...).map(b => ...) The for/yield command does nothing to help this confusion. Am I asking about the difference between a "fold" and "unfold" operation? Am I trying to jam too many questions into one? I think there may be an underlying concept that, if I understood it, might answer all these questions, or at least tie the answers together.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >