繁体   English   中英

C ++ static_assert检查模板是否已使用特定类型实例化

[英]C++ static_assert to check whether a template had been instantiated with a specific type

动机:我正在警告未来的维护者,如果他们在代码中做某事,则必须确保也做其他事情。

请注意,这里的“实例化”是指模板实例化,而不是实例化的对象

class A;
class B;

template<class T> void foo() {}
template<class T> class X {};

void f()
{
    foo<A>();   
}

void g()
{
    X<A> x; // ok
    X<B> y; // expecting static_assert here: if instantiated X with a type, 
            // foo must be instantiated with the same type too
}

至于你的评论:

任何组合都很好...是的,如果有帮助,我可以将函数包装在类中,但是我找不到那样的解决方案

我真的看不出应该解决什么。

如果您在类似的模板类中具有该功能

template<typename T>
class X {
    static void foo() {
        // Do something involving T
    }
};

已经保证X<A>X<A>::foo()实例化为相同的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM