c++ - 当使用由 std::unique_ptr 定义的一元运算时,术语在 std 算法中不计算为 1 个参数

标签 c++ c++11 stl

我正在尝试在标准算法中使用 std::unique_ptr 仿函数,但如果我这样使用它:

std::unique_ptr<IFormatter> format(new formatter("abcd"));
std::transform(vec.begin(), vec.end(), vec.begin(), *format.get()) 

我收到编译错误:

Error 1 error C2064: term does not evaluate to a function taking 1 arguments.

完整程序如下:

#include <iostream>
#include <string>
#include<algorithm>
#include<vector>

using namespace std;

struct IFormatter
{
protected:
    std::string keyFormat;
    void fun(std::string& str)
    {
        // do something here.
    }
public:
    IFormatter(std::string keyFormat) : keyFormat(keyFormat) {}
    virtual std::string operator() (const std::string &key) = 0;
};

struct formatter : IFormatter
{
    formatter(std::string keyFormat) : IFormatter(keyFormat) {}
    std::string operator() (const std::string &key)
    {
            std::string s = keyFormat;
            fun(s);
            return s;
    }
};

int main()
{        
    std::vector<std::string> vec{ "one", "two" };
    std::unique_ptr<IFormatter> format(new formatter("$ID$"));
    // This line compiles fine if i define format as - formatter format("abcd");
    std::transform(vec.begin(), vec.end(), vec.begin(), format.get());
    start s;
    return 0;
}

编辑:感谢大家的建议,但 format.get() 是一个拼写错误,我正在使用 *format.get() 并且我已经尝试过 *format (我同意 get() 并不是真正需要的。)。使用 std::ref(*format) 并不能解决问题。这很奇怪,但我仍然遇到同样的错误。

附言如果这很重要,我正在使用 visual studio 2013。

最佳答案

std::transform(vec.begin(), vec.end(), vec.begin(), std::ref(*format));

指针不可调用。但是你有一个指向基的指针,所以 std::ref 可以避免切片。


自从 MSVC 2013 的 reference_wrapper hates abstract classes , 使用 lambda:

std::transform(vec.begin(), vec.end(), vec.begin(),
               [&](const std::string& s) { return (*format)(s); });

关于c++ - 当使用由 std::unique_ptr 定义的一元运算时,术语在 std 算法中不计算为 1 个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38116375/

相关文章:

c++ - 使用 STL 映射作为结构的成员

c++ - 简单函数重载的考虑

c++ - std::function 表达式不会产生接受 1 个参数的函数

c++ - switch case 语句中包含成员变量 in case

linux - CMake 3.15.5 Bootstrap 因 g++ 9.3.0 而失败

c++ - 对自定义对象的 vector 进行排序

c++ - ostringstream 在插入输出后为空

c++ - Raspberry Pi ARM Float ABI 兼容性

c++ - 如何通过 boost::asio 和 shared_ptr 创建串口

c++ - 模板参数包会引发错误,而显式参数不会