Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of reference template arguments

Tags:

c++

templates

You can use a reference to a global object as a template parameter. For example thus:

class A {};  template<A& x> void fun() { }  A alpha;  int main() {     fun<alpha>(); } 

In what situation might a reference template argument be useful?

like image 457
oz1cz Avatar asked Apr 25 '19 17:04

oz1cz


People also ask

What is a template argument?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Why do we use :: template template parameter?

Correct Option: D. It is used to adapt a policy into binary ones.

What is template argument deduction?

Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.

What is the validity of template parameters?

What is the validity of template parameters? Explanation: Template parameters are valid inside a block only i.e. they have block scope.


Video Answer


1 Answers

One scenario could be a strong typedef with an identity token that shouldn't be of integral type, but instead a string for ease of use when serializing stuff. You can then leverage empty base class optimization to eliminate any additional space requirements a derived type has.

Example:

// 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"}; 

And in some translation unit:

#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"; 
like image 84
lubgr Avatar answered Sep 26 '22 00:09

lubgr