尝试编译以下代码时出现错误:
#include <exception>
#include <boost/thread.hpp>
int _tmain(int argc, _TCHAR* argv[])
{
boost::promise<int> pr;
pr.set_exception(std::copy_exception(std::runtime_error("test")));
std::cout << "done" << std::endl;
}
error C2668: 'boost::copy_exception' : ambiguous call to overloaded function d:\projects\boost\boost_1_55_0\boost\thread\future.hpp 2092
我正在使用 VS2010 和 Boost 1.55
供引用:`boost::promise::set_exception'的实现如下:
void set_exception(boost::exception_ptr p)
{
// exception is stored here
}
template <typename E> void set_exception(E ex)
{
set_exception(copy_exception(ex)); // <- this is the line 2092
}
于是就有了模板版,也就是所谓的非模板版。 我假设在我的案例中模板版本失败。
使用以下代码时问题消失:
pr.set_exception(boost::copy_exception(std::runtime_error("test")));
即 boost::copy_exception()
被用来代替 std::copy_exception()
。
谁能建议使用 std::copy_exception
编译代码的选项?
最佳答案
tldr;您应该使用 boost::copy_exception
。
boost::copy_exception
返回一个 boost::exception_ptr
,所以当我们调用 set_exception()
时,set_exception(exception_ptr )
重载作为非模板是首选。这个调用做对了。
std::copy_exception
(现在称为 std::make_exception_ptr
)返回一个 std::exception_ptr
。这与 boost::exception_ptr
不是同一类型,因此首选函数模板 set_exception()
。实例化函数模板会导致对命名空间 boost
中的 copy_exception()
调用不合格。结果:
namespace boost {
template <class T> exception_ptr copy_exception(T const&);
}
因为这只是一个函数,所以我们随后对参数的关联命名空间进行参数依赖查找。 std::exception_ptr
的关联命名空间是 std
,因此我们最终还发现:
namespace std {
template <class E> exception_ptr copy_exception(E );
}
这些函数模板中没有一个比另一个更好,因此调用不明确。
由于使用 std::copy_exception
没有任何优势,而且标准中根本不存在该函数,因此请使用 boost::copy_exception
。它做你想做的。
或者,您可以只使用 std::promise
,它的 set_exception()
只有一个采用 std::exception_ptr
的重载>。
关于c++ - boost::promise::set_exception() 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38642099/