繁体   English   中英

你如何强制编译器在C ++中通过引用传递一些变量?

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

这是一个简单的例子;

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

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

我的问题是如何在不修改函数foo的情况下强制编译器通过引用传递str?

明确传递引用类型:

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) ),但它不会修改函数模板。

现场演示。

您可以绕过模板参数推导并显式传递std::string&

除了其他答案,你还可以考虑重载foo()

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

void foo(std::string &t) {}

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

这样您就不会更改实际的foo()行为并使用重载版本完成工作。

boost :: reference_wrapper也应该解决你的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM