-2

I have template function

template<typename A,typename B,typename C>
C fun(A a,B b)
{
    return (string)(a+b);
}

And my main is

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    auto c= fun(10,20.3);
    cout<<c;
    return a.exec();
}

If I execute this it says In function int main(int, char**)

error: no matching function for call to fun(int, double)

Please let me know why I can't do this, or is this wrong?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
thippu
  • 75
  • 9

1 Answers1

0

In summary you will need a good C++ book;


First, You cannot "simply cast" objects to std::string in C++, (conversion in C++ follow some principles that we cannot explain fully here1). worse primitive types. For numeric types there is a function std::to_string for that

Secondly, there is such a thing known as template argument deduction which automatically deduces template parameters from arguments used to instantiate a function template or class template(C++17). In, C fun(A a, B b) - where A, B, and C are all template types. There is simply no way to deduce C with some further sorcery. or you could use a placeholder return type auto?

1Again, you should get good C++ book;

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • Thank you! so much – thippu Mar 20 '18 at 05:23
  • Don't worry about it, just select a good C++ material from the above link. You will appreciate it. - As for the `auto` *placeholder return type*, it would work for some limited cases in a C++11 compiler, and for broader cases in C++14. Again, if you don't know about these C++11, and C++14 compilers and/how to enable them on a recent version of your compiler, consult the materials and/or compiler docs, – WhiZTiM Mar 20 '18 at 05:34