减少彼此紧密相关的模板参数

时间:2018-04-09 13:58:34

标签: c++ templates traits

我有以下代码:

template<typename T1, typename T2, typename T3, typename T4>
void Func(void); // signature

具有4个模板参数的简单模板功能。目前的用法是这样的:

Func<Foo1, Foo1Helper, Foo1Client, Foo1Server>();
Func<Foo2, Foo2Helper, Foo2Client, Foo2Server>();
Func<Foo3, Foo3Helper, Foo3Client, Foo3Server>();

现在在用法示例中,Foo1Helper, Foo1Client, Foo1Server, Foo2Helper, Foo2Client, Foo2Server, Foo3Helper, Foo3Client, Foo3Server是基于Foo1, Foo2, Foo3类生成的类。

我想要实现的是简化Func模板化函数,以便可以像这样调用它:

Func<Foo1>();

不需要这样也指定生成的类,因为类的名称与原始类绑定。

您对我如何实现这一目标有什么建议吗?

3 个答案:

答案 0 :(得分:4)

生成的类的含义并不完全清楚,但您可以为它们提供元函数:

from lxml import etree

def Definations_Parser():
    global Definations_tree
    global Definations_root
    parser =  etree.XMLParser(remove_blank_text = True)
    Definations_tree = etree.parse('C:\\Users\\dell\\Desktop\\definitions.xml', parser)
    Definations_root = Definations_tree.getroot()

def Definations_File_Modify():
    Process_1 = Definations_root.find('Process')
    property_1 = Process_1.find('property[@name="am"]')
    print(property_1.text)
    property_1.text = 'NEW_A'
    print(property_1.text)

    property_2 = Process_1.find('property[@name="24hours"]')
    print(property_2.text)
    property_2.text = 'NEW_B'
    print(property_2.text)

def Definations_File_Write():
    Definations_tree.write('C:\\Users\\dell\\Desktop\\definitions.xml', pretty_print = True)

Definations_Parser()
Definations_File_Modify()
Definations_File_Write()

然后在// declare metafunctions template <typename T> struct Helper; template <typename T> struct Client; template <typename T> struct Server; // provide implementations template <> struct Helper<Foo1> { using type = Foo1Helper; }; template <> struct Client<Foo1> { using type = Foo1Client; }; template <> struct Server<Foo1> { using type = Foo1Server; }; // the same for Foo2, Foo3, etc 中使用它们:

Func

答案 1 :(得分:2)

另一种选择是使用宏。语法有点不同,但你可以有类似

的东西
#define PARAMS(name) name, name##Helper, name##Client, name##Server

然后你会像

一样使用它
Func<PARAMS(Foo1)>();

答案 2 :(得分:2)

您可以将Foo相关类分组:

struct FooProfile {
    using T = Foo1;
    using Helper = Foo1Helper;
    using Client = Foo1Client;
    using Server = Foo1Server;
};

然后传递出来:

Func<FooProfile>();

函数实现看起来像这样:

template<typename Profile>
void Func() {
    using T = typename Profile::T;
    using Helper = typename Profile::Helper;
    using Client = typename Profile::Client;
    using Server = typename Profile::Server;

    // stuff
}