将两个常量字符串(或数组)到在编译时间常数字符串(或阵列) [英] Combine two constant strings (or arrays) into one constant string (or array) at compile time

查看:145
本文介绍了将两个常量字符串(或数组)到在编译时间常数字符串(或阵列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#和Java,就可以创建使用一个或多个其他常量字符串常量字符串。我试图实现在C相同的结果++(实际上,在C ++ 0x中,要具体),但不知道什么语法我会用它来实现它,如果这样的事情是可能的C ++。这里有一个例子说明什么,我想做的事:

In C# and Java, it's possible to create constant strings using one or more other constant strings. I'm trying to achieve the same result in C++ (actually, in C++0x, to be specific), but have no idea what syntax I would use to achieve it, if such a thing is possible in C++. Here's an example illustrating what I want to do:

#include <stdio.h>

const char array1[] = "Hello ";
const char array2[] = "world!\n";
const char array3[] = array1 + array2; // C++ doesn't like it when I try this

int main() {

    printf(array3);

    return 0;

}

任何指针? (没有双关语意)。

Any pointers? (No pun intended.)

编辑:我需要能够以这种适用于整型数组以及 - 不仅仅是字符数组。然而,在这两种情况下,要被合并的阵列将是固定大小和是编译时间常数

I need to be able to apply this to integer arrays as well - not just char arrays. However, in both cases, the to-be-combined arrays will be fixed-size and be compile-time constants.

推荐答案

在的C ++ 0x可以做到以下几点:

In C++0x you can do the following:

template<class Container>
Container add(Container const & v1, Container const & v2){
   Container retval;
   std::copy(v1.begin(),v1.end(),std::back_inserter(retval));
   std::copy(v2.begin(),v2.end(),std::back_inserter(retval));
   return retval;
}

const std::vector<int> v1 = {1,2,3};
const std::vector<int> v2 = {4,5,6};
const std::vector<int> v3 = add(v1,v2);

我不认为有任何方式在C ++ 98(增加部分STL容器做到这一点的 V3 你可以做,但你不能在C ++ 98)使用初始化列表的 V1 V2 ,我不认为有什么办法对于C ++ 0x中或原始阵列C ++ 98做到这一点。

I don't think there's any way to do this for STL containers in C++98 (the addition part for v3 you can do, but you can't use the initializer lists for v1 and v2 in C++98), and I don't think there's any way to do this for raw arrays in C++0x or C++98.

这篇关于将两个常量字符串(或数组)到在编译时间常数字符串(或阵列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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