aer*_*fly 6 templates compile-time-constant compile-time constexpr c++11
在我们的项目中,我们使用printf兼容函数将消息添加到外部日志文件中.我们可以写
__LOG_INFO( "number of files = %d\n", number_of_files );
__LOG_INFO( "Just for information\n" );
Run Code Online (Sandbox Code Playgroud)
函数声明__LOG_INFO看起来像这样
template<int N>
inline void __LOG_INFO( const char (&fmt)[N] )
{
call_printf( MODULE_NAME, fmt, debug_parameters() );
}
template<int N, typename T1>
static void __LOG_INFO( const char (&fmt)[N], const T1 &t1 )
{
call_printf( MODULE_NAME, fmt, debug_parameters( t1 ) );
}
template<int N, typename T1, typename T2>
static void __LOG_INFO( const char (&fmt)[N], const T1 &t1, const T2 &t2 )
{
call_printf( MODULE_NAME, fmt, debug_parameters( t1, t2 ) );
}
...
Run Code Online (Sandbox Code Playgroud)
我们现在想要使用C++ 11 constexpr功能添加一些简单的编译时格式字符串检查,例如,对我们具有此功能的格式字符串中的参数数量进行非常简单的检查
template<int N>
constexpr static int count_arguments( const char (&fmt)[N], int pos = 0, int num_arguments = 0 )
{
return pos >= N-2 ? num_arguments :
fmt[pos] == '%' && fmt[pos+1] != '%' ? count_arguments( fmt, pos+1, num_arguments+1 ) :
count_arguments( fmt, pos+1, num_arguments );
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是我们不能在__LOG_INFO函数本身中添加类似static_assert的东西,因为编译器抱怨fmt不是一个整数常量.所以现在我们有这个丑陋的宏观解决方案:
#define COUNT_ARGS(...) COUNT_ARGS_(,##__VA_ARGS__,8,7,6,5,4,3,2,1,0)
#define COUNT_ARGS_(z,a,b,c,d,e,f,g,h,cnt,...) cnt
#define LOG_INFO(a, ...) \
{ \
static_assert( count_arguments(a)==COUNT_ARGS(__VA_ARGS__), "wrong number of arguments in format string" ); \
__LOG_INFO(a,##__VA_ARGS__); \
}
Run Code Online (Sandbox Code Playgroud)
因此,不必打电话__LOG_INFO,而是打电话LOG_INFO.
除了使用上面的那些宏之外还有更好的解决方案吗?
我正在编写一个编译时格式的字符串库,在此期间我遇到了类似的问题.所以我会在这里分享我的发现.
主要问题是,constexpr函数在C++中定义为在编译时和运行时都可调用.以下示例无效,因为F必须能够从运行时上下文中调用.
/* Invalid constexpr function */
constexpr int F(int x) { static_assert(x == 42, ""); return x; }
/* Compile-time context */
static_assert(F(42) == 42, "");
/* Runtime context */
void G(int y) { F(y); } // The way F is defined, this can't ever be valid.
Run Code Online (Sandbox Code Playgroud)
如果参数的类型是允许作为模板参数的类型,但解决方案很简单,我们只需将其传递给模板参数.但是如果不是这样,你可以将constexpr表达式的-ness包含在一个带有lambda的任意作用域中的类中.
constexpr 参数/* Simply counts the number of xs, using C++14. */
static constexpr std::size_t count_xs(const char *fmt, std::size_t n) {
std::size_t result = 0;
for (std::size_t i = 0; i < n; ++i) {
if (fmt[i] == 'x') {
++result;
} // if
} // for
return result;
}
template <typename StrLiteral, typename... Args>
constexpr void F(StrLiteral fmt, Args &&... args) {
static_assert(count_xs(fmt, fmt.size()) == sizeof...(Args), "");
}
int main() {
F([]() {
class StrLiteral {
private:
static constexpr decltype(auto) get() { return "x:x:x"; }
public:
static constexpr const char *data() { return get(); }
static constexpr std::size_t size() { return sizeof(get()) - 1; }
constexpr operator const char *() { return data(); }
};
return StrLiteral();
}(), 0, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)
呼叫站点很荒谬.尽管我讨厌宏,但我们可以用它来清理一下.
#define STR_LITERAL(str_literal) \
[]() { \
class StrLiteral { \
private: \
static constexpr decltype(auto) get() { return str_literal; } \
public: \
static constexpr const char *data() { return get(); } \
static constexpr std::size_t size() { return sizeof(get()) - 1; } \
constexpr operator const char *() { return data(); } \
}; \
return StrLiteral(); \
}()
int main() {
F(STR_LITERAL("x:x:x"), 0, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)
通常,我们可以使用这种constexpr在static constexpr函数中包装表达式的技术,constexpr通过函数参数保留其性能.但请注意,这可能F会导致编译时间停止,因为即使我们使用等效的字符串调用它,每次调用都会导致不同的模板实例化.
我们不是为每次调用实例化不同的模板F,而是为了使相同的格式字符串重用相同的实例.
template <char... Cs>
class Format {
private:
static constexpr const char data_[] = {Cs..., '\0'};
public:
static constexpr const char *data() { return data_; }
static constexpr std::size_t size() { return sizeof(data_) - 1; }
constexpr operator const char *() { return data(); }
};
template <char... Cs>
constexpr const char Format<Cs...>::data_[];
template <char... Cs, typename... Args>
constexpr void F(Format<Cs...> fmt, Args &&... args) {
static_assert(count_xs(fmt, fmt.size()) == sizeof...(Args), "");
}
int main() {
F(Format<'x', ':', 'x', ':', 'x'>(), 0, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)
Welp,让我们使用另一个宏来使Format建筑"更好".
template <typename StrLiteral, std::size_t... Is>
constexpr auto MakeFormat(StrLiteral str_literal,
std::index_sequence<Is...>) {
return Format<str_literal[Is]...>();
}
#define FMT(fmt) \
MakeFormat(STR_LITERAL(fmt), std::make_index_sequence<sizeof(fmt) - 1>())
int main() {
F(FMT("x:x:x"), 0, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
1236 次 |
| 最近记录: |