C++ 如何在保留弃用警告的同时删除类
我试图寻找一种好方法,从我的库中删除不推荐的类,同时保留好错误消息。这个想法基于我在函数方面已经做过的一些事情:C++ 如何在保留弃用警告的同时删除类,c++,g++,clang++,c++17,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 combu
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();
}
在叮当声中,这给了我一个很好的错误信息:
<source>:11:2: error: call to deleted function 'explode': This function has been replaced by combust()
explode();
^~~~~~~
这基本上为我提供了以下警告/错误(以及GCC中的类似警告/错误):
我对oneliner的最终结论是:
struct [[deprecated("Class has been replaced by Bar")]] Foo { Foo() = delete; };
struct [[deprecated("Class has been replaced by Bar")]] Foo;
请注意,这不包括通过引用传递Foo和调用某些方法的情况
是否有人有更好的解决方案来删除类,同时对以下某些版本发出明确的弃用警告?可以使用
static\u 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();
}
模板
空洞爆炸()
{
静态断言(I&&false,“此函数已被combust()替换”);
}
int main()
{
//错误:静态_断言失败:“此函数已被combust()替换”
爆炸();
}
这也可以用于类。但是,由于需要模板参数,因此需要使用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;
}
名称空间
{
模板
类foodprec
{
静态断言(I&&false,“类已被Bar替换”);
foodprec()=default;//无需删除
};
使用Foo=foodprec;
}
int main()
{
//错误:静态_断言失败“类已被Bar替换”
福福;
}
这样做的好处是不需要太多更改—您可以保留成员函数的声明。我认为您使用的术语不正确。“弃用”永远不应指“非功能性”。[[deprecated]]应仅应用于有效的方法和类。弃用是一种迹象,表明虽然现在可以使用,但以后可能会将其删除。永远不要删除函数/类,然后将它们标记为[[不推荐]]。只需删除它们;编译器会让类/函数的用户知道它们很快就会消失;)@Nicolabolas解释说,这是第二步,可以简化那些忽略弃用警告的人的迁移。对于函数,Clang的人认为这是一个好主意,因为他们甚至有一个特定的错误消息将两者结合起来。“并且调用了一些方法”--如何在
类Foo{Foo()=delete;}
上调用方法?f(Foo&Foo){Foo.method();}
struct [[deprecated("Class has been replaced by Bar")]] Foo { Foo() = delete; };
struct [[deprecated("Class has been replaced by Bar")]] Foo;
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();
}
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;
}