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

问题描述 投票:0回答:2

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

错误:无法通过局部专业化推导模板参数:

我不明白该消息的含义。即使在网上搜索,我也不知道如何解决此问题:

#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工具,欢迎使用

c++ templates c++17 typetraits
2个回答
6
投票

模板专业化应如下所示:

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

但是,即使您使用它,您的模板也会为符合cv的false或对其引用返回string。>>

我没有使用std::is_same,因为它拒绝将const stringstring &之类的类型作为字符串。

正确的方法是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>

1
投票

“ Typo”用专业化语法,应该是:

© www.soinside.com 2019 - 2024. All rights reserved.