Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template argument which is already "known"

Tags:

c++

templates

This question may be a well answered one but unfortunately I don't know the correct terminology to ask it properly, so...

template <class _Cp, bool _IsConst, typename _Cp::__storage_type = 0> class __bit_iterator;

Could someone explain the last template argument here? The only thing I can infer is that if the parameter specified for _Cp has a sub-type __storage_type then any use of _Cp::__storage_type in the template will resolve to that. If it doesn't then does that mean _Cp::__storage_type resolves to 0? This seems really perverse to me (or likely wrong after a bit of experimentation).

Explanation along with correct terminology and C++ reference would be appreicated.

For interest, this code was pulled from libc++.

like image 616
Andrew Parker Avatar asked Apr 09 '15 11:04

Andrew Parker


2 Answers

The class template __bit_iterator takes three arguments:

  • a class _Cp
  • a boolean _IsConst
  • an object of type _Cp::__storage_type (presumably an integer) that is given no name
    • this argument is optional and defaults to the expression 0

The purpose of the third argument (since it is unnamed and thus cannot be used inside the definition of __bit_iterator) appears to be only to require that the class _Cp has a member type __storage_type that is compatible with the expression 0. If it does not, that instantiation (with that _Cp), cannot compile.

like image 79
Lightness Races in Orbit Avatar answered Sep 27 '22 22:09

Lightness Races in Orbit


template <class _Cp, bool _IsConst, typename _Cp::__storage_type = 0>
class __bit_iterator;

__bit_iterator is a class template. This template takes three arguments.

  1. _Cp, which is a type.

  2. _IsConst, which is a boolean value.

  3. The last parameter is unnamed and is a value (just like _IsConst). Type of this parameter is type/typedef declared in _Cp and named __storage_type.

If you are confused by typename keyword: typename is a method for indicating that a dependent name is a type.

_Cp is template argument and can be any type. Even a type, that doesn't contain anything like __storage_type. That's why we must tell compiler, that such thing should exist there and is a type/typedef. If this requirement is not fulfilled, compile-time error will be raised.

like image 42
Mateusz Grzejek Avatar answered Sep 27 '22 21:09

Mateusz Grzejek