【发布时间】:2016-05-14 00:07:34
【问题描述】:
我需要检查一个类 C 是否具有默认构造函数,无论是隐式的还是自定义的,以及 public、protected 或 private。
我尝试使用std::is_default_constructible<C>::value,如果C 具有public 默认构造函数(隐式或自定义)则返回true,但false 如果C 具有protected 或private 默认构造函数(不过,接缝似乎是标准行为。)
有什么方法可以检查一个类是否有protected 或private 默认构造函数?
注意(如果这可能有帮助):检查是从要检查的 C 类的 friend 函数执行的。
我需要执行此检查,以便默认构造与 m_objs 元组的 nullptr 指针相对应的对象,Foo 对象的成员(下面的部分 Foo 定义):
template<class... Objects>
class Foo
{
public:
Foo(Objects*... objects)
: m_objs(objects...)
{
// User construct a Foo objects passing a pack of pointers
// some of them are nullptr, some are not.
// The following call should default-construct objects corresponding
// to the null pointers of m_objs member tuple:
objs_ctor<Objects...>();
}
private:
template<class Obj, class O1, class ...On>
void objs_ctor()
{
objs_ctor<Obj>(); objs_ctor<O1, On...>();
}
template<class Obj>
typename std::enable_if<std::is_default_constructible<Obj>::value, void>::type
objs_ctor()
{
Obj*& obj = std::get<Obj*>(m_objs);
if (obj == nullptr)
obj = new Obj; // default-construct Obj
}
template<class Obj>
typename std::enable_if<!std::is_default_constructible<Obj>::value, void>::type
objs_ctor()
{
Obj*& obj = std::get<Obj*>(m_objs);
assert(obj != nullptr); // terminate if not pre-constructed
}
private:
std::tuple<Objects*...> m_objs;
};
打算用作:
struct A { };
class B {
B() = default;
template <class... Ts>
friend class Foo;
};
int main() {
// currently asserts, even though Foo<A,B> is a friend of B
// and B is default-constructible to its friends
Foo<A, B> foo(nullptr, nullptr);
}
上面的示例断言因为std::is_default_constructible<B>::value 为假,即使B 有一个[私人] 默认 ctor 并且Foo<A,B> 是 B 的朋友。
【问题讨论】:
-
易于检查受保护 - 只需从它继承并查看新人是否默认可构造。我不知道如何为私人做到这一点。
-
你检查过this post吗?声明“即使默认构造函数是私有的或受保护的,is_default_constructible 也会返回 true”,并提供了许多解决方案。返回值似乎取决于您使用的编译器的版本。此外,如果执行检查的类是 C 的朋友,您可能需要查看 workaround。
-
@SergeyA:我没想过这个技巧,很好的解决方案,谢谢;不过,仍然需要一些私人的东西;无论如何,谢谢。
-
@much_a_chos:我看过这个帖子; afaiu,这是一个错误(在我使用的编译器版本中修复),OP 需要解决。
-
可以把朋友功能的签名贴出来吗?