gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:11:17 25 4
gpt4 key购买 nike

我想检测一个类是否有显式转换运算符。我已尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com