将泛型代码从c#转换为模板c++

convert generic code from c# to template c++

本文关键字:c++ 转换 泛型 代码      更新时间:2023-10-16

我尝试将这段代码(c#代码)转换为c++代码

public abstract class IGID<T>
    where T : IGID<T>

如何在c++中实现这样的模板条件?

最好的方法是将static_assert扔到一个空基类中,该基类将在构造时启动。您必须延迟到使用,因为所有类型必须完成后才能进行此类检查。

我们有了断言对象:
template <typename C>
struct Require {
    Require() {
        static_assert(C::value, "!");
    }
};

为空,因此不会增加开销。然后是:

template<typename T>
struct IGID : Require<std::is_base_of<IGID<T>, T>>
{
};

即使T在这里是不完整的,我们不检查任何东西,直到IGID<T>被构造,所以我们没事。

struct A : IGID<A> { }; // okay

但:

struct B : IGID<int> { }; 
main.cpp:8:9: error: static_assert failed "!"
        static_assert(C::value, "!");
        ^             ~~~~~~~~
main.cpp:13:8: note: in instantiation of member function 'Require<std::is_base_of<IGID<int>, int> >::Require' requested here
struct IGID : Require<std::is_base_of<IGID<T>, T>>
       ^