template<auto x>
using constant = std::integral_constant< std::decay_t<decltype(x)>, x >
模板
using constant = std::integral_constant< std::decay_t<decltype(x)>, x >;
constexpr int digit_val( char c ) {
if (c >= '0' && c <='9')
return c-'0';
else if (c >= 'A' && c <= 'Z')
return c-'A'+10;
else if (c >= 'a' && c <= 'z')
return c-'a'+10;
else
throw nullptr;
}
constexpr long long ce_pow( int base, int count, long long acc=1 ){
if (!count) return acc;
return ce_pow( base, count-1, acc*(long long)base );
}
constexpr long long from_digits( long long acc, int base ){
return acc;
}
template<int I, int...Is>
constexpr long long from_digits( long long acc, int base, constant<I>, constant<Is>... ) {
return from_digits( acc+ce_pow(base, sizeof...(Is))*(long long)I, base, constant<Is>{}... );
}
template<char...cs>
constexpr long long val( constant<'0'>, constant<'x'>, constant<cs>... ){
return from_digits( 0, 16, constant<digit_val(cs)>{}... );
}
template<char...cs>
constexpr long long val( constant<'0'>, constant<'b'>, constant<cs>... ){
return from_digits( 0, 2, constant<digit_val(cs)>{}... );
}
template<char...cs>
constexpr long long val( constant<'0'>, constant<cs>... ){
return from_digits( 0, 8, constant<digit_val(cs)>{}... );
}
template<char...cs>
constexpr auto operator""_k(){
return constant< val( constant<cs>{}... ) >{};
}
或类似的。现在:
template<int I>
int bar(constant<I>)
{
return (I);
}
应该与 bar(5_k);
一起使用。我可能会有一些打字错误,而花哨的 auto
constant
模板可能会阻止推导,缺少对 0X
和 0B
的支持。但除此之外就没问题了。
基于循环的替代实现:
struct number_format {
int prefix = 0;
int base = 0;
};
template<char...cs>
constexpr number_format get_format( constant<'0'>, constant<'x'>, constant<cs>... ) {
return {2,16};
}
template<char...cs>
constexpr number_format get_format( constant<'0'>, constant<'X'>, constant<cs>... ) {
return {2,16};
}
template<char...cs>
constexpr number_format get_format( constant<'0'>, constant<'b'>, constant<cs>... ) {
return {2,2};
}
template<char...cs>
constexpr number_format get_format( constant<'0'>, constant<'B'>, constant<cs>... ) {
return {2,2};
}
template<char...cs>
constexpr number_format get_format( constant<'0'>, constant<cs>... ) {
return {1,8};
}
template<char...cs>
constexpr number_format get_format( constant<cs>... ) {
return {0,10};
}
template<char...Cs>
constexpr long long val( constant<Cs>...cs ){
char buff[] = {Cs...};
constexpr number_format fmt = get_format( cs... );
long long r = 0;
for (auto it = std::begin(buff)+fmt.prefix; it != std::end(buff); ++it) {
r *= fmt.base;
r += digit_val(*it);
}
return r;
}
template<char...cs>
constexpr auto operator""_k(){
return constant< val( constant<cs>{}... ) >{};
}
live examples.
template<int X> int bar(const int x = X) { ... }
- Some programmer dudeconstexpr
参数。但是,非类型模板参数始终是常量表达式。因此,能够调用(可能是constexpr
函数的参数,它可以视为constexpr
)将是有用的。在我们获得真正的constexpr
参数之前,您必须使用模板参数找到解决方法。 - Nicol Bolas<X>
语法之外。如果是常量表达式,只使用模板?或者将整个函数设为constexpr
并传递一个常量表达式参数(如果可能的话)? - Some programmer dude