【发布时间】:2015-05-22 17:54:08
【问题描述】:
我有一个类,它使用模板函数重载函数调用运算符,如下所示:
class Test
{
public:
template<class T>
void operator()(T t)
{
std::cout<<(&t)<<std::endl;
};
};
我想用引用参数调用它,但是当尝试这样做时,它会将参数作为值传递。这是我的测试设置:
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;
}
输出是:
0110F738 -- 'i' 的地址输出
0110F664 -- 模板重载中参数地址的输出
0110F738 -- 通过'test'输出参数的地址
模板函数“test”仅用于验证。
Visual Studio 调试器确认它使用 'int' 而不是 'int&' 来进行模板重载:
test_function_call.exe!Test::operator()(int t) 第 9 行 C++
我怎样才能强制它使用引用呢?有没有办法在模板函数调用运算符上使用 来指定类型?
【问题讨论】:
-
你想要
void operator()(cont T& t) -
我不希望它是'const',我仍然需要能够修改值。
标签: c++ visual-studio-2013 operator-overloading windows-8.1 function-call-operator