gcc 11.2 似乎无法编译这个:
template <typename T = int>
struct Test {};
template <typename T> void foo(T& bar) {}
int main()
{
Test t;
foo<Test>(t);
}
Run Code Online (Sandbox Code Playgroud)
但没有问题
template <typename T = int>
struct Test {};
template <typename T> void foo(T& bar) {}
int main()
{
Test t;
foo<Test<>>(t);
}
Run Code Online (Sandbox Code Playgroud)
这是编译器错误吗?
这个问题似乎表明它应该有效。
当第一个模板参数不是 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 …Run Code Online (Sandbox Code Playgroud)