What are some other languages that support "partial specialization"? - language-agnostic

Partial template specialization is one of the most important concepts for generic programming in C++. For example: to implement a generic swap function:
template <typename T>
void swap(T &x, T &y) {
const T tmp = x;
y = x;
x = tmp;
}
To specialize it for a vector to support O(1) swap:
template <typename T, class Alloc>
void swap(vector<T, Alloc> &x, vector<T, Alloc> &y) { x.swap(y); }
So you can always get optimal performance when you call swap(x, y) in a generic function;
Much appreciated, if you can post the equivalent (or the canonical example of partial specialization of the language if the language doesn't support the swap concept) in alternative languages.
EDIT: so it looks like many people who answered/commented really don't known what partial specialization is, and that the generic swap example seems to get in the way of understanding by some people. A more general example would be:
template <typename T>
void foo(T x) { generic_foo(x); }
A partial specialization would be:
template <typename T>
void foo(vector<T> x) { partially_specialized_algo_for_vector(x); }
A complete specialization would be:
void foo(vector<bool> bitmap) { special_algo_for_bitmap(bitmap); }
Why this is important? because you can call foo(anything) in a generic function:
template <typename T>
void bar(T x) {
// stuff...
foo(x);
// more stuff...
}
and get the most appropriate implementation at compile time. This is one way for C++ to achieve abstraction w/ minimal performance penalty.
Hope it helps clearing up the concept of "partial specialization". In a way, this is how C++ do type pattern matching without needing the explicit pattern matching syntax (say the match keyword in Ocaml/F#), which sometimes gets in the way for generic programming.

D supports partial specialization:
Language overview
Template feature comparison (with C++ 98 and 0x).
(scan for "partial" in the above links).
The second link in particular will give you a very detailed breakdown of what you can do with template specialization, not only in D but in C++ as well.
Here's a D specific example of swap. It should print out the message for the swap specialized for the Thing class.
import std.stdio; // for writefln
// Class with swap method
class Thing(T)
{
public:
this(T thing)
{
this.thing = thing;
}
// Implementation is the same as generic swap, but it will be called instead.
void swap(Thing that)
{
const T tmp = this.thing;
this.thing = that.thing;
that.thing = tmp;
}
public:
T thing;
}
// Swap generic function
void swap(T)(ref T lhs, ref T rhs)
{
writefln("Generic swap.");
const T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
void swap(T : Thing!(U))(ref T lhs, ref T rhs)
{
writefln("Specialized swap method for Things.");
lhs.swap(rhs);
}
// Test case
int main()
{
auto v1 = new Thing!(int)(10);
auto v2 = new Thing!(int)(20);
assert (v1.thing == 10);
assert (v2.thing == 20);
swap(v1, v2);
assert (v1.thing == 20);
assert (v2.thing == 10);
return 0;
}

I am afraid that C# does not support partial template specialization.
Partial template specialization means:
You have a base class with two or more templates (generics / type parameters).
The type parameters would be <T, S>
In a derived (specialized) class you indicate the type of one of the type parameters.
The type parameters could look like this <T, int>.
So when someone uses (instantiates an object of) the class where the last type parameter is an int, the derived class is used.

Haskell has overlapping instances as an extension:
class Sizable a where
size :: a -> Int
instance Collection c => Sizable c where
size = length . toList
is a function to find size of any collection, which can have more specific instances:
instance Sizable (Seq a) where
size = Seq.length
See also Advanced Overlap on HaskellWiki.

Actually, you can (not quite; see below) do it in C# with extension methods:
public Count (this IEnumerable<T> seq) {
int n = 0;
foreach (T t in seq)
n++;
return n;
}
public Count (this T[] arr) {
return arr.Length;
}
Then calling array.Count() will use the specialised version. "Not quite" is because the resolution depends on the static type of array, not on the run-time type. I.e. this will use the more general version:
IEnumerable<int> array = SomethingThatReturnsAnArray();
return array.Count();

C#:
void Swap<T>(ref T a, ref T b) {
var c = a;
a = b;
b = c;
}
I guess the (pure) Haskell-version would be:
swap :: a -> b -> (b,a)
swap a b = (b, a)

Java has generics, which allow you to do similar sorts of things.

Related

Is there any profits of using Methods rather than Functions?

I'm developing "Matrix" struct and related methods for the purpose of practicing Go.
I made a lot of methods but I realized that all these methods can be changed into functions
I'm used to C++ and in C++, if I make a function whose parameter is a type of class, the function cannot use the class' private variable(information hiding)
However, when I built a similar code using "Go", a function can access a struct's variable.
So I don't get what is different between methods and functions in Go.
Are there any profits using methods rather than functions or vice versa?
First one is my original "Matrix" code(not all of it)
It used a method "Tr".
It doesn't have problems.
package main
import "fmt"
//definition of "Array"
type Array struct{
component [][]float32
row int
col int
}
//constructor of Array, "Ones"; making an array setting all component as one
func Ones(m int, n int) Array{
var a Array
a.component = make([][]float32, m)
a.row=m
a.col=n
for i:=0; i<m; i++{
a.component[i] = make([]float32, n)
for j:=0; j<n; j++{
a.component[i][j]=1
}
}
return a
}
//Tr function; find trace of an Array
func (a Array) Tr() float32{
var sum float32 = 0
for i:=0; i<a.row; i++{
sum += a.component[i][i]
}
return sum
}
func main(){
a := Ones(3,3)
fmt.Println(a.Tr())
}
The second one is another similar code. (Everything is same but "Tr" part)
It used only functions.
It also doesn't have problems.
package main
import "fmt"
//definition of "Array"
type Array struct{
component [][]float32
row int
col int
}
//constructor of Array, "Ones"; making an array setting all component as one
func Ones(m int, n int) Array{
var a Array
a.component = make([][]float32, m)
a.row=m
a.col=n
for i:=0; i<m; i++{
a.component[i] = make([]float32, n)
for j:=0; j<n; j++{
a.component[i][j]=1
}
}
return a
}
//Tr function; find trace of an Array
func Tr(a Array) float32{
var sum float32 = 0
for i:=0; i<a.row; i++{
sum += a.component[i][i]
}
return sum
}
func main(){
a := Ones(3,3)
fmt.Println(Tr(a))
}
If you just want to call the function or method, it doesn't matter, you may create a function with a signature where the receiver is a normal, regular parameter. There won't be any performance penalty (there could be if methods could be virtual, but in Go there are no virtual methods).
One advantage might be the "visual appeal". Calling a method makes it obvious it belongs to the receiver. I also find chained code easier to understand if methods are used.
Compare this solution without methods:
type Circle struct{}
type Point struct{}
func Center(Circle) Point { return Point{} }
func Abs(Point) float64 { return 0 }
func main() {
var c Circle
fmt.Println(Abs(Center(c)))
}
Abs(Center(c)) isn't that intuitive. But if you add methods instead of using functions:
func (Circle) Center() Point { return Point{} }
func (Point) Abs() float64 { return 0 }
func main() {
var c Circle
fmt.Println(c.Center().Abs())
}
c.Center().Abs() is easier to understand.
Methods are a must if you want to implement interfaces. If an interface contains some methods, only types that have those methods can implement it. See related: Why are interfaces needed in Golang? It should also be noted that you may only create methods defined in the same package, so if you want to "arm" a type from a different package, you can't "use" methods.
One thing that I would call "profit" for using methods: you can't call functions by name, but you can access and call methods by name. For details, see Call functions with special prefix/suffix.

Encapsulate a function with another function that has the same set of parameters

I have a function that has a lot of parameters. (4-7 parameters)
For simplicity, this is an example:-
class B{
friend class C;
int f(int param1,float param2, structA a, structB b){
//... some code ...
}
//.... other functions ....
};
Sometimes, I want to encapsulate it under another (more-public) function that has the same signature:-
class C{
B* b;
public: int g(int param1,float param2, structA a, structB b){
return b->f(param1,param2,a,b);
}
//.... other functions ....
};
In my opinion, the above code is :-
tedious
causes a bit of maintainability problem
human error-prone
Is there any C++ technique / magic / design-pattern to assist it?
In the real case, it happens mostly in edge-cases that composition is just a little more suitable than inheritance.
I feel that <...> might solve my problem, but it requires template from which I want to avoid.
but it requires template from which I want to avoid.
That's, in my opinion, the wrong mindset to have. You should avoid templates if you have a very good reason to do so, otherwise you should embrace them - they are a core feature of the C++ language.
With a variadic template, you can create a perfect-forwarding wrapper as follows:
class C{
B* b;
public:
template <typename... Ts>
int g(Ts&&... xs){
return b->f(std::forward<Ts>(xs)...);
}
};
The above g function template will accept any number of arguments and call b->f by perfectly-forwarding them.
(Using std::forward allows your wrapper to properly retain the value category of the passed expressions when invoking the wrapper. In short, this means that no unnecessary copies/moves will be made and that references will be correctly passed as such.)
In a public header:
using f_sig = int(int param1,float param2, structA a, structB b);
class hidden;
class famous {
hidden* pImpl
public:
f_sig g;
};
In your .cpp:
class hidden {
friend class famous;
f_sig f;
};
Now, you cannot use this pattern to define what f or g does, but this does declair their signatures. And if your definition doesn't match the declaration you get an error.
int hidden::f(int param1,float param2, structA a, structB b) {
std::cout << "f!";
}
int famous::g(int param1,float param2, structA a, structB b) {
return pImpl->f(param1, param2, a, b);
}
type the signatures wrong above, and you'll get a compile-time error.

How can set different function signature to the same function pointer?

How can I set a function pointer depending on some condition to functions with different signature?
Example:
short int A()
{
return 0;
}
long int B()
{
return 0;
}
void main()
{
std::function<short int()> f = A;
f();
if(true)
{
//error
f = B;
}
}
How can use the same function pointer for two functions with different signature?
Is it possible?
If is not, there is an efficient way to call the appropriate function depending on behavior instead of use a variable and split the whole code with if statements?
EDIT / EXPANSION ("2nd case")
#include <SDL.h>
class Obj { //whatever ...}
class A
{
private:
Uint16 ret16() { return SDL_ReadLE16(_pFile); }
Uint32 ret32() { return SDL_ReadLE32(_pFile); }
_pFile = nullptr;
public:
Obj* func()
{
Obj obj = new Obj();
_pFile = SDL_RWFromFile("filename.bin","r"));
auto ret = std::mem_fn(&SHPfile::ret16);
if(true)
{
ret = std::mem_fn(&SHPfile::ret32);
}
//ret();
// continue whatever
// ....
SDL_RWclose(_pFile);
return *obj;
}
}
I have a compilation error on a similar case using the Uint16 and Uint32 variable of SDL 2 library, using std::mem_fn
the compiler give me this error (relative to my code, but it's implemented in a way like the above example):
error: no match for ‘operator=’ (operand types are ‘std::_Mem_fn<short unsigned int (IO::File::*)()>’ and ‘std::_Mem_fn<unsigned int (IO::File::*)()>’)
To resolve this compilation error, I forced both the function to return a int type.
Is there a better way?
Or I did something wrong?
The comments already say that clang accepts the code as is, and I can now say that GCC 4.8.4 and GCC 4.9.2 both accept it as well, after fixing void main() to say int main().
This use of std::function is perfectly valid. The C++11 standard says:
20.8.11.2 Class template function [func.wrap.func]
function& operator=(const function&);
function& operator=(function&&);
function& operator=(nullptr_t);
There is no template assignment operator here, so assignment of B could only construct a new temporary function<short int()> object, and move-assign from that. To determine whether the construction of that temporary is possible:
20.8.11.2.1 function construct/copy/destroy [func.wrap.func.con]
template<class F> function(F f);
template <class F, class A> function(allocator_arg_t, const A& a, F f);
7 Requires: F shall be CopyConstructible. f shall be Callable (20.8.11.2) for argument types ArgTypes and return type R. The copy constructor and destructor of A shall not throw exceptions.
20.8.11.2 Class template function [func.wrap.func]
2 A callable object f of type F is Callable for argument types ArgTypes and return type R if the expression INVOKE(f, declval<ArgTypes>()..., R), considered as an unevaluated operand (Clause 5), is well formed (20.8.2).
20.8.2 Requirements [func.require]
2 Define INVOKE(f, t1, t2, ..., tN, R) as INVOKE(f, t1, t2, ..., tN) implicitly converted to R.
1 Define INVOKE(f, t1, t2, ..., tN) as follows:
... (all related to pointer-to-member types)
f(t1, t2, ..., tN) in all other cases.
In short, this means that std::function<short int()> can be used with any function that can be called with no arguments, and which has a return type that can be implicitly converted to short. long clearly can be implicitly converted to short, so there is no problem whatsoever.
If your compiler's library doesn't accept it, and you cannot upgrade to a more recent version, one alternative is to try boost::function instead.
Aaron McDaid points out lambdas as another alternative: if your library's std::function is lacking, you can write
std::function<short int()> f = A;
f = []() -> short int { return B(); };
but if you take this route, you can take it a step further and avoid std::function altogether:
short int (*f)() = A;
f = []() -> short int { return B(); };
This works because lambas that don't capture anything are implicitly convertible to a pointer-to-function type that matches the lambda's arguments and return type. Effectively, it's short for writing
short int B_wrapper() { return B(); }
...
f = B_wrapper;
Note: the conversion from long to short may lose data. If you want to avoid that, you can use std::function<long int()> or long int (*)() instead.
No, you can't do that in a statically typed language unless your types all have a common super type, and C++ doesn't have that for primitives. You would need to box them into an object, then have the function return the object.
However, if you did that, you may as well just keep an object pointer around and use that instead of a function pointer, especially since it's going to make it easier to actually do something useful with the result without doing casts all over the place.
For example, in a calculator I wrote in Java, I wanted to work with BigInteger fractions as much as possible to preserve precision, but fallback to doubles for operations that returned irrational numbers. I created a Result interface, with BigFractionResult and DoubleResult implementations. The UI code would call things like Result sum = firstOperand.add(otherOperand) and didn't have to care which implementation of add it was using.
The cleanest option that comes to mind is templates:
#include <iostream>
using namespace std;
template <typename T>
T foo() {
return 0;
}
int main() {
long a = foo<long>();
cout << sizeof a << " bytes with value " << a << endl;
int b = foo<int>();
cout << sizeof b << " bytes with value " << b << endl;
short c = foo<short>();
cout << sizeof c << " bytes with value " << c << endl;
return 0;
}
In ideone.com this outputs:
4 bytes with value 0
4 bytes with value 0
2 bytes with value 0
Hopefully this is what you needed.
If for some reason you really need to pass an actual function around, I would recommend looking into std::function and trying to write some template code using that.

Immutability in D constructors

My previous question discussed making a copy constructor like so:
struct Foo {
int i;
this(int j) { i = j; }
this(Foo rhs) { this = rhs; }
}
void main()
{
auto f = Foo(5);
auto g = new Foo(f);
}
But, if I make i immutable, the constructor fails to compile with
Error: cannot modify struct this Foo with immutable members
Why is this the case? I was under the impression that immutable members of a class or struct do not become immutable until the end of the constructor is reached.
Okay. In general, I'd advise against having structs with immutable members. There are just too many places where it's useful to be able to assign to one. What you typically want to do with a struct is make it so that it can be mutable, const, or immutable as a whole. And for the most part, that just works. e.g.
struct Foo
{
int i;
this(int j) { i = j; }
this(Foo rhs) { this = rhs; }
}
void main()
{
immutable f = Foo(5);
}
compiles just fine. The one area that generally causes trouble with that is when you have to have a postblit constructor, because those don't currently work with const or immutable structs (it's something that sorely needs to be fixed, but it's still an open problem due to how the type system works - it may result in us having to add copy constructors to the language, or we may figure out how to do it, but for now, it doesn't work, and it can be annoying). But that only affects you if you need a postblit constructor, which most structs don't need (the problem will be fixed eventually though, because it really needs to be; it's just a question of how and when).
However, to answer your question more generally, let's look at a class. For instance, this code won't compile, because the constructor is not immutable, and the compiler can't convert an immutable class object to a mutable one (it can do that with structs, because it makes a copy, but with a class, it's just copying the reference, not the object, so it doesn't work):
class Foo
{
int i;
this(int j) { i = j; }
}
void main()
{
auto f = new immutable Foo(5);
}
Instead of that compiling, you get this lovely error message:
q.d(10): Error: mutable method q.Foo.this is not callable using a immutable object
q.d(10): Error: no constructor for Foo
There are three ways to solve this. The first is to make the constructor immutable
class Foo
{
int i;
this(int j) immutable { i = j; }
}
and that works, but it makes it so that you can only construct Foos which are immutable, which usually isn't what you want (though it sometimes is). So, the second way to solve the problem would be to take the first solution a step further and overload the constructor. e.g.
class Foo
{
int i;
this(int j) { i = j; }
this(int j) immutable { i = j; }
}
However, that requires code duplication, which isn't a lot here, but it could be a lot for other types. So, what is generally the best solution is to make the constructor pure.
class Foo
{
int i;
this(int j) pure { i = j; }
}
This works, because the compiler then knows that nothing has escaped the constructor (since pure guarantees that nothing escapes by being assigned to a global or static variable, and the constructor's parameters don't allow anything to escape either), and because it knows that no references to Foo or its members can escape the constructor, it knows that there are no other references to this Foo and that it therefore can safely convert it to mutable, const, or immutable without violating the type system. Of course, that only works if you can make the constructor pure and nothing can escape via the constructor's arguments, but that's usually the case, and when it isn't, you can always just overload the constructor on mutability, much as that's less desirable.
The same techniques can be used on structs if you really want const or immutable members, but again, I'd advise against it. It's just going to cause you more trouble than it's worth, especially when it's usually trivial to just make the whole struct const or immutable when declaring a variable.
Making members of structs immutable stops assigning to the struct which in turn causes quite a few issues, you may which to rethink that.
Otherwise assign the members directly instead of relying on the assignment operator:
struct Foo {
immutable int i;
this(int j) { i = j; }
this(in Foo rhs) { this.i = rhs.i; }
}

SWIG and triggering a Python callback from C code

Apologies for not being familiar with formatting on here...I've made
some progress thanks to helpful replies and edited and removed my original
question to be replaced by the current one.
My problem lies with converting a C struct or struct pointer to PyObject. There
is no alternative to this because I am wrapping an existing C library whose
callback requires a C struct pointer.
Following works but with limitations:
%module cain1
%{
typedef struct {
double price;
int volume;
} book_entry_t;
typedef struct {
char symbol[10];
book_entry_t *book;
} trade_t;
typedef void (*CALLBACK)(trade_t trade);
CALLBACK my_callback = 0;
static PyObject *my_pycallback = NULL;
static void bigSnake(trade_t trade)
{
PyObject *result;
PyObject *d1;
result = PyEval_CallObject(my_pycallback,
Py_BuildValue("(y#)",
(char*)&trade,
sizeof(trade_t)
)
);
Py_XDECREF(result);
return /*void*/;
}
void test_cb (PyObject *callMe1) {
trade_t d1;
book_entry_t b1;
b1.price = 123.45;
b1.volume = 99;
Py_XINCREF(callMe1); /* Add a reference to new callback */
my_pycallback = callMe1; /* Remember new callback */
strcpy (d1.symbol,"Gupta Ltd");
d1.book = &b1;
bigSnake(d1);
}
%}
// Expose in python module..
typedef struct {
double price;
int volume;
} book_entry_t;
typedef struct {
char symbol[10];
book_entry_t *book;
} trade_t;
void test_cb(PyObject *callMe1);
and then triggering the callback from Python:
import cain1
import struct
def dave(d1):
N1,N2 = struct.unpack('10sP', d1)
print ('\n %s: %x' % (N1.decode() ,N2))
price,volume = struct.unpack('di',N2)
print (price,volume)
def main():
cain1.test_cb(dave)
main()
but I am unable to recover the book_entry_t strcut contents pointed to by trade_t....
I just feel this is all too convoluted since I have the pointer to structs and there
must be a straightforward way for Python to use that without any fuss.
Py_BuildValue("(N)",details) expects a PyObject* (your "N" says so), and you pass it something very different. Try Py_BuildValue("(i)", details.index) instead, and change it to accomodate any changes in details_t.
You're attempting to build a PyObject from a details_t struct. This isn't valid. Either pass the callback an integer (seems easier since details_t only has the one field) OR create a proper PyObject type. You can't blindly cast one type to another and expect it to work (a PyObject is more than just a pointer).