is_constructible 应该如何检测显式转换运算符?
How to detect explicit cast operator, should is_constructible work?
我想检测 class 是否具有显式转换运算符。
我尝试使用 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). Here's the full snippet 我用过。
我想检测 class 是否具有显式转换运算符。 我尝试使用 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). Here's the full snippet 我用过。