generic-programming

Generic pair class

淺唱寂寞╮ 提交于 2019-11-27 04:00:54
问题 Just attempting this question I found in a past exam paper so that I can prepare for an upcoming Java examination. Provide a generic class Pair for representing pairs of things. The class should provide a constructor, a method for getting the first member of the pair, a method for getting the second member of the pair, a method for setting the first member of the pair, a method for setting the second member of the pair. The class should be parameterised over two types one for the first member

Safely copying fields between case classes of different types

旧城冷巷雨未停 提交于 2019-11-27 01:46:30
问题 Assuming you have case classes like the following case class Test1(a:String,b:Int,c:Char) case class Test2(a:String,b:Int) And you instantiate the classes with the following variables val test1 = Test1("first",2,'3') val test2 = Test2("1st",20) Is there a way to use the .copy method (or otherwise), to apply the variables inside Test2 to Test1, something like val test3 = test1.copy(test2) //Note this isn't valid scala code // Result should be ("1st",20,'3') If this isn't possible in pure scala

Tag dispatch versus static methods on partially specialised classes

回眸只為那壹抹淺笑 提交于 2019-11-26 23:51:56
问题 Suppose I want to write a generic function void f<T>() , which does one thing if T is a POD type and another thing if T is non-POD (or any other arbitrary predicate). One way to achieve this would be to use a tag-dispatch pattern like the standard library does with iterator categories: template <bool> struct podness {}; typedef podness<true> pod_tag; typedef podness<false> non_pod_tag; template <typename T> void f2(T, pod_tag) { /* POD */ } template <typename T> void f2(T, non_pod_tag) { /*

Template function as a template argument

独自空忆成欢 提交于 2019-11-26 15:37:52
问题 I've just got confused how to implement something in a generic way in C++. It's a bit convoluted, so let me explain step by step. Consider such code: void a(int) { // do something } void b(int) { // something else } void function1() { a(123); a(456); } void function2() { b(123); b(456); } void test() { function1(); function2(); } It's easily noticable that function1 and function2 do the same, with the only different part being the internal function. Therefore, I want to make function generic