C++详解非类型模板参数Nontype与Template及Parameters的使用

2022-07-14,,,,

类型模板参数

前一章使用的例子 stack 使用的是标准库中的容器管理元素,也可以使用固定大小的 std::array,它的优势是内存管理开销更小,数组的大小可以交给用户指定。

#include <array>
#include <cassert>
template<typename t, std::size_t maxsize>
class stack {
  private:
    std::array<t,maxsize> elems; // elements
    std::size_t numelems; // current number of elements
  public:
    stack(); // constructor
    void push(t const& elem); // push element
    void pop(); // pop element
    t const& top() const; // return top element
    bool empty() const {  // return whether the stack is empty
      return numelems == 0;
    }
    std::size_t size() const { // return current number of elements
      return numelems;
    }
};
template<typename t, std::size_t maxsize>
stack<t,maxsize>::stack ()
 : numelems(0) // start with no elements
{
  // nothing else to do
}
template<typename t, std::size_t maxsize>
void stack<t,maxsize>::push (t const& elem)
{
  assert(numelems < maxsize);
  elems[numelems] = elem; // append element
  ++numelems; // increment number of elements
}
template<typename t, std::size_t maxsize>
void stack<t,maxsize>::pop ()
{
  assert(!elems.empty());
  --numelems; // decrement number of elements
}
template<typename t, std::size_t maxsize>
t const& stack<t,maxsize>::top () const
{
  assert(!elems.empty());
  return elems[numelems-1]; // return last element
}
int main()
{
  stack<int,20> int20stack; // stack of up to 20 ints
  stack<int,40> int40stack; // stack of up to 40 ints
  stack<std::string,40> stringstack; // stack of up to 40 strings
  // manipulate stack of up to 20 ints
  int20stack.push(7);
  std::cout << int20stack.top() << '\n';
  int20stack.pop();
  // manipulate stack of up to 40 strings
  stringstack.push("hello");
  std::cout << stringstack.top() << '\n';
  stringstack.pop();
}

使用该模板需要同时指定类型和个数。 maxsize 用于指定 std::array 的大小。非类型模板参数也可以有默认值。

template<typename t = int, std::size_t maxsize = 100>
class stack {
  ...
};

非类型函数模板参数

也可以为函数定义非类型模板参数。

template<int val, typename t>
t addvalue (t x)
{
  return x + val;
}
std::transform (source.begin(), source.end(), // start and end of source
                dest.begin(), // start of destination
                addvalue<5,int>); // operation

也可以指定一个模板参数,由该参数之前的参数推断出其类型。

template<auto val, typename t = decltype(val)>
t foo();

或者保证传值的类型和指定的类型相同。

template<typename t, t val = t{}>
t bar();

非类型模板参数的限制

需要注意的是,非类型模板参数有一定的限制。一般地,非类型模板参数可以是整形(包括枚举)、指向对象/函数/成员的指针、对象/函数的左值引用或空指针类型 std::nullptr_t

浮点数和类类型对象不可以作为非类型模板参数。

template<double vat>        // error: floating-point values are not
double process (double v)   // allowed as template parameters
{
  return v * vat;
}
template<std::string name>  // error: class-type objects are not
class myclass {             // allowed as template parameters
  ...
};

当使用指针或引用作为非类型模板参数时,不能用字符串字面值、临时对象、数据成员或其他子对象作模板实参。

template<char const* name>
class myclass {
  ...
};
myclass<"hello"> x; // error: string literal "hello" not allowed

c++版本逐渐放宽了限制。c+11 之前,对象必须有外部链接;c++17 之前对象必须有外部或内部链接;c++17 放开了此限制。

extern char const s03[] = "hi"; // external linkage
char const s11[] = "hi"; // internal linkage
int main()
{
  myclass<s03> m03; // ok (all versions)
  myclass<s11> m11; // ok since c++11
  static char const s17[] = "hi"; // no linkage
  myclass<s17> m17; // ok since c++17
}

非类型模板参数的实参可能是任何编译期表达式。

template<int i, bool b>
class c;
...
c<sizeof(int) + 4, sizeof(int)==4> c;

当表达式中使用了大于号,需要将整个表达式用小括号括起来。

c<42, sizeof(int) > 4> c; // error: first > ends the template argument list
c<42, (sizeof(int) > 4)> c; // ok

非类型模板参数 auto

从 c++17 开始, 可以将非类型模板参数定义为 auto,以接收任何允许作为非类型模板参数的类型。

#include <array>
#include <cassert>
template<typename t, auto maxsize>
class stack {
  public:
    using size_type = decltype(maxsize);
  private:
    std::array<t,maxsize> elems; // elements
    size_type numelems; // current number of elements
  public:
	stack();  // constructor
	void push(t const& elem); // push element
	void pop(); // pop element
	t const& top() const; // return top element
	bool empty() const {  // return whether the stack is empty
	  return numelems == 0;
	}
	size_type size() const { // return current number of elements
	  return numelems;
	}
};
// constructor
template<typename t, auto maxsize>
stack<t,maxsize>::stack ()
 : numelems(0) // start with no elements
{
  // nothing else to do
}
template<typename t, auto maxsize>
void stack<t,maxsize>::push (t const& elem)
{
  assert(numelems < maxsize);
  elems[numelems] = elem; // append element
  ++numelems; // increment number of elements
}
template<typename t, auto maxsize>
void stack<t,maxsize>::pop ()
{
  assert(!elems.empty());
  --numelems; // decrement number of elements
}
template<typename t, auto maxsize>
t const& stack<t,maxsize>::top () const
{
  assert(!elems.empty());
  return elems[numelems-1]; // return last element
}

从 c++14 开始,已经支持使用 auto 作为函数返回值。因此成员函数 size() 可以简写为:

auto size() const { // return current number of elements
  return numelems;
}

上述模板的使用:

int main()
{
  stack<int,20u> int20stack; // stack of up to 20 ints
  stack<std::string, 40> stringstack; // stack of up to 40 strings
  // manipulate stack of up to 20 ints
  int20stack.push(7);
  std::cout << int20stack.top() << '\n';
  auto size1 = int20stack.size();
  stringstack.push("hello");
  std::cout << stringstack.top() << '\n';
  auto size2 = stringstack.size();
  if (!std::is_same_v<decltype(size1), decltype(size2)>) {
    std::cout << "size types differ" << '\n';
  }
}

前面说过,非类型模板参数 auto 接收任何允许作为非类型模板参数的类型。

#include <iostream>
template<auto t> // take value of any possible nontype parameter (since c++17)
class message {
  public:
   void print() {
     std::cout << t << '\n';
   }
};
int main()
{
  message<42> msg1;
  msg1.print(); // initialize with int 42 and print that value:42
  static char const s[] = "hello";
  message<s> msg2; // initialize with char const[6] "hello"
  msg2.print(); // and print that value:hello
}

非类型模板 auto 的参数仍不能是浮点数。

stack<int,3.14> sd; // error: floating-point nontype argument

使用 decltype(auto) 指定非类型模板参数的类型也是可以的。

template<decltype(auto) n>
class c {
  ...
};
int i;
c<(i)> x; // n is int&

参考 http://www.tmplbook.com

到此这篇关于c++详解非类型模板参数nontype与template及parameters的使用的文章就介绍到这了,更多相关c++非类型模板参数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《C++详解非类型模板参数Nontype与Template及Parameters的使用.doc》

下载本文的Word格式文档,以方便收藏与打印。