检查 class 是否有复制构造函数? return 对或错
Checking if a class has a copy ctor? return true or false
在下面的代码片段中,我试图确定 class 是否具有复制构造函数。
如果我的 class 没有复制构造函数,我只会看到编译错误。我无法做到 return 是真还是假。请帮助我..
template <typename T>
auto has_copy_ctor(T const& data) -> decltype(T(data), bool())
{
return true;
}
struct A
{
A(A const& obj) = delete;
};
struct B {};
int main()
{
std::cout << has_copy_ctor<B>(B{}) << std::endl; // compiles
std::cout << has_copy_ctor<A>(A{}) << std::endl; // does not compile
}
考虑使用 std::is_copy_constructible
。
SFINAE 的意思是模板替换失败不是错误,但如果没有模板匹配,你手上仍然有错误。在您的情况下,您需要第二个模板函数,该函数 returns false for 类 不可复制构造。
在 libc++ 中,is_copy_constructible
是使用 __is_constructible
非标准编译器内部实现的。由于这些被保持在最低限度,如果可能的话,"native C++" 实现很可能是非常重要的。
您可以使用std::is_copy_constructible
int main()
{
std::cout << std::is_copy_constructible<B>::value << std::endl;
std::cout << std::is_copy_constructible<A>::value << std::endl;
}
以下是如何扩展您的方法(使用函数模板)来检查类型是否可复制构造(在 <type_traits>
不可用的世界中):
#include <utility>
template <typename T>
constexpr auto has_copy_ctor(int)
-> decltype(T(std::declval<const T&>()), void(), bool())
{
return true;
}
template <typename T>
constexpr bool has_copy_ctor(char)
{
return false;
}
template <typename T>
constexpr bool has_copy_ctor()
{
return has_copy_ctor<T>(0);
}
在下面的代码片段中,我试图确定 class 是否具有复制构造函数。 如果我的 class 没有复制构造函数,我只会看到编译错误。我无法做到 return 是真还是假。请帮助我..
template <typename T>
auto has_copy_ctor(T const& data) -> decltype(T(data), bool())
{
return true;
}
struct A
{
A(A const& obj) = delete;
};
struct B {};
int main()
{
std::cout << has_copy_ctor<B>(B{}) << std::endl; // compiles
std::cout << has_copy_ctor<A>(A{}) << std::endl; // does not compile
}
考虑使用 std::is_copy_constructible
。
SFINAE 的意思是模板替换失败不是错误,但如果没有模板匹配,你手上仍然有错误。在您的情况下,您需要第二个模板函数,该函数 returns false for 类 不可复制构造。
在 libc++ 中,is_copy_constructible
是使用 __is_constructible
非标准编译器内部实现的。由于这些被保持在最低限度,如果可能的话,"native C++" 实现很可能是非常重要的。
您可以使用std::is_copy_constructible
int main()
{
std::cout << std::is_copy_constructible<B>::value << std::endl;
std::cout << std::is_copy_constructible<A>::value << std::endl;
}
以下是如何扩展您的方法(使用函数模板)来检查类型是否可复制构造(在 <type_traits>
不可用的世界中):
#include <utility>
template <typename T>
constexpr auto has_copy_ctor(int)
-> decltype(T(std::declval<const T&>()), void(), bool())
{
return true;
}
template <typename T>
constexpr bool has_copy_ctor(char)
{
return false;
}
template <typename T>
constexpr bool has_copy_ctor()
{
return has_copy_ctor<T>(0);
}