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? 回答1: 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