0

I can't use typedef with template, how can I change it? There is a syntax error "a typedef template is illegal". I want to use print() function like this: print<double>(1, 2, add); for any kind of data type.

    #include <iostream>
    using namespace std;

    template <typename type> /*typedef*/ type(*calculator)(type, type);

    template <typename type> inline const type& add(type x, type y) { return (type) x + y; }
    template <typename type> inline const type& sub(type x, type y) { return (type) x - y; }
    template <typename type> inline const type& mul(type x, type y) { return (type) x * y; }
    template <typename type> inline const type& dev(type x, type y) { return (type) x / y; }

    template <typename type> void print(type x, type y, calculator func) {
        cout << "(" << x << "," << y << ")=" << func(x, y);
    }

    int main(void) {
        print<float>(1, 2, add);
        print<float>(1, 2, sub);
        print<float>(1, 2, mul);
        print<float>(1, 2, dev);
    }
Honza Dejdar
  • 947
  • 7
  • 19
  • That is by design. You are supposed to use [`using`](http://en.cppreference.com/w/cpp/language/type_alias) instead. `template using calculator = type(*)(type, type);`. – nwp Oct 18 '17 at 13:20
  • Thanks it works, but why i should use using and not typedef ? – Luka Mamulaishvili Oct 18 '17 at 13:26
  • The reason you can't use **type**def is that a **type**def defines a **type**. A template is not a type. – Pete Becker Oct 18 '17 at 13:29
  • Because the standard committee failed to agree on a syntax that works in all cases for `typedef`. There are some details [here](https://stackoverflow.com/a/24916837/3484570). – nwp Oct 18 '17 at 13:29
  • But i still can't pass calculator into print function. template void print(type x, type y, calculator func) – Luka Mamulaishvili Oct 18 '17 at 13:30
  • Because `calculator` is a template, not a type. You would need `calculator` to generate a type. And then you run into the problem that the signature of `calculator` doesn't match the one on `add` because `calculator` returns `type` whereas `add` returns `const type &`. [This](http://coliru.stacked-crooked.com/a/8d889b9d62fa1982) might get you on the right track. – nwp Oct 18 '17 at 13:36

0 Answers0