我想检测一个类是否有显式转换运算符。 我已尝试使用 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, "");
(!) 注意:此方法似乎无法在 MSVC 19.10 上正常工作( tested here )。这是 full snippet我用过。
关于c++ - 如何检测显式转换运算符,is_constructible 应该工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091576/