Note that there are some explanatory texts on larger screens.

plurals
  1. POC++0x template function object inference
    primarykey
    data
    text
    <p>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. </p> <p><a href="http://www.cc.gatech.edu/~yannis/fc++/tutorial.html" rel="nofollow">FC++</a> 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</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; using namespace std; template&lt;class T&gt; class ArrayBuffer { private: vector&lt;T&gt; array; public: ArrayBuffer(); ArrayBuffer(vector&lt;T&gt; a) : array(a) {} template&lt;typename Fn&gt; void foreach(Fn fn) { for(unsigned int i = 0; i &lt; array.size(); i++) fn(array[i]); } template&lt;typename Fn&gt; auto map(Fn fn) -&gt; ArrayBuffer&lt;decltype(fn(T()))&gt; { vector&lt;decltype(fn(T()))&gt; result(array.size()); for(int unsigned i = 0; i &lt; array.size(); i++) result[i] = fn(array[i]); return result; } }; template&lt;typename T&gt; class Print { public: void operator()(T elem) { cout&lt;&lt;elem&lt;&lt;endl; } }; template&lt;typename T&gt; class Square{ public: auto operator()(T elem) -&gt; T { return elem * elem; } }; int main() { vector&lt;int&gt; some_list = {5, 3, 1, 2, 4}; ArrayBuffer&lt;int&gt; iterable(some_list); ArrayBuffer&lt;int&gt; squared = iterable.map(Square&lt;int&gt;()); // works as expected iterable.foreach(Print&lt;int&gt;()); // 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&lt;int&gt; squared2 = iterable.map(Square()); // Same as above - compiler should be able to infer the template. } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload