c#类型列表类似于带层次生成器的Loki::Typelist
本文关键字:Loki Typelist 列表 类型 类似于 层次 | 更新日期: 2023-09-27 18:02:41
我喜欢Loki的c++ HierarchyGenerator,我想在c#中做同样的事情。
最后我想要的是一个在给定类型列表中每个参数都有一个虚函数的类。
我想转换的c++代码:
template <class T>
class SenderV
{
public:
virtual void Send(T t) = 0;
};
template <int i>
class Foo // Just to make it easy to show typelist, it's not interesting.
{ /* doIt definition */ };
typedef TYPELIST_2(Foo<1>,Foo<2>) FooSendables;
template <typename TList=FooSendables>
class FooSend : public Loki::GenScatterHierarchy <TList,SenderV>
{
public:
void Send(Foo<1> f) {f.doIt();std::cout<<"Sending Foo1."<<std::endl;};
void Send(Foo<2> f) {f.doIt();std::cout<<"Sending Foo2."<<std::endl;};
};
在c#。如果你不熟悉Loki,上面的FooSend类默认为:
class FooSend : SenderV<Foo<1> >, SenderV<Foo<2> >//including every type in TList
{ /*... as above */};
但是当给出一个新的TList时,它将是一个基于TList中的类型的不同层次结构。
我也对Loki中的GenLinearHierarchy感兴趣,如果它存在的话。
我总是可以尝试在语言之间进行翻译,但我不是一个大粉丝,因为我是c#的新手,只想做我的工作,而不是学习模板和泛型之间的细微区别。
我不知道Loki,但它看起来像你使用多重继承。c#不支持多重继承,我从多年的c#工作中学到的是,我并不怀念它。
using t4:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System" #>
namespace SomeNamespace
{
public interface Sender<T>
{
void Send<T>(T t);
};
<# string[] strings={"Foo1","Foo2","Foo3"};
foreach (String node in strings)
{ #> partial class <#= node #> {}
<# } #>
class z {}
public class FooSend: Sender<z><#
foreach (String node in strings)
{ #>, Sender<<#= node #>> <# } #>
{
}
}
我不能得到我想要的格式(而且,不管怎样,t4格式总是会很难看),但这解决了我的问题。
上面的代码产生:
namespace SomeNamespace
{
public interface Sender<T>
{
void Send<T>(T t);
};
partial class Foo1 {}
partial class Foo2 {}
partial class Foo3 {}
class z {}
public class ParentClass : Sender<z>, Sender<Foo1> , Sender<Foo2> , Sender<Foo3> {
}
}
正合我意