我目前正在使用__COUNTER__我的C库代码中的宏来生成唯一的整数标识符.它工作得很好,但我看到两个问题:
__COUNTER__可能会混淆.因此,我希望实现与__COUNTER__我自己的等价物.
我所知道的,但替代品并不需要使用:
__LINE__ (因为每行多个宏不会获得唯一ID)BOOST_PP_COUNTER(因为我不想要boost依赖)BOOST_PP_COUNTER证明这可以做到,即使其他答案声称这是不可能的.
本质上,我正在寻找一个头文件"mycounter.h",这样
#include "mycounter.h"
__MYCOUNTER__
__MYCOUNTER__ __MYCOUNTER__
__MYCOUNTER__
Run Code Online (Sandbox Code Playgroud)
将进行预处理gcc -E,以
(...)
0
1 2
3
Run Code Online (Sandbox Code Playgroud)
不使用内置__COUNTER__.
注:此前,这个问题被标记为重复这个,它使用交易__COUNTER__,而不是回避它.
我有一个编译时计数器,我使用多年,受这些答案的启发.它适用于C++ 03/11,就我测试而言,在主要编译器上相对较好:
namespace meta
{
template<unsigned int n> struct Count { char data[n]; };
template<int n> struct ICount : public ICount<n-1> {};
template<> struct ICount<0> {};
#define MAX_COUNT 64
#define MAKE_COUNTER( _tag_ ) \
static ::meta::Count<1> _counter ## _tag_ (::meta::ICount<1>)
#define GET_COUNT( _tag_ ) \
(sizeof(_counter ## _tag_ (::meta::ICount<MAX_COUNT + 1>())) - 1)
#define INC_COUNT( _tag_ ) \
static ::meta::Count<GET_COUNT(_tag_) + 2> _counter ## _tag_ (::meta::ICount<2 + GET_COUNT(_tag_)>)
}
Run Code Online (Sandbox Code Playgroud)
以下测试编译并运行完美(预期输出为0 1 2 3):
struct …Run Code Online (Sandbox Code Playgroud) 我想要一个constexpr可以为每个C ++类型返回唯一ID 的函数,如下所示:
using typeid_t = uintptr_t;
template <typename T>
constexpr typeid_t type_id() noexcept
{
return typeid_t(type_id<T>);
}
int main()
{
::std::cout << ::std::integral_constant<typeid_t, type_id<float>()>{} << ::std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是我得到一个错误:
t.cpp: In function 'int main()':
t.cpp:23:69: error: conversion from pointer type 'typeid_t (*)() noexcept {aka long unsigned int (*)() noexcept}' to arithmetic type 'typeid_t {aka long unsigned int}' in a constant-expression
::std::cout << ::std::integral_constant<typeid_t, type_id<float>()>{} << ::std::endl;
^
t.cpp:23:69: note: in template argument for type 'long unsigned …Run Code Online (Sandbox Code Playgroud) 我有兴趣能够做这样的事情:
void ISR()
{
MEASURE_TIME(counters)
do_something();
MEASURE_TIME(counters)
do_something_else();
MEASURE_TIME(counters)
do_another_thing();
MEASURE_TIME(counters)
do_one_last_thing();
MEASURE_TIME(counters)
}
Run Code Online (Sandbox Code Playgroud)
这会在编译时以某种方式转换为:
void ISR()
{
counters[0] = measure_time();
do_something();
counters[1] = measure_time();
do_something_else();
counters[2] = measure_time();
do_another_thing();
counters[3] = measure_time();
do_one_last_thing();
counters[4] = measure_time();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法使用预处理器(似乎不太可能)或模板来维护和增加整数状态?
我知道我可以这样做:
void ISR()
{
int i = 0;
counters[i++] = measure_time();
do_something();
counters[i++] = measure_time();
do_something_else();
counters[i++] = measure_time();
do_another_thing();
counters[i++] = measure_time();
do_one_last_thing();
counters[i++] = measure_time();
}
Run Code Online (Sandbox Code Playgroud)
但是拥有编译时索引还有一些额外的价值(如果不涉及一些专有细节,这里很难解释)
编辑:这是在嵌入式系统上,并且__COUNTER__不可用(我刚刚尝试过:__COUNTER__不是由我的编译器或预处理器定义的),并且我不确定我是否可以让 Boost 工作,至少不能完全工作。