c++ - 如何检测显式转换运算符,is_constructible 应该工作吗?

标签 c++ c++11 visual-c++ typetraits

我想检测一个类是否有显式转换运算符。 我已尝试使用 is_constructible,但以下断言因 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_constructible 应该在这里工作吗?
  • 如何以不同的方式检测它?

最佳答案

should is_constructible work here?

我认为应该,as there is nothing that excludes explicit conversions . g++4.8 (及更高版本) 和 clang++3.6 (及更高版本) 均成功编译了您的代码。


how to detect it in a different way?

您可以尝试使用 detection idiom ,它已针对 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 example

(!) 注意:此方法似乎无法在 MSVC 19.10 上正常工作( tested here )。这是 full snippet我用过。

关于c++ - 如何检测显式转换运算符,is_constructible 应该工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091576/

相关文章:

c++ - 如何处理错误cygwin_exception::open_stackdumpfile

Eclipse 错误格式化 C++11 统一初始化

c++ - 错误 C4592:符号将被动态初始化。 VS2015.1 静态常量 std::vector 字段

c++ - Visual Studio 中函数的返回值

c++ - 绑定(bind)模板化标准库函数

c++ - printf 跳过字符数组的第一个字符

c++ - 在 C++ 中迭代多个 std::vectors 的简单方法

c++ - 通过终端创建项目文件并编译失败,但通过 Qt Creator IDE 工作正常

python - 检查 PyObject 是否为 nullptr

c++ - VS2015从windows程序中删除linux上的文件