有点奇怪。我正在尝试编写一个代码来检测一个类型是否是一个字符串对象。 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 asconst string
orstring &
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/