-4

Suppose I have a function that takes a string as input:

SomeOutputType f_impl(const char* s);

Most call sites just use string literals as input, e.g. f("Hello, world"). Suppose I have implemented the following function to compute the result at compile time

template <char...> SomeOutputType f_impl();

My question is, is there a way to let the call sites like f("Hello, world") calls the templated form, while for general call sites like string s="Hello, world"; f(s.c_str()); calls the general form? For clarification, auto s = "Hello, world"; f(s); don't have to call the templated form because s is now a variable and no longer a compile time constant.

A useful case for this question is to optimize printf. In most cases the format will be string literals so a lot of things can be done at compile time to optimize things, instead of parsing the format at runtime.

7
  • 1
    Your function template has no input argument. Is that intended?
    – Andy Prowl
    Feb 17, 2013 at 20:23
  • Yes, the string literals should be converted to the template paramters.
    – Kan Li
    Feb 17, 2013 at 20:23
  • 1
    You can't invoke a function uniformly if you have to supply a function argument in one case and a template argument in another case
    – Andy Prowl
    Feb 17, 2013 at 20:25
  • Well I modified my question so that it reflects my intension clearly. Users call function f and it somehow dispatches to different forms of f_impl according to whether the call site uses string literal or not.
    – Kan Li
    Feb 17, 2013 at 20:31
  • So basically you want to specialise a template on whether a function argument was a string literal? Feb 17, 2013 at 21:12

3 Answers 3

17

No, a string literal like "foo" has the type const char[S + 1] where S is the number of characters you wrote. It behaves like an array of that type with no special rules.

In C++03, there was a special rule that said that a string literal could convert to char*. That allowed you to say

#define isStringLiteral(X) \
  isConvertibleToCharStar(X) && hasTypeConstCharArray(X)

For example isStringLiteral(+"foo") would yield false, and isStringLiteral("foo") would yield true. Even this possibiliy would not have allowed you to call a function with a string literal argument and behave differently.

C++11 removed that special conversion rule and string literals behave like any other arrays. In C++11 as a dirty hack you can compose some macros, matching some simple string literals without handling escape sequences

constexpr bool isStringLiteral(const char *x, int n = 0) {
  return *x == '"' ? 
           n == 0 ?
             isStringLiteral(x + 1, n + 1)
             : !*(x + 1) 
           : (*x && n != 0 && isStringLiteral(x + 1, n + 1));
}

#define FastFun(X) \
  (isStringLiteral(#X) ? fConstExpr(X, sizeof(X) - 1) : f(X))
26
  • 4
    @icando don't worry. it may be useful to others. Feb 17, 2013 at 21:08
  • 12
    @icando no, I won't delete it. It correctly explains why it is not possible to do what you asked for. I can understand that you find it frustrating that it won't work, but having no answer instead of an answer that states it doesn't work won't change it. Feb 17, 2013 at 21:10
  • 4
    @icando: Johannes Schaub is a world-reknowned expert in C++ who has contributed significant expertise to the standards committee itself, so you might want to spend a little less time blaming everybody for doing everything wrong, and a little more time in trying to figure out what it is that you are doing wrong. Feb 17, 2013 at 23:12
  • 6
    @icando: Yes, that's exactly right. You are "C++ super expert". Feb 17, 2013 at 23:29
  • 4
    @icando I am now invoking Godwin's Law. Discussion over; you lost.
    – Peter Wood
    Feb 18, 2013 at 0:01
0

While I haven't tested this, I think if you just declare the function constexpr and compile with high optimization, the compiler will compute at compile time whenever possible. As a bonus, you don't need to write the code twice. On the other hand, you have to write it once in constexpr style.

-2

If I understand the question correctly, I actually think something like this is possible using a function overload. Here's an article that shows the basic idea. In your case I think it would be sufficient to have the following two overloads:

void f(char const *);

template<unsigned int N>
void f(char const (&)[N]);

The latter should be invoked when the string is a string literal, the latter at other times. If the compiler is sufficiently good at optimizing then calls to the latter may be evaluated at compile time.

EDIT:

Alright, it bothered me that the above solution didn't work, so I did some playing around and I think I came up with a solution:

#include <string>
#include <boost/utility/enable_if.hpp>

template<typename T>
struct is_string_literal {
  enum { value = false };
};

template<unsigned int N>
struct is_string_literal<char const (&)[N]> {
   enum { value = true };
};

template<typename T>
typename boost::disable_if<is_string_literal<T> >::type
foo(T) {
  std::cout << "foo1" << std::endl;
}

template<int N>
void foo(char const (&)[N]) {
  std::cout << "foo2" << std::endl;
}

int main( ) {
  std::string bar = "blah";
  char const str[] = "blah";

  foo(str);
  foo("blah");

  foo(bar.data());
}

The output (on GCC 4.4 with -O3) is:

foo2
foo2
foo1

I admit that I don't completely understand why this works when the previous solution didn't. Maybe there's something about overload resolution that I don't completely understand.

13
  • The non-template function is always a better match than template functions (try out the code and see which one is chosen).
    – Jesse Good
    Feb 17, 2013 at 20:49
  • Well, this still relies on the optimization of the compiler and only works for simple f_impl. I don't think for functions as complicated as printf this technique helps.
    – Kan Li
    Feb 17, 2013 at 20:51
  • @Jesse Seems you're right. It does beg the question of how the author got the results he did in the post. Feb 17, 2013 at 20:57
  • @icando I don't understand. Any solution will rely on the optimizing capabilities of the compiler to evaluate f at compile time unless you can represent it as a constexpr in C++11. Feb 17, 2013 at 20:58
  • 1
    You're so wrong, it's not even funny. Your "Is string literal" template function will be called for any array of characters, string literal or not.
    – Puppy
    Feb 17, 2013 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.