how to use function as literal string in C or C++ macro -


i posted a similar question yesterday, site suggested post new question better explanations.

there 2 macros:

#define company l"test company" #define product company l" in canada" 

the result of product "test company in canada".

now, have following requirements:

  1. make company "dynamic" string, call function return company name, e.g . #define company getcompanyname()
  2. we not allowed change other code reference company, such #define product company l" in canada", since there many macros in code

the issue change: result of product "test company", lost part " in canada" literal.

here code:

#include <stdio.h> #include <tchar.h> const wchar_t* getcompanyname() { return l"test company";}; #define company getcompanyname(); #define product company l" in canada"  int _tmain(int argc, _tchar* argv[]) {  const wchar_t * company = company; // test company const wchar_t * product = product; // test company in canada  wprintf(company); wprintf(product);   return 0; }  

it's nasty hack, it's possible. define company expression, starts literal, ends literal , can implicitly converted const wchar_t *:

#define company l"" + getcompanyname() + l"" 

of course getcompanyname() must not return const wchar_t *, because operator+ not defined 2 pointers , work on addresses , not strings anyway.

you need std::wstring, need convertible const wchar_t *, std::wstring not. you'd have define own class:

struct autoconvertiblestring {     std::string s;     autoconvertiblestring(const std::string &s) : s(s) {}     // c++ optimization move:     // autoconvertiblestring(std::string s) : s(std::move(s)) {}     operator const wchar_t *() { return s.c_str(); } }; autoconvertiblestring operator+(const wchar_t *l, const autoconvertiblestring &r) {     return (l + r.s).c_str(); } autoconvertiblestring operator+(const autoconvertiblestring &l, const wchar_t *r) {     return (l.s + r).c_str(); } // ok, operator+s optimized use move temporaries too...  autoconvertiblestring getcompanyname() { /* ... whatever ... */ } 

it's ugly hack. better convert of them functions. should work.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -