此模板参数是什么意思?

时间:2020-10-09 15:28:36

标签: c++ templates

对于以下代码,std::uint64_t = 0是什么意思?

template< class T, std::uint64_t = 0 >
struct Dummy {  
   T value;
};

2 个答案:

答案 0 :(得分:5)

这是类型为std::uint64_t的非类型模板参数,默认值为0

请注意,该参数未命名,因此不能直接在Dummy中使用它。

但是,此模板参数仍有多种用途,例如您可以为此参数使用其他值来选择Dummy的特化:

// specialization
template< class T>
struct Dummy<T, 42> {
   // ... 
};

现在Dummy<int>Dummy<int, 0>将使用主要模板,而Dummy<int, 42>将使用部分专业化。这种技术的常见用途之一是一种称为SFINAE的技术。

答案 1 :(得分:3)

@cigien's answer涵盖了该类模板的一般说明:

  • 两个模板参数,其中,
  • 第一个是 type模板参数,其中
  • 第二个未命名 非类型模板参数,其默认参数值0

可能要指出的是,您仍然可以通过将类模板Dummy部分固定在类型模板参数的固定类型上,同时为该模板添加名称来访问未命名的非类型模板参数。仍对其部分专业化进行参数化的非类型模板参数。

#include <cstdint>
#include <iostream>

template< class T, std::uint64_t = 0 >
struct Dummy {
   T value;
};

// Partial specialization where the remaining non-type
// template parameter is given a name which in turn can
// be used within the class template definition blueprint
// for this specialization.
template<std::uint64_t NUM>
struct Dummy<std::uint64_t, NUM> {
    // Use the named non-type template parameter to define
    // a default member initializer for the value member.
    std::uint64_t value{NUM};
};

int main() {
    std::cout 
        << Dummy<std::uint64_t, 42>{}.value  // 42 (<uint64_t, 42> specialization)
        << Dummy<std::uint32_t>{}.value      // 0  (<uint32_t, 0> specialization)
        << Dummy<std::uint32_t, 42>{}.value; // 0  (<uint32_t, 42> specialization)
                             // ^^ - template argument '42' is not used in the 
                             //      primary template (other than encoding the type)
}