如何在保持弃用警告的同时删除类

时间:2017-01-15 11:48:33

标签: c++ g++ clang++ c++17

我正在尝试寻找一种从我的库中删除已弃用的类的好方法,同时保留好的错误消息。这个想法是基于我已经用函数做的事情:

namespace
{
    [[deprecated("This function has been replaced by combust()")]]
    void explode() = delete; // Using variadic templates in reality to have all signatures covered

    void combust() {}
}

int main()
{
    explode();
    combust();
}

在clang中,这给了我一个很好的错误信息:

<source>:11:2: error: call to deleted function 'explode': This function has been replaced by combust()
explode();
^~~~~~~

GCC仅向我提供此功能已被删除的消息。但是,这仍然表明每个人都试图升级忽略弃用警告的库的意图。

所以,既然这是一个c ++库,我主要有类,我正在寻找正确的方法来做这些类的类似事情。我目前的方法如下:

namespace
{
    class [[deprecated("Class has been replaced by Bar")]] Foo
    {
        Foo () = delete; // And every other method I had in this class
    };
    class Bar
    {
    };
}

int main()
{
    Foo f;
    Bar b;
}

这基本上在clang中给出了以下警告/错误(在GCC中类似):

<source>:13:5: warning: 'Foo' is deprecated: Class has been replaced by Bar [-Wdeprecated-declarations]
Foo f;
^
<source>:3:60: note: 'Foo' has been explicitly marked deprecated here
class [[deprecated("Class has been replaced by Bar")]] Foo
^
<source>:13:9: error: call to deleted constructor of '(anonymous namespace)::Foo'
Foo f;
^
<source>:5:8: note: 'Foo' has been explicitly marked deleted here
Foo () = delete;
^

我可以使用这个无用的函数代码,因为这是单行代码,这对于类来说变得很麻烦,因为它们可以有很多方法。

所以,我正在寻找的是一个很好的方法来执行以下操作:(非编译代码)

class [[deprecated("Class has been replaced by Bar")]] Foo = delete;

关闭我到了一个oneliner是:

struct [[deprecated("Class has been replaced by Bar")]] Foo { Foo() = delete; };
struct [[deprecated("Class has been replaced by Bar")]] Foo;

请注意,这不包括通过引用传递Foo并调用某些方法的情况。

有没有更好的解决方案来删除类,同时对以下某些版本有明确的弃用警告?

1 个答案:

答案 0 :(得分:2)

可以使用static_assert执行此操作,因为它会导致带有消息的编译时错误。但是,如果置于非模板化函数中,它将始终置位。为了解决这个问题,我们将其作为模板函数,断言依赖于参数。如果不使用该函数,这不会导致错误,因为它不会被实例化。

template <int I = 0>
void explode()
{
    static_assert(I && false, "This function has been replaced by combust()");
}

int main()
{
    // error: static_assert failed: "This function has been replaced by combust()"
    explode();
}

这也可用于课程。但是,由于需要模板参数,因此需要使用typedef。

namespace
{
    template <int I = 0>
    class FooDeprec
    {
        static_assert(I && false, "Class has been replaced by Bar");

        FooDeprec() = default; // no need to delete
    };

    using Foo = FooDeprec<>;
}

int main()
{
    // error: static_assert failed "Class has been replaced by Bar"
    Foo f;
}

这样做的好处是不需要进行太多更改 - 您可以保留成员函数的声明。