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]:
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
.
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.
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