gpt4 book ai didi

c# - 将通用代码从 C# 转换为模板 C++

转载 作者:行者123 更新时间:2023-11-30 01:46:40 24 4
gpt4 key购买 nike

我尝试将此代码(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>>
^

关于c# - 将通用代码从 C# 转换为模板 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com