用于提升函数转换的匿名结构在gcc 5.4上失败

问题描述 投票:0回答:1

这段特殊的代码在gcc 5.4上失败了,但是在许多其他代码上运行,msvc 2015,clang和更新版本的gcc。

#include <boost/function.hpp>

#include <map>
#include <string>

typedef boost::function1<int, double> fn;

class fn_map : public std::map<std::string, fn> {
public:
    void reg(const std::string&, fn);
};

int main(int, char**) {
    fn_map fm;

    struct {
        int operator()(double v) {
            return static_cast<int>(v * 2.);
        }
    } factory;

    fm.reg("factory", factory);
}

void fn_map::reg(const std::string& nm, fn f) {
    this->insert(std::make_pair(nm, f));
}

错误信息:

no known conversion for argument 2 from 'main(int, char**)::<anonymous struct>' to 'fn {aka boost::function1<int, double>}'

最后一个ubuntu LTS仍然有gcc 5,所以如果可能的话我也想让这个代码在那里工作。

c++ gcc
1个回答
0
投票

struct定义从函数定义中移出到非匿名类型似乎解决了gcc上的这个特定问题。

#include <boost/function.hpp>

#include <map>
#include <string>

typedef boost::function1<int, double> fn;

class fn_map : public std::map<std::string, fn> {
public:
    void reg(const std::string&, fn);
};

namespace {
    struct factory_t {
        int operator()(double v) {
            return static_cast<int>(v * 2.);
        }
    };
}

int main(int, char**) {
    fn_map fm;

    factory_t factory;

    fm.reg("factory", factory);
}

void fn_map::reg(const std::string& nm, fn f) {
    this->insert(std::make_pair(nm, f));
}
© www.soinside.com 2019 - 2024. All rights reserved.