0

I've obviously misunderstood the code. Thanks for pointing out the error.

--original post--

I know for a while that integers can be used as types in c++ template programming. What surprises me is that when an integer such as 2 and 3 is used as a type, one can actually instantiate a variable out of the type, as shown in the example below extracted from gcc 4.8.1 random.h.

It seems to me that one can declare a variable

2 x; //not actual c++ code 

and x will be an integer variable initialized to the value of 2.

Code for deterniming whether a number is a power of 2:

#include <iostream> template<typename _Tp> inline bool _Power_of_2(_Tp __x) { return ((__x - 1) & __x) == 0; }; int main() { std::cout << _Power_of_2(2) << std::endl; std::cout << _Power_of_2(3) << std::endl; } 

Output:

1 0 

Can someone please explain what's going on here in terms of types and domains?

Are there any similar features in other programming languages that can do the same, i.e. using a concrete value as a type?

Also, is this feature available for other types, such as struct, string or float?

Thanks,

1
  • 2
    Where do you see the use of an integer as a type in your code? Commented Mar 20, 2014 at 10:58

1 Answer 1

3

In your example, 2 is not used as a type, but as a function parameter. From that, the template parameter _tP is automatically deduced as int. So the lines inside main would be equivalent to:

std::cout << _Power_of_2<int>(2) << std::endl; std::cout << _Power_of_2<int>(3) << std::endl; 
Sign up to request clarification or add additional context in comments.

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.