【问题标题】:convert generic code from c# to template c++将通用代码从 c# 转换为模板 c++
【发布时间】:2015-09-26 19:35:49
【问题描述】:

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

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

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

【问题讨论】:

  • 它在 C# 中的作用是什么?
  • 我不认为你可以
  • C++ 中没有这样的东西,C++ 中也没有需要这样的东西。 C# 泛型在运行时被具体化,而 C++ 模板在编译时被实例化。因此,如果不满足约束,代码将无法编译。我想你可以使用static_assert,但如果你真的想要它。
  • 我的 C# 生锈了,但是这段代码真的需要 T 是 / 继承自 IGID&lt;T&gt; 吗?所以一个有效的对象需要类型IGID&lt;A&gt; == IGID&lt;IGID&lt;B&gt;&gt; == IGID&lt;IGID&lt;IGID&lt;C&gt;&gt;&gt;等等......无限级别。
  • 无论解决方案涉及某种形式的static_assert,现在该断言需要包含什么,我不确定。

标签: c# c++ templates generics


【解决方案1】:

你能做的最好的就是在一个空的基类中抛出一个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&lt;T&gt; 构造之前检查任何内容,所以我们没问题。

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>>
       ^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2022-01-02
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    相关资源
    最近更新 更多