这里发生了什么?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... ?"
};