将成员声明与enable_if一起使用

Using member declaration with enable_if?

本文关键字:if 一起 enable 成员 声明      更新时间:2023-10-16

我需要条件使用成员声明。

template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template <typename T>
struct A : public B<is_default_constructible<T>::value> {
    using B<is_default_constructible<T>::value>::foo();
    void foo(int) {}
};

这显然不起作用,因为B<bool>::foo没有定义在一半的情况下。我怎样才能做到这一点?拥有B<>::foo()在foo(int)旁边的A<T>作用域中是否可见?

这是我的解决方案。我相信这不会是最好的,但它完成了任务。

struct A {
    void foo(int) {}
};

struct A应该包含在这两种情况下都要定义的方法。

template <bool> struct B;
template <> struct B<false> : A {};
template <> struct B<true> : A { 
    using A::foo;
    void foo() {} 
};

B<false>的情况下,仅定义void foo(int)。在B<true>的情况下,定义了void foo(int)void foo()

template <typename T>
struct C : public B<is_default_constructible<T>::value> {};

现在我不必担心B<is_default_constructible<T>::value>::foo()在某些情况下没有定义。

class D { D() = delete; };
int main()
{
    C<int> c1;
    c1.foo(1234);
    c1.foo();
    // both methods are defined for C<int>
    C<D> c2;
    c2.foo(1234);
    // c2.foo(); // undefined method
    return 0;
}

使用专业化

enable_if不能用于此。你也需要专门化struct A

#include <type_traits>
template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template <typename T, bool default_constructible = std::is_default_constructible<T>::value>
struct A : public B<default_constructible> {
    using B<default_constructible>::foo;
    void foo(int) {}
};
template<typename T>
struct A<T, false> : public B<false> {
    void foo(int) {}
};

避免foo(int)的重复代码

如果foo(int)在这两种情况下都具有相同的功能,您可能需要从另一个基本结构中派生它:

#include <type_traits>
template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template<typename T>
struct C {
  void foo(int) {}
};
template <typename T, bool default_constructible = std::is_default_constructible<T>::value>
struct A : public B<default_constructible>, public C<T> {
    using B<default_constructible>::foo;
    using C<T>::foo;
};
template<typename T>
struct A<T, false> : public B<false>, public C<T> {
    using C<T>::foo;
};

消除那丑陋的嘘声

最后,要从struct A的模板参数中删除bool,您可能需要将选择foo重载的责任转发给基类。这还有一个优点,即不会为您可能想要添加的其他struct A成员复制代码。

#include <type_traits>
template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template<typename T>
struct C {
  void foo(int) {}
};
template <typename T, bool default_constructible = std::is_default_constructible<T>::value>
struct base_A : public B<default_constructible>, public C<T> {
    using B<default_constructible>::foo;
    using C<T>::foo;
};
template<typename T>
struct base_A<T, false> : public B<false>, public C<T> {
    using C<T>::foo;
};
template <typename T>
struct A : public base_A<T> {
    // Other members.
};