如何在 C++ 中以编程方式检查字符串类型

roh*_*itt 0 c++ templates c++17

如何检查字符串是否为 typestd::string或 is of type const char*

template<typename B>
B check(B b)
{
    //
}
Run Code Online (Sandbox Code Playgroud)

check可能用 astd::string或 a调用const char*
我不知道如何推断返回类型。如何确定它应该是std::string还是const char*

Enr*_*lis 5

正如我在评论中所写的那样,如果您只需要处理const char *并且std::string可能使用模板是多余的。

但是,如果您真的想这样做,可以使用if constexpr

#include <iostream>
#include <string>
#include <type_traits>

template<typename B>
B check(B b)
{
    if constexpr (std::is_same_v<B, std::string>) {
        std::cout << "std::string" << std::endl;
        return b;
    } else if constexpr (std::is_same_v<B, const char*>) {
        std::cout << "const char *" << std::endl;
        return b;
    } else {
        throw; // obviously you might want do to something different
    }
}

int main() {
    check("ciao");
    check(std::string{"ciao"});
    check(1); // throws
}
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望在使用静态断言之前进行保护if constexpr

template<typename B>
B check(B b)
{
    static_assert(std::is_convertible_v<const char *, B>); // just an idea
    if constexpr (std::is_same_v<B, std::string>) {
        std::cout << "std::string" << std::endl;
        return b;
    }
    else if constexpr (std::is_same_v<B, const char*>) {
        std::cout << "const char *" << std::endl;
        return b;
    } else {
        std::cout << "other type convertible from `const char *`" << std::endl;
    }

}

int main() {
    check("ciao");
    check(std::string{"ciao"});
    //check(1); // fails at compile time
}
Run Code Online (Sandbox Code Playgroud)