【问题标题】:Is there any reason to use final specifier with unions?是否有任何理由将最终说明符与工会一起使用?
【发布时间】:2016-10-15 20:09:43
【问题描述】:

final 说明符 可以与类或结构一起使用以禁止从它们继承。在这种情况下,我们只需要将我们的类/结构标记为final

class Foo final {
    // ...
};

更有趣的是,相同的语法对联合有效:

union Foo final {
    // ...
};

来自cpp.reference.com

final 也可以与联合定义一起使用,在这种情况下,它具有 没有影响(除了对 std::is_final 的结果),因为联合 不能派生自)

看起来 final 说明符 与联合的使用是荒谬的。如果是这样,为什么甚至可以将联合标记为最终?只是为了一致性?或者关于 type_traits 的一些东西?我错过了什么吗?在某些情况下我们需要将 final 与 unions 一起使用吗?

【问题讨论】:

  • 如果你迷恋“没有效果”。这远非“荒谬”。
  • @ddriver 抱歉,我没听清。 “恋物癖”是什么意思?
  • 我的意思正是它的意思。
  • 这可能是因为union被认为是一个类,所以final关键字适用于它。
  • @AndyG 这基本上意味着,唯一的原因是一致性......

标签: c++ c++11


【解决方案1】:

就像你说的,union 不能派生,所以final 说明符对它们绝对没有影响。 Other 除了std::is_final 的结果,可以使用下面的代码测试该行为,其中所有断言都通过:

struct P final { };
union U1 { };
union U2 final { }; // 'union' with 'final' specifier

template <class T>
void test_is_final()
{
    static_assert( std::is_final<T>::value, "");
    static_assert( std::is_final<const T>::value, "");
    static_assert( std::is_final<volatile T>::value, "");
    static_assert( std::is_final<const volatile T>::value, "");
}

template <class T>
void test_is_not_final()
{
    static_assert(!std::is_final<T>::value, "");
    static_assert(!std::is_final<const T>::value, "");
    static_assert(!std::is_final<volatile T>::value, "");
    static_assert(!std::is_final<const volatile T>::value, "");
}

int main()
{
   test_is_final    <P>(); 
   test_is_not_final<P*>();    
   test_is_not_final<U1>();
   test_is_not_final<U1*>();
   test_is_final    <U2>(); // 'std::is_final' on a 'union' with 'final' specifier
   test_is_not_final<U2*>();   
}

【讨论】:

    【解决方案2】:

    您可能正在使用依赖于std::is_final&lt;T&gt; 的第三方库(即使来自同一家公司,但没有写入权限)。一个常见的例子是半正确编写的单例模式:您绝对不希望 BaseSingleton 和 DerivedSingleton 被并行实例化。防止这种情况的一种(众所周知的糟糕)方法是std::enable_if&lt;&gt; for std::is_final&lt;T&gt;。因此,您需要能够以某种方式指定它。问题是,为什么工会不会自动成为最终的。

    【讨论】:

      猜你喜欢
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多