首页 > 解决方案 > cpp 函数,根据模板类型返回值

问题描述

我想将以下伪代码转换为 c++17 代码:

template<class T>
char* foo(){
    if(T is a float) return "we have a float"
    if(T is a int) return "we have a int"
    if(T is a double) return "we have a double"
    return "unknown"
}

这样我就可以像使用它一样

LOGD("%s", foo<float>());
LOGD("%s" foo<double>());

那可能吗 ?

标签: c++templatesc++17typename

解决方案


您可以使用std::is_same来检查类型,并且由于您提到了 C++17,因此您可以使用constexpr if,它在编译时检查条件,并根据结果将丢弃语句真/假。

template<class T>
const char* foo(){
    if constexpr (std::is_same_v<T, float>) return "we have a float";
    else if constexpr (std::is_same_v<T, int>) return "we have a int";
    else if constexpr (std::is_same_v<T, double>) return "we have a double";
    else return "unknown";
}

在 C++17 之前,您还可以使用原始版本 if,并且将在运行时检查条件。

顺便说一句:c 风格的字符串文字的类型为const char[],自 C++11 以来无法转换char*,因此最好将返回类型更改为const char*.


推荐阅读