C++检测类型是否为字符串对象

标签 c++ templates c++17 typetraits

有点奇怪。我正在尝试编写一个代码来检测一个类型是否是一个字符串对象。 char * 或其他对象类型应该导致 false 而不是 true。下面的代码给我:

error: template parameters not deducible in partial specialization:

我不明白消息的意思。即使在线搜索,我也不知道如何解决这个问题:

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

template <typename T>
struct is_string : std::false_type { };

template <typename T>
struct is_string<std::string> : std::true_type<T> { };

class Temp
{
  int a;
};

int main()
{
    // Expect: false
    std::cout << is_string<int>::value << std::endl;
    std::cout << is_string<char *>::value << std::endl;
    std::cout << is_string<Temp>::value << std::endl;

    // Expect: true
    std::cout << is_string<std::string>::value << std::endl;
    std::cout << is_string<const std::string>::value << std::endl;
    std::cout << is_string<std::string&>::value << std::endl;
}

如果有开箱即用的 std 工具,那是欢迎的

最佳答案

模板特化应如下所示:

template <>
struct is_string<std::string> : std::true_type { };

但即使你使用它,你的模板也会返回 false简历合格 string或对其的引用。

I did not use std::is_same because it rejects types such as const string or string & as string.

正确的做法是std::is_same_v<std::remove_cv_t<std::remove_reference_t< <强> your_type >>, std::string> (或使用 std::decay_t ,如其他答案所建议的那样)。

或者,在 C++20 中:std::is_same_v<std::remove_cvref_t<< <强> your_type >, std::string> .

关于C++检测类型是否为字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929056/

相关文章:

c++ - 多态性 : non-templated base with templated derived class, 使用基指针

c++ - Arduino 在启动时自动运行代码

c++ - 我们可以有一个具有多种返回类型的函数吗? (C++11 及以上版本)

c++ - 使用 std::type_info 在 natvis 中进行转换

c++ - 使用基于签名的技术编写防病毒软件

c++ - 模板中关键字 'typename' 和 'class' 的区别?

c++ - ADL 相关的 GCC 4.7.2 问题与表达式 SFINAE

c++ - 'inline' 变量可以像内联函数一样内联吗?

c++ - 使用&符号后跟下划线命名的变量是什么意思?

java - 归并排序的开放区间的中点