c++ - 引用模板参数的用途

标签 c++ templates

您可以使用对全局对象的引用作为模板参数。比如这样:

class A {};

template<A& x>
void fun()
{
}

A alpha;

int main()
{
    fun<alpha>();
}

在什么情况下引用模板参数可能有用?

最佳答案

一个场景可能是一个强类型定义,其身份标记不应该是整数类型,而是一个字符串,以便在序列化内容时使用。然后,您可以利用空基类优化来消除派生类型的任何额外空间需求。

例子:

// 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/

相关文章:

c++ - 不能在 double 上使用模数?

c++ - 从第一类型的第二个非类型参数推导第一类型

c++ - 模板成员函数签名与非模板成员函数签名冲突

c++ - 有什么方法可以避免或允许在此线相交算法中除以零?

C++、ANTLR 和 VECTORS

c++ - 函数指针和回调函数定义示例

c++ - 如何在Leonardo堆中找到root的左子节点和右子节点?

c++11 可变参数模板编译失败

模板类的 C++11 std::vector 在构造函数中带有参数

C++11 模板 : How to ensure that the type inherits a class?