类型不可知的吸气方法 [英] Type agnostic getter methods
问题描述
我正在为系统的客户端编写程序,该系统以随机顺序返回自然类型的值(有些可以是int,有些可以浮点数,有些可以是字符串[好,几乎是自然的])。问题是,我不知道在编译时值将是什么类型。
I'm writing a client for a system that returns values of natural types in random order (some can be int, others float, others string [well, almost natural]). The problem is, I don't know what type a value will be at compile time.
因为我不知道要返回的值的类型,直到之后已经查询了远程系统,提供统一接口的最佳方法是什么,该接口允许客户端库的用户提取正确类型的值?
Since I don't know the type of the value to be returned until after the remote system has been queried, what is the best way to provide a uniform interface that allows a user of the client library to extract the value in the right type?
如果查询远程系统一次返回一个字符串,我希望我的 get_value()
返回一个字符串。如果是int,则使其返回int。或者,如何让客户端库用正确的类型调用getter?
If querying the remote system once returns a string, I'd like my get_value()
to return a string. If an int, make it return an int. Alternatively, how to have the client library call the getter with the right type?
我想带有类型提示的模板将是实现此目标的好方法?
I guess templates with type hinting would be a good way to achieve this?
推荐答案
有两种不同的用例。如果客户端程序可以提前知道所需值的类型,则可以为每种可能的类型使用不同的getter(旧的C语言,例如 getInt
, getDouble
, getString
),或使用模板化的吸气剂(现代C ++方式):
There are two different use case. If the client program can know in advance the type of the value it wants, you can either use a different getter for each possible type (the good old C way with for example getInt
, getDouble
, getString
), or use templated getters (modern C++ way):
template <class T>
T get(char *byte_array) {
T value;
# manage to extract the value
return T;
}
并明确实例化它们以确保它们可用。
and explictely instanciate them to make sure that they will be available.
在客户端库中,用法为:
In the client library, the usage will be:
int i = get<int>(byte_array);
如果客户端程序可能以编译时不知道的顺序接收数据,则必须找到一个返回 variant 数据类型的方法(旧的Basic程序员请记住这一点)。您可以在boost或C ++ 17中找到实现,但是简单的实现可能是:
If the client program may received data in an order which is unknow at compile time, you must find a way to return a variant data type (old Basic programmers remember that). You can find implementations in boost or C++ 17, but a trivial implementation could be:
struct variant {
enum Type { INT, DOUBLE, STRING, ... } type;
union {
int int_val;
double d_val;
std::string str_val;
...
};
};
在这种情况下,客户端程序将使用
In that case the client program will use
variant v = get(byte_array);
switch v.type {
case INT:
...
}
这篇关于类型不可知的吸气方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!