gla*_*des 0 c++ template-specialization c++17 default-template-argument
当第一个模板参数不是 POD 类型时,我想部分专门化一个类。这是我想出的:
#include <iostream>
#include <type_traits>
template <typename T, bool = std::is_pod<T>>
struct A
{
void print()
{
std::cout << "POD\n";
}
};
template <typename T>
struct A<T, false>
{
void print()
{
std::cout << "Non-POD\n";
}
};
int main()
{
A<int> a;
A<std::string> c;
a.print();
c.print();
}
Run Code Online (Sandbox Code Playgroud)
然而,这不会编译并产生三种类型的错误(对于字符串大小写重复):
<source>:4:43: error: expected primary-expression before '>' token
4 | template <typename T, bool = std::is_pod<T>>
| ^~
<source>: In function 'int main()':
<source>:24:10: error: template argument 2 is invalid
24 | A<int> a;
| ^ ^
<source>:26:7: error: request for member 'print' in 'a', which is of non-class type 'int'
Run Code Online (Sandbox Code Playgroud)
我该怎么做?我已经尝试命名默认模板参数 (bool = ) 但无济于事。此外,将所有三个参数添加到专用模板列表中也没有帮助。
is_pod<T>本身是一个类类型,无法转换为bool,您应该使用::value它来获取其值
template <typename T, bool = std::is_pod<T>::value>
// ^^^^^
struct A { };
Run Code Online (Sandbox Code Playgroud)
值得注意的是,它is_pod在 C++20 中已被弃用,对于简单数据类型,您应该使用is_standard_layout,对于普通数据类型,您应该使用is_trivial.
请参阅为什么在 C++20 中不推荐使用 std::is_pod?