C++ 如何检测显式cast运算符,应该是可构造的吗?

C++ 如何检测显式cast运算符,应该是可构造的吗?,c++,c++11,visual-c++,typetraits,C++,C++11,Visual C++,Typetraits,我想检测一个类是否有显式转换运算符。 我尝试过使用is_可构造,但以下断言在使用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, "Fai

我想检测一个类是否有显式转换运算符。 我尝试过使用is_可构造,但以下断言在使用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");
#包括
#包括
结构Foo{显式运算符std::string(){return”“;}};
静态断言(std::is_constructible::value,“Fail”);
我的问题是:

  • 你应该在这里施工吗
  • 如何以不同的方式检测它
你应该在这里施工吗

我认为应该。g++4.8(及以上版本)和clang++3.6(及以上版本)都成功编译了您的代码


如何以不同的方式检测它

您可以尝试使用,它是为C++17标准化的,但可在C++11中实现。(cppreference页面上提供了符合C++11的实现。)

struct Foo{explicit operator std::string(){return”“;};
模板
使用convertible_to_string=decltype(std::string{std::declval()});
//传球!
静态_断言(std::experimental::is_detected::value,“”);


(!)注意:这种方法在MSVC 19.10()上似乎无法正常工作。这是我使用的。

如果MSVC上甚至出现了
是可构造的
,为什么你会期望检测习惯用法(它依赖于表达式SFINAE,它在MSVC中的支持是出了名的糟糕/坏)起作用呢?我不使用MSVC-我建议了一种可能起作用,也可能不起作用的不同方法。我对它进行了测试,它似乎报告了错误的值。我将编辑答案以澄清这一点。我想在条件模板函数中使用check,这很好:typename=decltype(std::string(std::declval()),因此接受。。。谢谢。@simon你试过“假阳性”吗?(即当T不能转换为字符串时)@Vittorio Romeo是的,它似乎能工作。编译会在函数实现时失败,如果templatete参数不起作用,我会将其转换为std::string,但它会抱怨没有适用的重载。这…更新您的编译器。
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, "");