简体   繁体   English

用于可变参数序列的C ++模板和代码生成:如何为每个参数/类型创建相似的代码块?

[英]C++ templates and code generation for Variadic Sequence: How to create similar code block for each argument/type?

I wonder if we could have class like this (pseudocode): 我想知道我们是否可以拥有这样的类(伪代码):

template <class Arg1T, ... class ArgNT>
class my_class
{
public:
    my_class(Arg1T Arg1, std::string Arg1_name  ... ArgNT  ArgN, std::string ArgN_name){}
};

And if we could auto generate a function for each provided argument type on compile time using defines for example to get something like (pseudocode): 并且如果我们可以在编译时使用定义自动为每个提供的参数类型生成一个函数,以获取类似(pseudocode)的信息:

template <class Arg1T, ... class ArgNT>
class my_class
{
public:
    my_class(Arg1T Arg1, std::string Arg1_name  ... ArgNT  ArgN, std::string ArgN_name){}
    // for each Arg we want to create a function like
    ArgMT   my_class_function(std::string name)
    {
       if(name == ArgM_name)
          return ArgM;
    }

};

Is such/or a bit similar thing possible in modern C++ and how to create it? 在现代C ++中,这种/或类似的事情是否可能发生,以及如何创建?

What I try to say is: I want to generate functions, for each class type provided to constructor from some function template. 我想说的是:我想为从某个函数模板提供给构造函数的每个类类型生成函数。 And wonder how to do such thing? 想知道如何做这样的事情? Here is shown how to repeat but how to repeat over provided to class arguments and thare types? 这里显示了如何重复,但是如何重复提供给类参数和thare类型的内容呢?

What I meant was if we'd know ammount of class templete arguments ( N ) we could create N variables of difrent types (one for each argument) and N strings (all private) and so we could create N functions for setters and getters of that (strings + variables) (which we would call in constructor). 我的意思是,如果我们知道大量的Templetemple类参数( N ),则可以创建N不同类型的变量(每个参数一个)和N字符串(全部为私有),因此可以为N setter和getter创建N函数。那(字符串+变量)(我们将在构造函数中调用)。 Main problem here is - how to solve times when you get same types twice or more, haw to get ammount of args from boost.preprocessor, how to filter same types? 这里的主要问题是-如何解决两次或两次以上相同类型的时间,如何从boost.preprocessor中获取大量的args,如何过滤相同类型?

You cannot overload functions based only on a return type, so no, it's not possible. 您不能仅基于返回类型重载函数,所以不行,这是不可能的。

If you take the argument names and my_class_function out of the picture, you're left with std::tuple<T0, ..., Tn> . 如果将参数名称和my_class_function从图片中删除,则剩下的是std::tuple<T0, ..., Tn> You can use std::get<N> to get N-th argument then (but it's entirely compile-time construct, N cannot be determined at runtime). 您可以使用std::get<N>来获取第N个参数(但这完全是编译时的构造,无法在运行时确定N)。

If you really need runtime handling, then mapping from std::string to boost::variant over N types might work. 如果确实需要运行时处理,则可以在N个类型上从std::string映射到boost::variant进行映射。

我认为在这种情况下,您通常可以使用接口和工厂方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM