您可以将对全局对象的引用用作模板参数。例如:
class A {};
template<A& x>
void fun()
{
}
A alpha;
int main()
{
fun<alpha>();
}
在什么情况下引用模板参数可能有用?
最佳答案
一种情况可能是带有身份 token 的强类型定义,该身份 token 不应该是整数类型,而应该是一个字符串,以方便序列化填充时使用。然后,您可以利用空的基类优化来消除派生类型具有的任何其他空间要求。
例:
// File: id.h
#pragma once
#include <iosfwd>
#include <string_view>
template<const std::string_view& value>
class Id {
// Some functionality, using the non-type template parameter...
// (with an int parameter, we would have some ugly branching here)
friend std::ostream& operator <<(std::ostream& os, const Id& d)
{
return os << value;
}
// Prevent UB through non-virtual dtor deletion:
protected:
~Id() = default;
};
inline const std::string_view str1{"Some string"};
inline const std::string_view str2{"Another strinng"};
在某些翻译单元中:
#include <iostream>
#include "id.h"
// This type has a string-ish identity encoded in its static type info,
// but its size isn't augmented by the base class:
struct SomeType : public Id<str2> {};
SomeType x;
std::cout << x << "\n";
关于c++ - 引用模板参数的目的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55854416/