你如何强制编译器在C ++中通过引用传递一些变量? [英] How do you force compiler to pass some variable by reference in C++?

查看:106
本文介绍了你如何强制编译器在C ++中通过引用传递一些变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的例子;

Here is a simple example;

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

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

我的问题是如何强制编译器通过引用传递str
foo?

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

推荐答案

明确传递引用类型:

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

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

(通过生成 void foo< std :: string&>(std :: string& t)),但不会修改函数模板。

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.

这篇关于你如何强制编译器在C ++中通过引用传递一些变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆