没有名称的 C++ 模板参数

4 c++

我遇到了以下代码片段:

template <typename T, typename = void>
struct test {
  int t = sizeof(T);
};
Run Code Online (Sandbox Code Playgroud)

我知道在typename = void, void 是默认参数,但它没有名称!它有什么用处,它甚至意味着什么?

Nat*_*ica 6

这与SFINAE一起用于专业化。这样做可以让您拥有类似的代码

template <typename T, typename = void>
struct test {
  int t = sizeof(T);
};

template <typename T>
struct test<T, std::enable_if_t<std::is_integral_v<T>>> {
//             ^^  this part "fills in" the void    ^^
  int t = 42;
};

template <typename T>
struct test<T, std::enable_if_t<std::is_floating_point_v<T>>> {
//             ^^     this part "fills in" the void       ^^
  int t = 21;
};

int main()
{
    test<int> i;
    std::cout << i.t << "\n";
    test<double> d;
    std::cout << d.t;
}
Run Code Online (Sandbox Code Playgroud)

哪个输出

42
21
Run Code Online (Sandbox Code Playgroud)

没有typename = void,我们将无法添加这些特化,因为该enable_if_t部件将没有第二个参数可以“填充”。