C++ Return 基于输入参数的类型推导

C++ Return Type Deduction Based on Input Parameters

我正在创建一个可以处理多种数据形式的 "knowledge processor"。我计划支持的数据形式是文本、视觉和听觉。每个都可以分别通过 TEXT、VISUAL 和 AUDIO 表示。所以每个 "knowledge" 或数据都在一个名为 "know_t".

的结构中表示
#define VISUAL 0
#define AUDIO  1
#define TEXT   2

struct know_t {
    k_type_t type;
    text_k_t text_value;
    visual_k_t visual_value;
    audio_k_t audio_value;
};

k_type_t 是来自 int 的类型定义。用来存放数据的"type",可以用代码段开头的#define'd宏来表示。

言归正传,我正在为处理器编写一个搜索算法。这些类型(VISUAL、AUDIO 和 TEXT)中的每一种都可以用 "prototype" 形式表示。例如,TEXT 数据可以通过 std::string 表示。这种数据的原型形式将用于搜索知识数据库。为了便于搜索,我创建了一个名为 "search_t" 的结构来表示搜索。

struct search_t {
    k_type_t type;
    visual_t visual_value;
    audio_t audio_value;
    std::string text_value;

    bool operator == (const struct __search_t &in);
};

现在这里的结构可能看起来和上面的结构几乎一模一样,know_t,它们有很大的不同。例如,虽然类型 "k_type_t" 包含字符串的数据,例如定义,但 std::string 是一种用于搜索的数据形式。所有其他形式的数据也是如此。

我正在使用 C++ 的 unordered_map 来完成搜索。 ISO C++ 标准规定,要使 unordered_map 起作用,密钥类型需要散列函数和“==”运算符,在本例中为 search_t。为此,我决定编写一个 get_value 函数,它 return 是搜索结构的原型值。问题是 随着数据类型的变化, return 类型也会发生变化

到目前为止,我已经为 == 运算符编写了以下代码,但我的编译器(带有 -std=c++11 的 GCC 4.8.1)似乎不喜欢它。

#define test(in) in.type == VISUAL ? in.visual_value : \
                 in.type == AUDIO  ? in.audio_value  : \
                 in.type == TEXT   ? in.text_value   : NULL

bool search_t::operator == (const struct search_t &in) {
    auto getval_search = [](const search_t &in) -> decltype(test(in)) {
        if (in.type == __VISUAL__)
            return in.visual_value;
        if (in.type == __AUDIO__)
            return in.audio_value;
        if (in.type == __TEXT__)
            return in.text_value;
    }

    bool equal = (bool)((this->type) == in.type);
    if (!equal)
        return false;

    search_t tmp = *this; // bugfix
    if (getval_search(tmp) == getval_search(in))
        return true;
}

有办法解决这个问题吗?

是的。修复它的简单方法是写一个正常的 == 比较:

struct search_t { // because C++
    k_type_t type;
    visual_t visual_value;
    audio_t audio_value;
    std::string text_value;

    bool operator == (const search_t& in) const {
        return type == in.type && visual_value == in.visual_value
            && audio_value == in.audio_value && text_value == in.text_value;
    }
}; 

如果它真的只是基于类型,那么我想你可以这样做:

bool operator == (const search_t& in) const {
    if (type != in.type) return false;

    switch (type) {
    case __VISUAL__: return visual_value == in.visual_value;
    case __AUDIO__: return audio_value == in.audio_value;
    case __TEXT__: return text_value == in.text_value;
    default: return false; // or something
}

请注意,根据 [global.names]:

,您的 type 是无效标识符

Each name that contains a double underscore __ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

最后,这可能不是一种适合存储的数据类型。考虑使用:

using search_t = boost::variant<visual_t, audio_t, std::string>;