我正在使用 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/