Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use > (greater-than) inside a template parameter and not get a parsing error?

Tags:

I want to only define a function based on the size of the template parameter:

template <class T> typename std::enable_if<sizeof(T) > 1, void>::type foobify(T v) {     // ... }  int main() {     //foobify((unsigned char)30); // should not compile     foobify((long)30); } 

However, I get:

main.cpp:8:41: error: expected unqualified-id before numeric constant      typename std::enable_if<sizeof(T) > 1, void>::type 

It works if I instead do 1 < sizeof(T). Thus I believe GCC is thinking I am ending the template parameter, instead of continuing the boolean expression.

Is there any way to use > itself without having to work around it?

like image 307
Claudiu Avatar asked Oct 29 '15 20:10

Claudiu


People also ask

How do you pass a parameter to a template in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Can we pass Nontype parameters to templates?

Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.

Why do we use :: template template parameter?

Correct Option: D. It is used to adapt a policy into binary ones.

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.


Video Answer


2 Answers

Yes, expressions using that operator must be parenthesized. See [temp.names]/3:

When parsing a template-argument-list, the first non-nested >138 is taken as the ending delimiter rather than a greater-than operator. [..] [ Example:

template<int i> class X { /* ...*/ };  X< 1>2 > x1; // syntax error X<(1>2)> x2; // OK 

— end example ]

138) A > that encloses the type-id of a dynamic_cast, static_cast, reinterpret_cast or const_cast, or which encloses the template-arguments of a subsequent template-id, is considered nested for the purpose of this description.

Clearly that doesn't apply if you use the symmetric counterpart of that comparison, i.e. employing <, instead - parsing is unambiguous in that case.

like image 105
Columbo Avatar answered Sep 21 '22 21:09

Columbo


Yes, you should use parentheses:

template <class T> typename std::enable_if<(sizeof(T) > 1), void>::type foobify(T v) {     // ... } 
like image 21
Claudiu Avatar answered Sep 18 '22 21:09

Claudiu