1

I have seen in some code the following :

template<const Foo& bar>

I was told its purpose was to handle big structures.

Can't we then use const & directly in the code non-templatized arguments ?
Can it be considered a good practice to pass object references around as arguments using a const reference as template parameter ?

2
  • 3
    Your question is vague as the origin of the universe. What is the context of this code? Non-type template parameters of reference type are really rare and obscure. Commented Apr 24, 2015 at 7:48
  • Reading between the huge gaps in the lines he might be asking whether it's good practice to pass object references around as arguments using a const reference where possible and the answer to that is: "yes it is". Commented Apr 24, 2015 at 7:56

1 Answer 1

2

This is a non-type template parameter, which happens to be of type const Foo&.

Whatever its use there is ("big structures" isn't really that descriptive), like all non-type template parameters its advantage is to be usable at compile-time (for example in metaprograms), its drawback is that you must have its value at compile-time. It being a compile-time constant may also help the compiler optimize it better.

Here are some examples :

struct Foo {};

/////////////////////////////////
// Type template parameter :
template <class T>
struct TypeParame {
    T const &tRef; // T is a type
};

/////////////////////////////////
// Non-type template parameters :

// Integral type
template <int I>
struct NonTypeParam {
    // I is a value
    enum { constant = I };
};

// Reference
template <Foo const &F>
struct RefParam {
    // F is a value again
    Foo const &ref = F;
};

// Pointer
template <Foo const *F>
struct PtrParam {
    // F is still a value
    Foo const *ptr = F;
};

// More are possible, but...

// error: 'struct Foo' is not a valid type for a template non-type parameter
template <Foo F>
struct ValParam {};
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Quentin in your link I can see template<const Y& b> struct Z {}; which correspond to what I have seen sometimes. Can't we have an equivalent with template<Y b> and use the reference elsewhere ?
@coincoin You may be mixing it up with type template parameters, where declaring template <class T> will enable you to then decorate T however you want (e.g T&). With non-type template parameters though, the parameter is the value. So, no.
@coincoin see my edit fo hopefully clearer examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.