简体   繁体   English

将结构传递给C ++中的模板函数

[英]Passing structure to a template function in C++

This is what i want to achieve, 这就是我想要实现的

  1. I want to pass structure as an argument to a function, which will return character pointer 我想将结构作为参数传递给函数,该函数将返回字符指针
  2. Everytime i will pass different structure as argument, which has distinct name and member variables of different types 每当我将不同的结构作为参数传递时,它具有不同类型的名称和成员变量
  3. The function has to identify the structure and its member variables, get the value of the member variable and concatenate it as a single string and return. 函数必须标识结构及其成员变量,获取成员变量的值并将其连接为单个字符串并返回。

Please suggest.... 请建议...。

am confused with template function and RTTI..... 与模板功能和RTTI混淆.....

您可以查看Boost.Fusion ,尤其是BOOST_FUSION_ADAPT_STRUCT

The first suggestion that crosses my mind is: redesign! 我想到的第一个建议是:重新设计!

If you really want to do it like you say and don't know the names of the fields, I don't think a template will do you any good. 如果您真的想按您的意愿去做而不知道字段的名称,那么我认为模板不会对您有任何帮助。 I'd suggest using the preprocessor: 我建议使用预处理器:

#define UGLY(str, int_field, char_field) whatever_you_want_to_do_with_them

and then you'd call: 然后您会打电话给:

a some_a;
b some_b;

UGLY(some_a, x, y);
UGLY(some_b, b, a);

There's no particularly nice way to iterate over class members. 没有特别好的方法可以遍历类成员。 One approach I've used is to store the values in a tuple, and provide named accessors if required: 我使用的一种方法是将值存储在元组中,并在需要时提供命名访问器:

struct a {
    std::tuple<int, char*> stuff;
    int  & x() {return std::get<0>(stuff);}
    char & y() {return std::get<1>(stuff);}
};

In the future (next year, perhaps?) we should get type deduction for function return types (as we already have for lambdas), which will remove error-prone type specifier in each accessor. 在将来(也许是明年?),我们应该对函数返回类型进行类型推导(就像对于lambda一样),这将删除每个访问器中容易出错的类型说明符。

You can then use variadic template functions to iterate over the tuples. 然后,您可以使用可变参数模板函数遍历元组。

Why you don't represent your structs (Which have same memeber types, but different names) as tuples?. 为什么不代表元组的结构(成员类型相同但名称不同)呢? IMHO if you want to treat this set of structs in the same manner, having different names is counterproductive: 恕我直言,如果您想以相同的方式处理这组结构,则使用不同的名称会适得其反:

template<typename...Ts>
void f(const std::tuple<Ts...>& tuple)
{
    ...
}

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

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