2012-02-20 137 views
0

我有多种格式类型,每种类型都有一个名称和一个赋值给它们的值。我希望能够将格式类型作为参数传递给方法。声明看起来像CreateFile(4,3,2,UGS12_FMT),其中UGS12_FMT是一个C++类型。C++:使用类类型作为参数

请注意,我没有传入实例作为参数。有关如何完成此任务的任何建议?

回答

0

可能有很多方法来做到这一点。第一种方法是最值得推荐的方法,就是从共同父类继承每个类,因为它们共享“名称”和“值”,如前所述。

如果你真的需要知道它是在功能“的CreateFile”什么课,你最好改变实现的功能,使用多个功能,如

CreateFile(ClassA a) 
CreateFile(ClassB a) 

,而不是

CreateFile(Class x) 
    if x is an instance of ClassA 
     doSomething ... 
    else if x is an instance of ClassB 
     doSomething ... 
0

你想看什么是RTTI。支持因编译器而异,但基本功能在那里。一个好地方开始here

请注意,例如对于GCC,您需要帮助程序函数来取消type_info对象的名称。

编辑:当然,确保模板不能提供你想要的东西,这将是首选的方式。

+2

我看不出RTTI如何适合这里。 – jweyrich 2012-02-20 03:18:17

+0

*如果*你不能使用模板,并且你需要做一些最终取决于类型的事情,那么可以使用RTTI信息(通常在type_info的映射中起作用)来有条件地执行操作。这避免了编写一个可能很长且不那么可维护的枚举的需要。 – 2012-02-20 05:44:23

+0

我们不知道OP有多少文件类型正在考虑,但是如果他要编写代码来处理其中的每一个文件类型,那么维护'enum'和'struct'是最简单的任务。除此之外,'std :: type_info :: name()'在编译器中是不一致的,因此,如果考虑可移植性,我将它看作主要的con。 – jweyrich 2012-02-20 06:01:00

1

你不能在typename传递作为一个正常的函数参数,即你的片断

using UGS12_FMT = some_type; 
auto file = CreateFile(4,3,2,UGS12_FMT); // error 

不会有任何效果(当你CreateFile宏,这是strongly discouraged除外)。

相反,您可以基本上使用三种替代技术之一。

  1. 超载取空类型的不同参数的函数(所谓的标签分派):

    // declarations of tag types 
    struct format1 {} fmt1; 
    struct format2 {} fmt2; // etc 
    // overloaded file creation functions 
    file_type CreateFile(args, format1); 
    file_type CreateFile(args, format2); 
    // usage: 
    auto file = CreateFile(4,3,2,fmt1); // use format1 
    
  2. 使用一个template(和专门它为不同的格式类型)

    template<typename Format> 
    file_type CreateFile(args); // generic template, not implemented 
    template<> file_type CreateFile<Format1>(args); // one speciliasation 
    template<> file_type CreateFile<Format2>(args); // another speciliasation 
    
    auto file = CreateFile<Format1>(4,3,2); // usage 
    
  3. 使用enum类型传递信息。

    enum struct format { 
        f1,    // indicates Format1 
        f2 };    // indicates Format2 
    file_type CreateFile(args,format); 
    
    auto file = CreateFile(4,3,2,format::f1); 
    

最后,你可以结合使用traits类作为类似的技术,这些不同的方法。