何が起きてる?testGeneric
パラメータで宣言するauto&
機能により、関数を使用して複数のディスパッチを実装できるという奇妙な状況が発生するようです。
「-fconcepts-ts」フラグを使用して gcc 10.1 以降でテスト済み。コンパイラ エクスプローラーを介して x86-64 の clang (古い概念ブランチ) でも動作します。
#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... ?"
};