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?
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.
Correct Option: D. It is used to adapt a policy into binary ones.
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? Explanation: Template parameters are valid inside a block only i.e. they have block scope.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With