I have a function definition like this:
template <typename T> auto print(T t) -> decltype(t.print()) { return t.print(); }
The idea is that the argument must be of type T and must have a print function. This print function can return anything, explaining the need for decltype . So, for example, you can do:
struct Foo { int print() { return 42; } }; struct Bar { std::string print() { return "The answer..."; } }; ... std::cout << print(Foo()) << std::endl; std::cout << print(Bar()) << std::endl;
I read that templates cannot create instances of the runtime and that you can get classes from a base class and then determine their types to see which template argument to use. However, how would I do this for a non-class ? The idea is to have:
template <typename T> T print(T t) { return t; }
but it gives me ambiguous overload errors. Qualification does not work, i.e. print<Foo> . And the other got a 'cha, that if I had a functor like:
struct Foo { virtual int print(); operator int() const { return 42; } };
How to solve it now?
So my question is, can all of these ambiguities be resolved using templates, or do I need to write a bunch of redundant code?
Test
I gradually added tests, copying / pasting each editable solution from below. Here are the results:
With the following classes:
struct Foo { int print() { return 42; } operator int() const { return 32; } }; struct Bar { std::string print() { return "The answer..."; } operator int() const { return (int)Foo(); } }; struct Baz { operator std::string() const { return std::string("The answer..."); } };
And the following test result:
std::cout << print(Foo()) << std::endl; std::cout << print(Bar()) << std::endl; std::cout << print(42) << std::endl; std::cout << print((int)Foo()) << std::endl; std::cout << print("The answer...") << std::endl; std::cout << print(std::string("The answer...")) << std::endl; std::cout << print((int)Bar()) << std::endl; std::cout << print((std::string)Baz()) << std::endl;
Both are correctly output:
42 The answer... 42 32 The answer... The answer... 32 The answer...