在运行时之前对字符串进行操作

发布于 2024-09-29 12:06:16 字数 235 浏览 2 评论 0原文

我有一个字符串: B::B() [with T = int]

有什么办法可以得到 B[with T = int] 在运行时之前以某种方式? :)

简化:有没有办法得到 X & Y 与运行前以任何形式定义为预处理器宏的静态字符串 XY 分开吗?

I have a string:
B<T>::B() [with T = int]

Is there any way I can get
B<T> [with T = int] from this before run time somehow? :)

Simplifying: Is there any way to get X & Y separately from a static string XY defined as a preprocessor macro in any form before runtime?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

入画浅相思 2024-10-06 12:06:16

在当前的 C++ 中,我无法想出在编译时分割字符串的方法。大多数模板技巧不适用于字符串文字。现在,我想您希望在某种日志记录机制中使用它,并且希望避免在每个方法调用中在运行时执行拆分的影响。如果是这种情况,请考虑添加一个将执行该操作的函数,然后在每个函数中添加一个 static const std::string 来保存该值。该字符串将在第一次调用该函数时仅初始化一次:(

#define DEFINE_LOG_NAME static const std::string _function_name( parse( __PRETTY_FUNCTION__ ) )
#define LOG_NAME( level ) do { DEFINE_LOG_NAME; log( level, _function_name ); } while (0)
std::string parse( std::string const & pretty ) {
   // split here, return value
}
template <typename T>
struct B {
   B() {
      LOG_NAME( DEBUG );
   }
};

我尚未对此进行测试,因此您可能需要摆弄它)

这将产生一些运行时影响,但每个函数仅初始化一次。另请注意,这种方法不是线程安全的:如果两个线程同时调用之前未调用过的方法,则会出现竞争条件。

In current C++ I cannot think on a way to split the string at compile time. Most of the template tricks will not work on string literals. Now, I imagine that you want this to use in some sort of logging mechanism and you want to avoid the impact of performing the split at runtime in each method invocation. If that is the case, consider adding a function that will perform the operation and then in each function a static const std::string to hold the value. That string will be initialized only once in the first call to the function:

#define DEFINE_LOG_NAME static const std::string _function_name( parse( __PRETTY_FUNCTION__ ) )
#define LOG_NAME( level ) do { DEFINE_LOG_NAME; log( level, _function_name ); } while (0)
std::string parse( std::string const & pretty ) {
   // split here, return value
}
template <typename T>
struct B {
   B() {
      LOG_NAME( DEBUG );
   }
};

(I have not tested this, so you might need to fiddle with it)

This will have some runtime impact, but only once for each function. Also note that this approach is not thread safe: if two threads simultaneously call a method that has not been called before there will be a race condition.

何止钟意 2024-10-06 12:06:16

这是你想要的吗?

#define X "X"
#define Y "Y"
#define XY string(X) + Y
static string s = XY;

is this what you wanted ?

#define X "X"
#define Y "Y"
#define XY string(X) + Y
static string s = XY;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文