MST

星途 面试题库

面试题:C++字符常量与字符串常量在模板元编程中的比较应用

利用C++模板元编程,实现一个编译期的函数,该函数接收一个字符常量和一个字符串常量模板参数,判断该字符常量是否存在于字符串常量中,如果存在返回true,否则返回false。在主函数中通过实例化该模板函数并输出结果来验证正确性。
42.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

template<char c, const char* str>
struct CharInString {
    static constexpr bool value = (str[0] == c) || (str[0] != '\0' && CharInString<c, str + 1>::value);
};

int main() {
    constexpr const char* testStr = "hello";
    std::cout << "Is 'h' in 'hello': " << (CharInString<'h', testStr>::value? "true" : "false") << std::endl;
    std::cout << "Is 'z' in 'hello': " << (CharInString<'z', testStr>::value? "true" : "false") << std::endl;
    return 0;
}
  1. 模板类 CharInString
    • 它是一个模板类,接收一个字符常量 c 和一个字符串常量 str 作为模板参数。
    • value 是一个 constexpr 静态成员变量,用于存储判断结果。如果当前字符 str[0] 等于目标字符 c,则返回 true,否则如果当前字符不是字符串结束符 '\0',则递归检查下一个字符,即 CharInString<c, str + 1>::value
  2. main 函数
    • 定义了一个字符串常量 testStr
    • 通过实例化 CharInString 模板类,并输出结果来验证函数的正确性。对于字符 'h' 应该返回 true,对于字符 'z' 应该返回 false