Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you force compiler to pass some variable by reference in C++?

Here is a simple example;

template <typename T>
void foo(T t) {}

std::string str("some huge text");
foo(str);

My question is how can I force the compiler to pass str by reference without modifying function foo?

like image 220
akk kur Avatar asked Dec 16 '22 11:12

akk kur


1 Answers

Pass the reference type explicitly:

template <typename T>
void foo(T t) {}

int main() {
   std::string str("some huge text");
   foo<std::string&>(str);
}

This does modify the function instantiation that you get (by generating a void foo<std::string&>(std::string& t)), but it doesn't modify the function template.

Live demo.

like image 125
Lightness Races in Orbit Avatar answered Jan 11 '23 23:01

Lightness Races in Orbit