Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking uniqueness of characters at compile time

Is it possible in C++11 (not later) to write a function that verifies the uniqueness of characters passed to it at compile time

verify('a');
verify('b');
verify('c');
verify('a');  //should cause compilation error

[Edit by MK to answer some questions]:

  • The calls are always in the same scope, right one after the other like above.
  • A macro solution would be acceptable too
  • Non-type template parameters are acceptable too
like image 511
MK. Avatar asked Jan 30 '18 22:01

MK.


2 Answers

Not exactly what you asked for, but given your constraints (same scope and macro solution is acceptable) you can try something like this:

#define verify(x) class _tmp_##x {};

Example:

int main()
{
    verify(a);
    verify(b);
    verify(a);
    return 0;
}

Will fail compilation due to redefinition of local class _tmp_a.

like image 186
Patryk Obara Avatar answered Nov 05 '22 08:11

Patryk Obara


template<std::size_t X>
struct line_t { enum{value=X}; constexpr line_t(){} };

template<std::size_t line, char c>
constexpr std::integral_constant<bool, false> use_flag(
  std::integral_constant<char,c>, line_t<line>
) { return {}; }

#define FLAG_USE( C ) \
constexpr std::integral_constant<bool, true> use_flag( \
  std::integral_constant<char,C>, line_t<__LINE__> \
) { return {}; }

template<char c, std::size_t line>
constexpr std::size_t count_uses( line_t<line> from, line_t<1> length ){
  return use_flag( std::integral_constant<char, c>{}, from )();
}
template<char c, std::size_t line>
constexpr std::size_t count_uses( line_t<line> from, line_t<0> length ){
  return 0;
}

template<char c, std::size_t f, std::size_t l>
constexpr std::size_t count_uses(line_t<f> from, line_t<l> length ){
  return count_uses<c>( from, line_t< l/2 >{} )+ count_uses<c>( line_t< f+l/2>{}, line_t<(l+1)/2>{} );
}

#define UNIQUE(C) \
  FLAG_USE(C) \
  static_assert( count_uses<C>( line_t<0>{}, line_t<__LINE__+1>{} )==1, "too many" )

This should work in files of size 2^100s, until your compiler runs out of memory, as counting is log-depth recursion.

The type line_t enables deferred ADL lookup of use_flag until we invoke count_uses. We do a binary tree sum over every overload of use_flag, one per line per character in the file.

Live example.

like image 8
Yakk - Adam Nevraumont Avatar answered Nov 05 '22 07:11

Yakk - Adam Nevraumont