有点奇怪。我正在尝试编写代码来检测类型是否为字符串对象。 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
工具,欢迎使用
模板专业化应如下所示:
template <>
struct is_string<std::string> : std::true_type { };
但是,即使您使用它,您的模板也会为符合cv的false
或对其引用返回string
。>>
我没有使用
std::is_same
,因为它拒绝将const string
或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>
。“ Typo”用专业化语法,应该是: