如何检测明确的铸造运算符,应IS_Constructibles工作

How to detect explicit cast operator, should is_constructible work?

本文关键字:运算符 IS 工作 Constructibles 何检测 检测      更新时间:2023-10-16

我想检测,如果类具有显式转换操作员。我已经尝试使用IS_Construction,但是MSVC 19.00.23506。

,以下断言失败了。
#include <string>
#include <type_traits>
struct Foo { explicit operator std::string() { return ""; } };
static_assert(std::is_constructible<std::string, Foo>::value, "Fail");

我的问题是:

  • 应该在这里IS_Construction工作吗?
  • 如何以不同的方式检测它?

应该在这里is_constructible工作吗?

我认为应该这样做,因为没有什么可以排除明确的转换。G 4.8 (及以上)和clang 3.6 (及以上)成功编译了您的代码。


如何以不同的方式检测它?

您可以尝试使用检测成语,该是针对C 17的标准化,但可以在C 11 中实现。(在CPPReference页面上提供了C 11兼式实现。)

struct Foo { explicit operator std::string() { return ""; } };
template <class T>
using convertible_to_string = decltype(std::string{std::declval<T>()});
// Passes!
static_assert(std::experimental::is_detected<convertible_to_string, Foo>::value, "");

wandbox示例

(!)注意:此方法似乎在MSVC 19.10 上无法正常工作(在此处测试)。这是我使用的完整片段。