5

Is it possible to make an overload of a constructor which will accept only a blank string when used in an initializer list?

struct null_ptr_type;

struct str
{
  str(null_ptr_type*) {}
  str(const char(&)[1]) {}
};

struct config
{
  str s;
};

int main()
{
  config c1 = {0}; // Works, implicit conversion to a null pointer
  config c2 = {str("")}; // Works
  config cx = {str("abc")}; // Fails (as desired)
  config c3 = {""}; // Fails with no conversion possible
}

Is there a way to make the syntax for c3 work without also accepting non-empty strings? I don't see why it doesn't, given that c1 works. Is there some rule I'm missing here that forbids this?

Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
  • FWIW, VS 2013 invokes the implicit conversion as you would expect. Not the best reference I know but it's something. – Captain Obvlious Apr 17 '14 at 17:40
  • Thanks, maybe I should specify: `g++ (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3`, but good to hear it does work somewhere. :) – Dark Falcon Apr 17 '14 at 17:41
  • 1
    clang++3.5 also accepts this conversion. – dyp Apr 17 '14 at 17:42
  • Could you not give it a default value, so you'd do config(string fred = ""); ? –  Apr 17 '14 at 17:44
  • The real code is much more complex, with members before and after that are initialized. There are also thousands of strings in a format not easily batch-modified. (Lots of legacy code) – Dark Falcon Apr 17 '14 at 17:45
  • 1
    Why do you want this? I can't envision any reason. – Cheers and hth. - Alf Apr 17 '14 at 17:48
  • @Cheersandhth.-Alf, internationalization. This string is displayed to the user, and I want to enforce that all non-empty strings are wrapped in `N_()`, but a lot of those strings are blank strings and I don't want to modify each and every one. – Dark Falcon Apr 17 '14 at 17:51
  • If N_ is a macro, then you have the option of doing things like `#define N_( s ) tutti_frutti( s, sizeof( s ) )`. In C++03 you could even determine whether `s` was a literal. In C++011 that's only possible with a suitable assumption (clearly communicated to users). – Cheers and hth. - Alf Apr 17 '14 at 17:55
  • On further reflection that doesn't solve your problem of "avoid fixing those existing empty strings". Not sure I grok the problem though. It seems strange to have so many empty string arguments around. – Cheers and hth. - Alf Apr 17 '14 at 18:01

1 Answers1

0

Using C++11 and "uniform initialization syntax" you can make this work, on assumption that you are able to modify interface of struct config:

struct config
{
  str s;

  config(str s) : s(s) {}
};

int main()
{
  config c1 = {0}; // Works, implicit conversion to a null pointer
  config c2 = {str("")}; // Works
  config cx = {str("abc")}; // Fails (as desired)
  config c3 = {""}; // Works
}
milleniumbug
  • 15,379
  • 3
  • 47
  • 71