What's going on here? It seems the ability to declare testGeneric
with an auto&
parameter creates a weird situation where the function can be used to implement multiple dispatch.
Tested on gcc 10.1 or newer with "-fconcepts-ts" flag, also works on x86-64 clang (old concepts branch) via Compiler Explorer.
#include <iostream>
void testGeneric(auto &g)
{
g.print();
};
struct Generic
{
bool value = false;
void print() {
std::cout << value << std::endl;
};
};
auto main() -> int
{
auto foo = Generic();
auto bar = []() {
struct Generic
{
int value;
Generic(int v) : value(v){};
void print() {
std::cout << value << std::endl;
};
};
return Generic{123};
}();
auto baz = []() {
struct Generic
{
const char* value;
Generic(const char* v) : value(v){};
void print() {
std::cout << value << std::endl;
};
};
return Generic{"What the... ?"};
}();
testGeneric(foo); // prints 0 (false)
testGeneric(bar); // prints 123
testGeneric(baz); // prints "What the... ?"
};
testGeneric
is an abbreviated function template. It is functionally equivalent to the template declaration
template <class T>
void testGeneric(T &g)
{
g.print();
};
Your code will have 3 different testGeneric
functions, one for each type that you call it with.