Search code examples
c++templatesconstantsiteratorconst-correctness

How do I require const_iterator semantics in a template function signature?


I am creating a constructor that will take a pair of input iterators. I want the method signature to have compile-time const semantics similar to:

DataObject::DataObject(const char *begin, const char *end)

However, I can't find any examples of this. For example, my STL implementation's range constructor for vector is defined as:

template<class InputIterator>
vector::vector(InputIterator first, InputIterator last)
{
    construct(first, last, iterator_category(first));
}

which has no compile-time const guarantees. iterator_category / iterator_traits<> contain nothing relating to const, either.

Is there any way to indicate to guarantee the caller that I can't modify the input data?

edit, 2010-02-03 16:35 UTC

As an example of how I would like to use the function, I would like to be able to pass a pair of char* pointers and know, based on the function signature, that the data they point at will not be modified.
I was hoping I could avoid creating a pair of const char* pointers to guarantee const_iterator semantics. I may be forced to pay the template tax in this case.


Solution

  • You could simply create a dummy function which calls your template with char * const pointers. If your template attempts to modify their targets, then your dummy function will not compile. You can then put said dummy inside #ifndef NDEBUG guards to exclude it from release builds.