c++ - 'reinterpret_cast' : cannot convert from 'overloaded-function' to 'intptr_t' with boost. dll

标签 c++ boost

我正在使用 Boost.dll 开发插件系统

#include <boost/config.hpp>
#include <boost/dll/alias.hpp>
#include <memory>

class base {
public:
  base(){};
  ~base(){};
  template <typename T>
  static std::shared_ptr<base> create() {
    return std::make_shared<T>();
  }
  virtual void do1() = 0;
};

class derived : public base {
public:
  derived(){};
  ~derived(){};
  virtual void do1() override {}
};

BOOST_DLL_ALIAS(base::create<derived>, // <-- this function is exported with...
                create_plugin          // <-- ...this alias name
)

// auto a = base::create<derived>();

当我尝试在 BOOST_DLL_ALIAS 宏中使用工厂方法时出现如下错误。

cl /c /ID:\Download\Compressed\boost_1_67_0 a.cpp

Microsoft (R) C/C++ Optimizing Compiler Version 19.12.25834 for x86

Copyright (C) Microsoft Corporation.  All rights reserved.

a.cpp

a.cpp(27): error C2440: 'reinterpret_cast': cannot convert from 'overloaded-function' to 'intptr_t'

a.cpp(27): note: Context does not allow for disambiguation of overloaded function

调用工厂方法时没有 BOOST_DLL_ALIAS 宏(如最后一行注释所示),它编译正常。

最佳答案

// this really does nothing:
template<class R, class...Args>
R(*to_fptr( R(*f)(Args...) ))(Args...) {
    return f;
}
// except avoid the bug in MSVC:
BOOST_DLL_ALIAS(to_fptr(base::create<derived>),
            create_plugin
)

应该可以解决问题。

当您尝试从模板函数的名称转换为 intptr_t 时,MSVC 似乎中断了。这是一个错误。

上述解决方法将其从直接处理模板函数的名称更改为仅处理函数指针。通过打破重载决议和转换为 intptr_t 分开,MSVC 不再阻塞。

你也可以这样做:

template<class T>
T identity( T t ) { return std::move(t); }

代替 to_fptr

to_fptr 是一个接受函数指针并返回它的函数。从函数返回函数指针的语法有点荒谬,这就是它难以阅读的原因。

关于c++ - 'reinterpret_cast' : cannot convert from 'overloaded-function' to 'intptr_t' with boost. dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51967446/

相关文章:

c++ - 什么时候调用构造函数以及如何不调用它们

c++ - 在循环外定义变量

C++ 任何具有特定值类型的迭代器?

c++ - LNK2019 DirectX 无法解析的外部符号;文件 dxerr.lib

c++ - 使用前导和尾随空格 boost spirit 解析字符串

c++ - 搜索/迭代 boost::spirit::qi::symbols

c++ - 嵌套的 boost::variant fusion 对的编译失败

C++ 冒泡排序双向链表

c++ - 如何使用 boost ublas 理解和修复递归模板实例化错误?

c++ - 具有不同数据类型的 std::move()