How to force the 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 to get the compiler to pass str by reference without changing the foo function?

+4
source share
4 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 changes the function instance you created (by creating void foo<std::string&>(std::string& t) ), but does not change the function template.

Demo version.

+9
source

You can bypass the output of the template argument and explicitly skip std::string& .

+2
source

Among other answers, you can also 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 do not change the actual behavior of foo() and do not do your work with the overloaded version.

0
source

boost :: reference_wrapper should also solve your problem.

0
source

All Articles