[英]Passing a reference to template function call operator overload
I have a class which overloads the function call operator with a template function, like so: 我有一个类,它使用模板函数重载函数调用操作符,如下所示:
class Test
{
public:
template<class T>
void operator()(T t)
{
std::cout<<(&t)<<std::endl;
};
};
I'd like to call it with a reference argument, however when trying to do so, it passes the argument as a value instead. 我想用引用参数调用它,但是当试图这样做时,它会将参数作为值传递。 Here's my test setup: 这是我的测试设置:
template<class T>
void test(T t) {std::cout<<(&t)<<std::endl;}
int main(int argc,char *argv[])
{
Test t;
int i = 5;
std::cout<<(&i)<<std::endl;
t((int&)i); // Passes the argument as a value/copy?
test<int&>(i); // Passes the argument as a reference
while(true);
return 0;
}
The output is: 输出是:
0110F738 -- Output of the address of 'i' 0110F738 - 输出'i'的地址
0110F664 -- Output of the address of the argument in the template overload 0110F664 - 输出模板重载中参数的地址
0110F738 -- Output of the address of the argument through 'test' 0110F738 - 通过'test'输出参数的地址
The template function 'test' is merely for validation. 模板函数'test'仅用于验证。
The visual studio debugger confirms that it's using 'int' instead of 'int&' for the template overload: visual studio调试器确认它为模板重载使用'int'而不是'int&':
test_function_call.exe!Test::operator()(int t) Line 9 C++ test_function_call.exe!Test :: operator()(int t)第9行C ++
How can I force it to use a reference instead? 如何强制它使用引用? Is there a way to specify the types using <> on a template function call operator? 有没有办法在模板函数调用运算符上使用<>指定类型?
That's because in your case the cv-qualifiers and the reference-ness of the parameter are discarded when performing template type deduction. 那是因为在你的情况下,执行模板类型推导时会丢弃cv限定符和参数的引用。 Pass via a std::ref
wrapper instead 通过std::ref
包装器代替
t(std::ref(i));
Simple example: 简单的例子:
#include <iostream>
#include <functional>
template<typename T>
void f(T param)
{
++param;
}
int main()
{
int i = 0;
f(std::ref(i));
std::cout << i << std::endl; // i is modified here, displays 1
}
You may use universal reference: 您可以使用通用参考:
class Test
{
public:
template<class T>
void operator()(T&& t)
{
std::cout<<(&t)<<std::endl;
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.