【问题标题】:What is the function in type_traits to check if the type is const char*?type_traits 中检查类型是否为 const char* 的函数是什么?
【发布时间】:2020-08-19 08:25:42
【问题描述】:

我需要创建一个模板函数 myPrintf 来检查给定字符串中 %d %f %s 的类型是否正确。

我找到了这两个

std::is_integral_v<T> 
std::is_floating_point<T> 

但我不知道如何检查给定参数是否为 const char*

有人知道吗?

谢谢

【问题讨论】:

标签: c++ c++17


【解决方案1】:

您可以使用std::is_same_v 检查类型是否完全匹配。例如:

template <typename T>
void foo(const T &t) {
    if constexpr (std::is_same_v<const char*, T>) {
        // do something here
    }
}

注意:std::is_same&lt;A, B&gt;::value等价于std::is_same_v&lt;A, B&gt;

【讨论】:

    猜你喜欢
    • 2011-08-14
    • 2018-01-06
    • 2012-07-21
    • 2015-12-12
    • 1970-01-01
    • 2011-08-25
    • 2016-02-14
    • 2020-12-01
    • 2011-10-24
    相关资源
    最近更新 更多