ar2*_*015 1 c++ templates type-traits c++17
这有点奇怪。我正在尝试编写一个代码来检测类型是否为字符串对象。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;
}
Run Code Online (Sandbox Code Playgroud)
如果有开箱std即用的工具,那是受欢迎的
模板特化应如下所示:
template <>
struct is_string<std::string> : std::true_type { };
Run Code Online (Sandbox Code Playgroud)
但即使你使用它,你的模板也会返回falsecv-qualifiedstring或对它的引用。
我没有使用,
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>
| 归档时间: |
|
| 查看次数: |
263 次 |
| 最近记录: |