简体   繁体   English

在失败的 If 语句中调用 Switch 语句

[英]Switch Statement Called Inside Of A Failed If Statement

Sorry if the title is misleading or generic.抱歉,如果标题具有误导性或通用性。 I literally do not know what else to name the title.我真的不知道还有什么可以命名的标题。 I have created a function that converts a vector of any type into a string.我创建了一个 function 将任何类型的向量转换为字符串。 I have template<typename K> prefacing the function code, which is used as a placeholder for the type of the vector.我有template<typename K>前缀 function 代码,它用作向量类型的占位符。 My main problem is the nested switch statements inside of if statements used to check the type of the vector.我的主要问题是用于检查向量类型的 if 语句中的嵌套 switch 语句。 Even when the if statement checks fail, the code still gives this error: a switch expression of type 'float' is not valid .即使 if 语句检查失败,代码仍然会出现此错误: a switch expression of type 'float' is not valid For example, if I had a vector of type float declared in main, then I used the function to convert the vector to a string, it would give me two errors.例如,如果我在 main 中声明了一个float类型的向量,那么我使用 function 将向量转换为字符串,这会给我两个错误。 One for the switch statement nested inside the int check, and the other for the switch statement nested inside of the char check.一个用于嵌套在int检查内的 switch 语句,另一个用于嵌套在char检查内的 switch 语句。 This is very frustrating as these if checks should fail due to the vector not being an int or char .这是非常令人沮丧的,因为如果由于向量不是intchar而导致检查失败。 Furthermore, they can't be both int and char at the same time either, I've been trying to dissect my code and figure this problem out.此外,它们也不能同时是intchar ,我一直在尝试剖析我的代码并解决这个问题。 but I've come to no solution.但我没有解决办法。 Maybe it's because I'm new to templates and the std::is_same function.也许是因为我不熟悉模板和std::is_same function。

Here is my header file code (it's kinda long sry):这是我的 header 文件代码(有点长):

#include <string>
#include <vector>

//Converts a vector of any type into a string like this: 2, 5, 6, 3, (Yes the comma stays at the end like that. That can be fixed but it will require huge amounts of code)
template<typename K>
std::string convertToString(std::vector<K>& V) {

    std::string result_str{""};

    for (auto s : V) {

        if (std::is_same<K, bool>::value) {

            if (s == true) {

                result_str += "true, ";

            }
            else if (s == false) {

                result_str += "false, ";

            }

        }
        else if (std::is_same<K, int>::value) {

            switch (s) {

            case 1:
                result_str += "1, ";
                break;

            case 2:
                result_str += "2, ";
                break;

            case 3:
                result_str += "3, ";
                break;

            case 4:
                result_str += "4, ";
                break;

            case 5:
                result_str += "5, ";
                break;

            case 6:
                result_str += "6, ";
                break;

            case 7:
                result_str += "7, ";
                break;

            case 8:
                result_str += "8, ";
                break;

            case 9:
                result_str += "9, ";
                break;

            default:
                result_str += "Not a digit, ";

            }

        }
        else if (std::is_same<K, float>::value) {

            //Because switch statements cannot take floating point values (For some reason I thought this would fix my problem but it didn't)
            if (s == 1) {

                result_str += "1, ";

            }
            else if (s == 2) {

                result_str += "2, ";

            }
            else if (s == 3) {

                result_str += "3, ";

            }
            else if (s == 4) {

                result_str += "4, ";

            }
            else if (s == 5) {

                result_str += "5, ";

            }
            else if (s == 6) {

                result_str += "6, ";

            }
            else if (s == 7) {

                result_str += "7, ";

            }
            else if (s == 8) {

                result_str += "8, ";

            }
            else if (s == 9) {

                result_str += "9, ";

            }
            else {
                result_str += "., ";
            }

        }
        else if (std::is_same<K, char>::value) {

            switch (s)
            {
            case 'a': 
                result_str += "a, ";
                break;

            case 'A':
                result_str += "A, ";
                break;

            case 'b': 
                result_str += "b, ";
                break;

            case 'B':
                result_str += "B, ";
                break;

            case 'c': 
                result_str += "c, ";
                break;

            case 'C':
                result_str += "C, ";
                break;

            case 'd': 
                result_str += "d, ";
                break;

            case 'D':
                result_str += "D, ";
                break;

            case 'e': 
                result_str += "e, ";
                break;

            case 'E':
                result_str += "E, ";
                break;

            case 'f': 
                result_str += "f, ";
                break;

            case 'F':
                result_str += "F, ";
                break;

            case 'g': 
                result_str += "g, ";
                break;

            case 'G':
                result_str += "G, ";
                break;

            case 'h':
                result_str += "h, ";
                break;

            case 'H':
                result_str += "H, ";
                break;

            case 'i':
                result_str += "i, ";
                break;

            case 'I':
                result_str += "I, ";
                break;

            case 'j': 
                result_str += "j, ";
                break;

            case 'J':
                result_str += "J, ";
                break;

            case 'k': 
                result_str += "k, ";
                break;

            case 'K':
                result_str += "K, ";
                break;

            case 'l': 
                result_str += "l, ";
                break;

            case 'L':
                result_str += "L, ";
                break;

            case 'm': 
                result_str += "m, ";
                break;

            case 'M':
                result_str += "M, ";
                break;

            case 'n': 
                result_str += "n, ";
                break;

            case 'N':
                result_str += "N, ";
                break;

            case 'o': 
                result_str += "o, ";
                break;

            case 'O':
                result_str += "O, ";
                break;

            case 'p': 
                result_str += "p, ";
                break;

            case 'P':
                result_str += "P, ";
                break;

            case 'q': 
                result_str += "q, ";
                break;

            case 'Q':
                result_str += "Q, ";
                break;

            case 'r': 
                result_str += "r, ";
                break;

            case 'R':
                result_str += "R, ";
                break;

            case 's': 
                result_str += "s, ";
                break;

            case 'S':
                result_str += "S, ";
                break;

            case 't': 
                result_str += "t, ";
                break;

            case 'T':
                result_str += "T, ";
                break;

            case 'u': 
                result_str += "u, ";
                break;

            case 'U':
                result_str += "U, ";
                break;

            case 'v': 
                result_str += "v, ";
                break;

            case 'V':
                result_str += "V, ";
                break;

            case 'w': 
                result_str += "w, ";
                break;

            case 'W':
                result_str += "W, ";
                break;

            case 'x':
                result_str += "x, ";
                break;

            case 'X':
                result_str += "X, ";
                break;

            case 'y': 
                result_str += "y, ";
                break;

            case 'Y':
                result_str += "Y, ";
                break;

            case 'z': 
                result_str += "z, ";
                break;

            case 'Z':
                result_str += "Z, ";
                break;
            }

        }

    }

    return result_str;

}

Here is my cpp file code:这是我的cpp文件代码:

#include "Helper.h"
#include <iostream>

std::vector<float> nums{ 2.4, 65.2, 56.3, 4.6 };

int main() {

    std::cout << convertToString(nums);

}

Well you are using a float vector, so when compiler compiles the code it replaces the template version with float version so the line switch (s) is using float in a switch statement, as for solution here is a simplified version using string streams好吧,您使用的是浮点向量,因此当编译器编译代码时,它会将模板版本替换为浮点版本,因此行switch (s)在开关语句中使用浮点数,至于解决方案,这里是使用字符串流的简化版本

#include <string>
#include <vector>
#include <iostream>
#include <sstream>

std::vector<float> nums{2.4, 65.2, 56.3, 4.6};
std::vector<bool> b{true, false, false};
std::vector<int> i{1,2,3,4,5};
//Converts a vector of any type into a string like this: 2, 5, 6, 3, (Yes the comma stays at the end like that. That can be fixed but it will require huge amounts of code)
template <typename K>
std::string convertToString(std::vector<K> &V)
{
    std::string result_str{""};
    for (auto s : V)
    {
            std::stringstream converter;
            converter << std::boolalpha << s; 
            result_str += converter.str() + ", ";

    }
    return result_str;
}

int main()
{
    std::cout<< convertToString(b)<<std::endl;
    std::cout<< convertToString(nums)<<std::endl;
    std::cout<< convertToString(i)<<std::endl;
}

you can follow up with a substring operation to remove the last comma if needed.如果需要,您可以执行 substring 操作以删除最后一个逗号。

I think the compiler checks the switch expr during compilation.我认为编译器在编译期间会检查 switch expr。 Maybe you could use some string methods to do this, just like that也许你可以使用一些字符串方法来做到这一点,就像那样
else if (std::is_same<K, char>::value) { result_str.push_back(s); }

else if (std::is_same<K, int>::value) { result_str.append(std::to_string(s)); }

I think you're over-complicating things.我认为你把事情复杂化了。 You can leverage std::to_string and the type trait checkers to do most of the work:您可以利用std::to_string和类型特征检查器来完成大部分工作:

#include <string>
#include <type_traits>
#include <vector>

template<typename K>
std::string convertToString_helper(K s) {
    //Test from most specific to least to prevent bool and char being converted incorrectly.
    if constexpr(std::is_same_v<K, bool>) {
        return s ? std::string{"true"} : std::string{"false"};
    } else if constexpr(std::is_same_v<K, char>) {
        return std::string{s};
    } else if constexpr(std::is_integral_v<K> || std::is_floating_point_v<K>) {
        return std::to_string(s);
    } else if constexpr(std::is_convertible_v<K, std::string>) {
        return s;
    } else {
        return "Not convertible to a string";
    }
}

template<typename K>
std::string convertToString(std::vector<K>& V) {
    std::string result{};
    for(auto iter = std::cbegin(V); iter != std::cend(V) - 1; ++iter) {
        result += convertToString_helper(*iter) + ", ";
    }
    auto last_iter = std::cend(V) - 1;
    result += convertToString_helper(*last_iter);
    return result;
}

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

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