使编译在模板类的特定实例化时失败
make compilation fail on specific instantiation of template class
使C++失败 在模板函数的特定实例化上编译解释了如果使用特定类实例化函数,如何使编译失败,但不知道如何使用类进行编译失败。
假设我有一堂课:
template<class T>
class foo;
还有另一个class Bar
.如果 foo 被实例化或专门用于Bar
,我将如何使编译失败?
所有解决方案都像运行时一样(即使评估是在编译时,错误只能在运行时给出,这是不合适的(。
如果您希望在实例化foo<Bar>
时出现硬编译错误,可以使用static_assert
(它还允许您提供自定义错误消息(:
template <class T>
class foo
{
static_assert(!std::is_same_v<T, Bar>,
"foo does not support Bar");
};
魔杖盒上的现场示例
在糟糕的专业化中放置一个static_assert(错误,"类不能用 xxx 实例化"(;
struct foo { };
template<typename T>
struct bar_base {
...
};
template<typename T>
struct foo : foo_base<T>
{ };
template<>
struct bar<foo>
{
static_assert(false, "bar cannot be instantiated with foo");
};
在这里,bar_base保存了所有实际的实现。
你可以做:
template<class T>
class foo {};
struct bar {};
template <>
class foo<bar>;
这声明了bar
的专用化,但没有定义它,因此任何试图导致实例化的东西都将失败。只需确保在与foo
的主要定义相同的头文件中声明此专用化,以便翻译单元无法看到主要定义,但看不到专用化。
相关文章:
- 从C++实例化QML
- 使用用户定义的类型 UDT 实例化 std::atomic<>。如果 UDT 具有虚函数,则 l 墨水将失败。为什么?
- 模板实例化失败:编译器选择不正确的重载函数
- 显式实例化失败的原因是什么
- 使编译在模板类的特定实例化时失败
- 类模板的成员函数有条件无效(隐式实例化有效;显式实例化失败)
- 如果实例化,如何使模板化变量专用化在编译时失败
- 在这个失败的C++类实例化中,我忽略了什么明显的事情
- 双模板化函数实例化失败
- 函数模板实例化失败
- 模板实例化与 constexpr 函数失败
- 模板化赋值运算符模板实例化失败
- std::conditional 的可变模板化使用,其中一种类型是实例化失败
- 为什么局部变量的实例化失败,而静态变量没有
- c++ dynamic_cast对装饰器实例化失败
- 由于抽象模板arg的实例化,Boost::lambda表达式编译失败.任何解释和/或解决方法
- 构建libsigc++失败(std::basic_ostream显式实例化)
- 当模板化函数实例化失败时,回退到备用函数
- QtSerialPort在错误的线程中实例化,导致信号/插槽失败
- 可以实例化 C++ 类模板,但具有相同模板参数的函数模板实例化失败