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?
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.
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.
Correct Option: D. It is used to adapt a policy into binary ones.
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.
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 adynamic_cast
,static_cast
,reinterpret_cast
orconst_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.
Yes, you should use parentheses:
template <class T> typename std::enable_if<(sizeof(T) > 1), void>::type foobify(T v) { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With