Код: Выделить всё
#include
#include
#include
#include
template
void ref_visit(T& t, const Visitor& visit) { visit(t); }
template
void template_ref_visit(C& c, Visitor visit) { visit(c[0]); }
struct Printer {
void operator()(int& i) const { std::println("non-const: {}", i); }
void operator()(const int& i) const { std::println("const: {}", i); }
} printer;
int main()
{
int i{1};
int& ri{i};
const int& cri{i};
ref_visit(ri, printer); // prints "non-const: 1"
ref_visit(cri, printer); // prints "const: 1"
std::vector v{42};
std::vector& rv{v};
const std::vector& crv{v};
template_ref_visit(rv, printer); // prints "non-const: 42"
template_ref_visit(crv, printer); // FAILS TO COMPILE
}
Код: Выделить всё
template_template_const.cpp: In function ‘int main()’:
template_template_const.cpp:29:24: error: binding reference of type ‘std::vector&’ to ‘const std::vector’ discards qualifiers
29 | template_ref_visit(crv, printer); // FAILS TO COMPILE
| ^~~
template_template_const.cpp:10:31: note: initializing argument 1 of ‘void template_ref_visit(C&, Visitor) [with C = std::vector; T = int; Visitor = Printer]’
10 | void template_ref_visit(C& c, Visitor visit) { visit(c[0]); }
|
Код: Выделить всё
template
void template_ref_visit(const C& c, Visitor visit) { visit(c[0]); }
Подробнее здесь: https://stackoverflow.com/questions/791 ... -parameter