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

末鹿安然 提交于 2020-01-01 11:55:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!