【问题标题】:How do I define a generic/templated class like the C# example below如何定义一个通用/模板类,如下面的 C# 示例
【发布时间】:2012-02-03 13:21:44
【问题描述】:

在 C# 中:

public sealed class StateMachine<TState, TTrigger>

我想写一个 C++ 等价物。

【问题讨论】:

  • 你会想要改写它

标签: c# c++ templates


【解决方案1】:

像这样:

template <typename TState, typename TTrigger>
class StateMachine
{
    //...
};

【讨论】:

    【解决方案2】:

    This site 对如何制作模板类有很好的解释。示例:

    // function template
    #include <iostream>
    using namespace std;
    
    template <class T>
    T GetMax (T a, T b) {
      T result;
      result = (a>b)? a : b;
      return (result);
    }
    
    int main () {
      int i=5, j=6, k;
      long l=10, m=5, n;
      k=GetMax<int>(i,j);
      n=GetMax<long>(l,m);
      cout << k << endl;
      cout << n << endl;
      return 0;
    }
    

    将此与this previous Stack Overflow question 结合使用以实现类的密封方面。

    【讨论】:

      【解决方案3】:

      您可以使用 Stuart 和 Xeo 建议的方法,如果您想在此处密封课程,请使用 link 说明如何操作。

      已编辑:this 更好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 2015-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多