1
double f(const int& i) { return 1.5 * i;  }

template<
    typename _out, 
    typename _in, 
    _out (*__f)(const _in&)> 
class X {}; // template <... __f> class X {};

int main()
{
    X<double, int, f> x; // X<f> x;
}

How can I simplify this code? I want to write code as the one in the comments. C++11 result_of and decltype seems to help but I not smart enough to write correct code to deduce the input and output types of the function f inside of the class. Can you help me see the light? Thanks

gustavo
  • 96
  • 1
  • 6
  • You're using a [reserved identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris Jul 16 '14 at 11:15
  • sorry... just learning – gustavo Jul 16 '14 at 11:19
  • maybe a [`std::function< double( int ) > func = f`](http://http://en.cppreference.com/w/cpp/utility/functional/function)is what you are looking for? – Buni Jul 17 '14 at 09:48

1 Answers1

1

Just remove the _out and _in parameter and change parameter to std::function:

#include <functional>
#include <iostream>

double f(const int &i) { std::cout << "Func F" << std::endl; return 1.5 * i; }

struct functor_of_f {
    double operator()(const int &i)
    { std::cout << "Func F" << std::endl; return 1.5 * i; }
};

template <typename T> class X {
public:
  X(T t) { std::cout << t(5) << std::endl; }
  X() { std::cout << T()(5) << std::endl; }
}; // template <... __f> class X {};

int main(int argc, char* argv[]) {
  typedef std::function<double(int)> f_func;
  X<f_func> x1(f);
  X<decltype(f)> x2(f);
  X<std::function<double(int)>> x3(f);

  X<functor_of_f> x4;
  return 0;
}

Updated the code adding a functor version, the problem is that need to have the function in a class and no as a free function.

NetVipeC
  • 4,402
  • 1
  • 17
  • 19
  • Your code is perfect but I forget one restriction of class X. It must have an empty default constructor so the function f can't be passed this way. – gustavo Jul 16 '14 at 19:56
  • best solution so far... it would be great if you don't have to write a wrapper class for every function :) – gustavo Jul 17 '14 at 09:30