问题
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 modify the function template.
Live demo.
回答2:
You can bypass template argument deduction and explicitly pass std::string&.
回答3:
Apart from the other answers, you can also think to overload foo():
template <typename T>
void foo(T t) {}
void foo(std::string &t) {}
std::string str("some huge text");
foo(str);
This way you don't change the actual foo() behavior and get your work done with the overloaded version.
回答4:
boost::reference_wrapper should also solve your problem.
来源:https://stackoverflow.com/questions/6800824/how-do-you-force-compiler-to-pass-some-variable-by-reference-in-c