传递对模板函数调用运算符重载的引用

Passing a reference to template function call operator overload

我有一个 class,它使用模板函数重载函数调用运算符,如下所示:

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 -- Output of the address of 'i'

0110F664 -- Output of the address of the argument in the template overload

0110F738 -- Output of the address of the argument through 'test'

模板函数'test'仅用于验证。

visual studio 调试器确认它使用 'int' 而不是 'int&' 进行模板重载:

test_function_call.exe!Test::operator()(int t) Line 9 C++

我怎样才能强制它改用引用?有没有办法在模板函数调用运算符上使用 <> 来指定类型?

那是因为在你的例子中,cv 限定符和参数的引用在执行模板类型推导时被丢弃。通过 std::ref 包装器传递而不是

t(std::ref(i));

简单示例:

#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
}

您可以使用通用参考:

class Test
{
public:
    template<class T>
    void operator()(T&& t)
    {
        std::cout<<(&t)<<std::endl;
    };
};