【问题标题】:Static Assert that a type A can be constructed from type B静态断言类型 A 可以从类型 B 构造
【发布时间】:2014-04-28 21:55:37
【问题描述】:

我正在尝试做一个静态断言来检查两种类型 A 和 B;类 A 应该具有签名 A(B& b) 或 A(const B& b) 的公共构造函数。

如果存在公共 A(B& b) 或 A(const B& b) 或 A(B b),我希望有某种 is_constructable_from<A, B>::value 的计算结果为 true

我想这和 boost is_convertible type_trait 有点不同。

我如何做到这一点?

我是否错过了在 Boost Type Traits 或 Concept Check 库中执行此操作的内容?

现在我需要这个来静态检查表达式 A a(b) 是一个有效的表达式,正如 Sehe 所建议的那样,它比以前的概念限制更少。欢迎为这两种情况提供解决方案。我可以使用 Boost。

【问题讨论】:

  • 您的“换句话说”描述描述了/不同/要求! (隐式转换和绑定临时......)
  • 请原谅我的新手 C++ 知识,但我不明白您评论的临时部分。现在我对第二个描述比第一个更严格的描述感到满意。
  • 如果您的 ctor 采用 const& 或一个值,它可以接受隐式转换的结果(临时)。
  • 好的,我更新了我的问题。我想知道这两个概念检查的解决方案。
  • 我想不到,如果你可以从 B 转换为 A,那么有 A(B)、A(B &)、A(const B &)、A(B&&) , A(const B &&) 或转换运算符,例如:B::operator A()。所以我不清楚你想禁止什么。

标签: c++ boost sfinae typetraits c++-concepts


【解决方案1】:

构造函数不是成员函数 - 它们没有您可以获取的地址,因此无法使用 SFINAE* 直接测试它们的存在。

虽然它不是完全您所要求的,但使用 C++11,您可以接近 std::is_constructible, 并且使用 C++03 你必须推出自己的:

template<class A, class B = void>
struct is_constructible;

template<class A, class B>
struct is_constructible { 

    template<class U> static U declval();    
    template<std::size_t N> struct dummy;
    template<class U> static char test(dummy<sizeof(U(declval<B>()))>*);        
    template<class U> static long test(...);

    static const bool value = sizeof(test<A>(0)) == sizeof(char); 
};

* 以下是一个有趣的尝试,但据我所知,它在编译器中效果不佳:
Check at compile time class constructor signature

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 2021-08-25
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多