标签: default-template-argument

模板函数中的默认模板需要空尖括号 <>

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)

这是编译器错误吗?

这个问题似乎表明它应该有效。

c++ templates function-templates default-template-argument

3
推荐指数
1
解决办法
377
查看次数

部分模板特化:模板参数 X 无效

当第一个模板参数不是 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)

c++ template-specialization c++17 default-template-argument

0
推荐指数
1
解决办法
106
查看次数