0

In C++ the following is legal:

template <int i>
run(){...}

run<3>(); // legal

const int j=3;
run<j>(); // legal because j is const

why the following are or aren't legal?

template <String s>
run(){...}

run<"hello">(); // legal or illegal?

const string s="hello";
run<s>(); // legal or illegal?
1
  • 6
    The "Why" part could be simply answered as "The standard only allows for integer non-type template parameters." The "Why" for this is a bit more complicated. Usually it devolves into discussions about architecture-specific implementations of those types. Strings, actually, are a great example of this. Floating point is usually the default go-to answer, though. Commented Mar 18, 2016 at 15:27

2 Answers 2

6

From the C++11 Standard:

14.1 Template parameters

...

4 A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
— integral or enumeration type,
— pointer to object or pointer to function,
— lvalue reference to object or lvalue reference to function,
— pointer to member,
std::nullptr_t.

Hence, you cannot use a class as a non-type template parameter.

Sign up to request clarification or add additional context in comments.

Comments

1

The int one is legal because the compiler knows about int. On the other hand, String is not a built-in C++ data type. It is defined in a header and library. The constant "hello" is an array of characters, not a String().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.