I'm a Scala/Java programmer looking to reintroduce myself to C++ and learn some of the exciting features in C++0x. I wanted to start by designing my own slightly functional collections library, based on Scala's collections, so that I could get a solid understanding of templates. The problem I'm running into is that the compiler doesn't seem to be able to infer any type information for templated function objects.
FC++ seems to have solved this using "Signatures". These seem really similar to the result_type typename, and I thought I would get this using the new function syntax. Can anyone suggest a way to do this sort of thing in C++0x, if it's possible, or at least explain how FC++ was able to accomplish this? Here's a snippet of code I was playing around with
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
template<class T>
class ArrayBuffer {
private:
vector<T> array;
public:
ArrayBuffer();
ArrayBuffer(vector<T> a) : array(a) {}
template<typename Fn>
void foreach(Fn fn) {
for(unsigned int i = 0; i < array.size(); i++) fn(array[i]);
}
template<typename Fn>
auto map(Fn fn) -> ArrayBuffer<decltype(fn(T()))> {
vector<decltype(fn(T()))> result(array.size());
for(int unsigned i = 0; i < array.size(); i++) result[i] = fn(array[i]);
return result;
}
};
template<typename T>
class Print {
public:
void operator()(T elem) { cout<<elem<<endl; }
};
template<typename T>
class Square{
public:
auto operator()(T elem) -> T {
return elem * elem;
}
};
int main() {
vector<int> some_list = {5, 3, 1, 2, 4};
ArrayBuffer<int> iterable(some_list);
ArrayBuffer<int> squared = iterable.map(Square<int>()); // works as expected
iterable.foreach(Print<int>()); // Prints 25 9 1 4 16 as expected
iterable.foreach(Print()); // Is there a way or syntax for the compiler to infer that the template must be an int?
ArrayBuffer<int> squared2 = iterable.map(Square()); // Same as above - compiler should be able to infer the template.
}