我已经看到了一些使用模板模板参数(即模板作为参数的模板)来进行基于策略的类设计的C++示例.这种技术有什么其他用途?
是否可以使用C++(或C#)模板模拟Haskell的类型类功能?
这样做有意义还是有任何回报?
我试图用C++编写一个Functor类,但我无法做到.我试过这样的事情:
#include <iostream>
using namespace std;
//A function class to make types more readable
template <class input, class output> class Function {
private:
output (*ptrfunc )(input);
public:
Function(output (* ptr)(input)) {
ptrfunc = ptr;
}
output call(input x) {return (*ptrfunc)(x);}
output operator() (input x) { return call(x);}
};
//the functor "typeclass"
template <class a> class Functor{
public:
template <class b> Functor<b> fmap(Function<a,b> func);
};
// an container type to be declared "instance" of functor:
template <class a> class …Run Code Online (Sandbox Code Playgroud)