C ++编译时函数执行 [英] C++ compile time function execution

查看:102
本文介绍了C ++编译时函数执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有字符串标签,它们被转换为数字,用于在标签值结构中搜索值。

I have string tags in my code that are converted to numbers and used to search values in a tag-value structure.

我有这样的: p>

I have something like this:

void foo()
{
    type value = search("SomeTag");
}

其中搜索定义如下:

type search(const char* tag)
{
    return internal_search(toNumber(tag));
}

因为所有时间标记在编译时都是常量,我想删除调用将标签转换为来自搜索功能的数字。我知道可以在编译时使用模板执行一些简单的函数( http://en.wikipedia.org/wiki/Compile_time_function_execution ),但我不知道如何迭代通过一个null终止的字符串,并保留模板中的中间值。

Because all the time tag is constant at compile time I want to remove the call that converts the tag to a number from search function. I know it is possible to execute some simple functions at compile time using templates (http://en.wikipedia.org/wiki/Compile_time_function_execution), but I don't know exactly how to iterate through a null terminated string and keep intermediate values in the template. Can you give a simple sample that iterates a null terminated string and adds the chars in a public variable please?

推荐答案

你不能操作在编译时的字符串字面量,所以你想要的是不可行的,你建议的方式。但是,如果你打算在编译时处理这些字符串,那么这意味着你在编译时知道所有的字符串,从中你可以得到你想要的可接受的近似值。

You cannot operate on string literals at compile-time, so what you want isn't feasible in the way you suggested. However, if you're contemplating to process these strings at compile-time, then this means you know all strings at compile-time, and from that you might arrive at acceptable approximations to what you want.

您显示的代码意味着每次有人搜索标记时都会调用数字生成(我们称之为哈希)。将这减少到一个调用是可以接受的吗?如果是这样,你可以定义常量,并使用这些而不是字符串:

The code you showed implies that the number generation (let's call it a hash) is invoked every time someone searches for a tag. Would reducing this to one invocation be acceptable? If so, you could define constants and use these instead of strings:

const int SomeTag       = toNumber("SomeTag"      ); 
const int SomeOtherTag  = toNumber("SomeOtherTag" ); 
const int YetAnotherTag = toNumber("YetAnotherTag"); 
// ... 

然后,简单地替换通过搜索(SomeTag)搜索(SomeTag)

Then, simply replace all occurances of search("SomeTag") by search(SomeTag).

大量的标签,打字上面可能是非常乏味,在这种情况下一个宏可能有帮助:

If there's a great number of tags, typing the above could be very tedious, in which case a macro might help:

#define DEFINE_TAG(Tag_) const int Tag_ = toNumber(#Tag_); 

DEFINE_TAG(SomeTag); 
DEFINE_TAG(SomeOtherTag); 
DEFINE_TAG(YetAnotherTag); 
// ... 

#undef DEFINE_TAG

这篇关于C ++编译时函数执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆