'reinterpret_cast':无法使用boost.dll从'重载函数'转换为'intptr_t'

Man*_*lva 5 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>();
Run Code Online (Sandbox Code Playgroud)

当我尝试在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
Run Code Online (Sandbox Code Playgroud)

在调用工厂方法时(如上一条注释行所示),如果没有BOOST_DLL_ALIAS宏,则可以很好地进行编译。

Yak*_*ont 3

// 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
)
Run Code Online (Sandbox Code Playgroud)

那应该可以解决它。

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

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

你也许还可以这样做:

template<class T>
T identity( T t ) { return std::move(t); }
Run Code Online (Sandbox Code Playgroud)

代替to_fptr

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