c++ - 有没有办法 constexpr 检查一个类是否有任何可访问的构造函数?

标签 c++

std::is_constructible 及其变体(用于复制、移动和默认构造函数)。

但是,有没有一种方法可以通过 constexpr 检查对象是否可以构造?

最佳答案

is there a way to do a constexpr check whether an object can be constructed at all?

您可以编写一个constexpr 函数,然后添加不同的检查(is_default_constructible 等),如下所示:

class C 
{
    public:
       C() = default;
};
class C2
{
    public:
     C2() {}
    private:
     C2(const C2&){}
};
template<typename T>
constexpr bool checkAccessibleCtor()
{
    //write checks here according to your need
    return std::is_default_constructible<T>::value && 
        std::is_copy_constructible<T>::value && 
        std::is_move_constructible<T>::value;
}
int main()
{
    std::cout << checkAccessibleCtor<C>()<<std::endl;   //print 1
    std::cout << checkAccessibleCtor<C2>()<<std::endl; //prints 0
}

关于c++ - 有没有办法 constexpr 检查一个类是否有任何可访问的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73345836/

相关文章:

C++ 尝试使用#ifndef 和#include 语句

c++ - 断言代码不能编译

c++ - 使用 `void*` 将右值引用绑定(bind)到左值

c++ - 为什么 "stdint.h"的实现不同意 UINT8_C 的定义?

C++ 比较器对结构 vector 进行无效排序

c++ - GDB。只捕获未捕获的异常

c++ - 该指令的 #endif 丢失

c++ - 从 const 派生的类的模板问题

c++ - 为什么转换可以涉及两个用户定义的转换函数/构造函数?

C++ - 在哪里抛出异常?