What does template <unsigned int N> mean? - c++

When declaring a template, I am used to having this kind of code:
template <class T>
But in this question, they used:
template <unsigned int N>
I checked that it compiles. But what does it mean? Is it a non-type parameter? And if so, how can we have a template without any type parameter?

Yes, it is a non-type parameter. You can have several kinds of template parameters
Type Parameters.
Types
Templates (only classes and alias templates, no functions or variable templates)
Non-type Parameters
Pointers
References
Integral constant expressions
What you have there is of the last kind. It's a compile time constant (so-called constant expression) and is of type integer or enumeration. After looking it up in the standard, i had to move class templates up into the types section - even though templates are not types. But they are called type-parameters for the purpose of describing those kinds nonetheless. You can have pointers (and also member pointers) and references to objects/functions that have external linkage (those that can be linked to from other object files and whose address is unique in the entire program). Examples:
Template type parameter:
template<typename T>
struct Container {
T t;
};
// pass type "long" as argument.
Container<long> test;
Template integer parameter:
template<unsigned int S>
struct Vector {
unsigned char bytes[S];
};
// pass 3 as argument.
Vector<3> test;
Template pointer parameter (passing a pointer to a function)
template<void (*F)()>
struct FunctionWrapper {
static void call_it() { F(); }
};
// pass address of function do_it as argument.
void do_it() { }
FunctionWrapper<&do_it> test;
Template reference parameter (passing an integer)
template<int &A>
struct SillyExample {
static void do_it() { A = 10; }
};
// pass flag as argument
int flag;
SillyExample<flag> test;
Template template parameter.
template<template<typename T> class AllocatePolicy>
struct Pool {
void allocate(size_t n) {
int *p = AllocatePolicy<int>::allocate(n);
}
};
// pass the template "allocator" as argument.
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;
A template without any parameters is not possible. But a template without any explicit argument is possible - it has default arguments:
template<unsigned int SIZE = 3>
struct Vector {
unsigned char buffer[SIZE];
};
Vector<> test;
Syntactically, template<> is reserved to mark an explicit template specialization, instead of a template without parameters:
template<>
struct Vector<3> {
// alternative definition for SIZE == 3
};

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:
unsigned int x = N;
In fact, we can create algorithms which evaluate at compile time (from Wikipedia):
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}

You templatize your class based on an 'unsigned int'.
Example:
template <unsigned int N>
class MyArray
{
public:
private:
double data[N]; // Use N as the size of the array
};
int main()
{
MyArray<2> a1;
MyArray<2> a2;
MyArray<4> b1;
a1 = a2; // OK The arrays are the same size.
a1 = b1; // FAIL because the size of the array is part of the
// template and thus the type, a1 and b1 are different types.
// Thus this is a COMPILE time failure.
}

A template class is like a macro, only a whole lot less evil.
Think of a template as a macro. The parameters to the template get substituted into a class (or function) definition, when you define a class (or function) using a template.
The difference is that the parameters have "types" and values passed are checked during compilation, like parameters to functions. The types valid are your regular C++ types, like int and char. When you instantiate a template class, you pass a value of the type you specified, and in a new copy of the template class definition this value gets substituted in wherever the parameter name was in the original definition. Just like a macro.
You can also use the "class" or "typename" types for parameters (they're really the same). With a parameter of one of these types, you may pass a type name instead of a value. Just like before, everywhere the parameter name was in the template class definition, as soon as you create a new instance, becomes whatever type you pass. This is the most common use for a template class; Everybody that knows anything about C++ templates knows how to do this.
Consider this template class example code:
#include <cstdio>
template <int I>
class foo
{
void print()
{
printf("%i", I);
}
};
int main()
{
foo<26> f;
f.print();
return 0;
}
It's functionally the same as this macro-using code:
#include <cstdio>
#define MAKE_A_FOO(I) class foo_##I \
{ \
void print() \
{ \
printf("%i", I); \
} \
};
MAKE_A_FOO(26)
int main()
{
foo_26 f;
f.print();
return 0;
}
Of course, the template version is a billion times safer and more flexible.

Related

Syntax for an instance of a class template as a non-type template parameter

I can't find the right syntax even after reading cppreference on template params. The following doesn't compile, but hopefully describes what I want to do. What's the correct syntax?
template <class DisplayType>
class DisplayAdapter : public DisplayType
{
};
template<template <typename> DisplayAdapter>
class Painter // Takes an instance of DisplayAdapter, not a type!
{
}
Here is how it's supposed to be used:
struct S{};
int main()
{
DisplayAdapter<S> concreteAdapter;
Painter<concreteAdapter> p;
return 0;
}
Here's Ideone snippet for the whole thing: https://ideone.com/dvbYt8
What you're wanting is not a template template parameter.
A template template parameter is used to pass templates around, like this:
template<template<typename> typename Container>
struct foo {
Container<int> container;
};
int main() {
foo<std::vector> f;
}
As you can see, you can pass template names around with that. Remember that templates are not types, but a blueprint for type, and the language (and the standard) is not treating templates the same way as types.
I assume with your examples your trying to use non-type template parameters?
A non-type template parameter is a template parameter that is a value instead of a type. It can be of any integral types, reference type and pointer type.
For example, look at std::array:
std::array<int, 10> tenInts;
Notice the second parameter is a number. This is because std::array look something like this:
template<typename T, std::size_t N>
struct array { /* ... */ };
The second parameter is an unsigned long int.
You can also pass references and pointers as template parameter:
template<int& i> struct foo {};
template<int* i> struct bar {};
int main() {
// Need at least internal linkage in C++14 and older
// No linkage required since C++17, only static needed.
static int num = 0;
foo<num> f;
bar<&num> b;
}
You can even pass a pointer to any type as reference template parameter:
struct stuff {};
template<stuff& s> struct foo;
int main() {
static stuff s{};
foo<s> f; // works!
}
This seem to be closer to what you wanted. However, you seem to have many many different type you want to send as template parameter, as the type of the instances you want to pass around are templated. For that you'll need C++17 template auto feature:
template<auto& da>
struct Painter {
// ...
};
int main() {
static DisplayAdapter<S> concreteAdapter;
Painter<concreteAdapter> p;
}
And done!
If you don't have C++17 with you don't worry, and simply pass the display type along with your instance (C++14 example):
template<typename DT, DisplayAdapter<DT>& da>
struct Painter {};
// Internal linkage
DisplayAdapter<S> da;
int main() {
Painter<S, da> painter;
}
If it was some simple type like int you would just use type instead of typename keyword e.g
template <int x>
or
template <std::vector<int>::value_type x>
But you can't put object of arbitrary type here.
More about non-type template parameters can be found in another Q&A
You need to add class before DisplayAdater
template <class DisplayType>
class DisplayAdapter : public DisplayType
{
};
template<template <typename> class DisplayAdapter>
class Painter // Takes an instance of DisplayAdapter, not a type!
{
};
https://godbolt.org/g/mV7YRC

Return a class template with value template arguments from function

Suppose I have a simple template class:
template <typename ElementType, ElementType Element>
class ConsecutiveMatcher
{
public:
bool operator () (ElementType lhs, ElementType rhs)
{
return lhs == Element && rhs == Element;
}
};
I would usually make instantiation simpler than ConsecutiveMatcher<wchar_t, L'\\'>() by providing a function which can infer the template argument types based on the parameter types:
template <typename ElementType>
ConsecutiveMatcher<ElementType, Element /* ?? */>
MakeConsMatcher(ElementType Element)
{
return ConsecutiveMatcher<ElementType, Element>();
}
However, in this case, MakeConsMatcher(L'\\') will not work, because the function needs to return a class whose template does not only contain a type, but also a value.
How can I return a class template from a function which has not only type template arguments, but also value template arguments?
You want a runtime computed value turned into an template argument? it's not possible.
I'm just looking for a way to omit the wchar_t and use automatic type deduction during instantiation.
I can imagine such situations:
Argument type only known at runtime (and you have no any idea about it): you cannot handle it with templates: you will want to redesign your code and use inheritance and virtual functions (or, probably, mix both, templates and inheritance)
Argument type known at compile-time, argument value known at runtime: left Type of argument in template argument list and pass argument value to constructor, then, for user's convenience, make factory function to deduce type
template<typename T>
struct MyType
{
template <class T>
MyType(const T& defaultValue) :
value(defaultValue)
{}
T value;
};
template<typename T>
MyType<T> MyFactory(const T& defaultValue)
{
return MyType<T>(defaultValue);
}
int main()
{
char c = 'a';
wchar_t w = L'a';
int i = 42;
float f = 3.14f;
auto mt_char = MyFactory(c);
auto mt_wchar = MyFactory(w);
auto mt_int = MyFactory(i);
auto mt_float = MyFactory(f);
}
At compile-time you know a list of Types and want they behave differently (for example have different default values): make template specializations for each type from a list, then, for user's convenience, create typedefs
template<typename T> struct MyType
{
MyType(const T& defaultValue) :
value(defaultValue)
{}
T value;
};
template<>
struct MyType <char>
{
MyType() :
value('c')
{}
char value;
};
template<>
struct MyType <wchar_t>
{
MyType() :
value(L'w')
{}
wchar_t value;
};
typedef MyType<char> MyTypeChar;
typedef MyType<wchar_t> MyTypeWchar;
int main()
{
MyTypeChar mt_char_default;
MyTypeWchar mt_wchar_default;
}
In this case, user still can instantiate own specializations. Example of that approach is a std::basic_string class.
Further, you can simplify your specializations, if make class members static or static const and for integral types just define in member list:
template<>
struct MyType <char>
{
static const char value = 'c';
};

typedefing non-type template parameter

I would like to access a template parameter outside of a class. I usually do this as follows:
template <class T>
class A
{
typedef typename T T;
}
A<int>::T;
I would like to be able to do the same for non-type template parameters. This doesn't work:
template <int T>
class A
{
typedef typename T T;
}
A<3>::T;
I will clarify why I need this. I want to define a second class as follows:
template <class C>
class B
{
static int func() {return C::T;}
}
B<A<3> >::func();
What is the correct way to do this?
Thank you very much.
That's because T is not a type name and you cannot typedef it. It is an int value and, if you want to access it as a static member of the class, you need a static member int. Seems like what you really want is this:
template <int T>
class A
{
public:
static const int x = T;
};
doSomething(A<5>::x);
It's a value, and not a type, so perhaps:
template <int T>
class A
{
static const int param = T;
};
And then you can access it as A<42>::param. Not that it helps much, unless A is itself used as a template parameter somewhere else.
in the second case, T is not a type, it's an int value. Therefore you should define it as a const int or static const int value.
template <int T>
class A {
static const int T = T;
};
Note that it is customary to use T for types (in particular when the template is monadic, since there is no ambiguity on the type), and other names for constants, usually a more meaningful name, for instance SIZE or preferably Size (all caps symbols are best used for macros).
template <int Param>
class A {
static const int param = Param;
};
See other SO questions (like this one) for the use of static const values in the context of a template definition.

Template classes with specialised constructors

Consider the following contrived example of a templated array definition:
template <typename t, unsigned int n> class TBase
{
protected:
t m_Data[n];
//...
};
template <typename t, unsigned int n> class TDerived : public TBase<t, n>
{
TDerived()
{
}
};
I can specialize this type to provide a non-default constructor for an array of length 2 as follows:
template <typename t> class TDerived<t, 2> : public TBase<t, 2>
{
public:
TDerived(const t& x0, const t& x1)
{
m_Data[0] = x0;
m_Data[1] = x1;
}
};
int main()
{
TDerived<float, 2> Array2D_A(2.0f, 3.0f); //uses specialised constructor
TDerived<float, 3> Array3D_A; //uses default constructor
return 0;
}
Is there some other way I can create a class that has different constructor options constrained against template parameters at compile-time without the requirement for a complete class specialisation for each variation?
In other words, is there some way I can have specialised constructors in the TBase class without the need for the intermediary step of creating TDerived whilst preserving the functionality of TBase?
I think deriving your class from a base class is not relevant to the question here, that's a mere implementation detail. What you really seem to be after is if there's a way to partially specialize member functions, like the constructor. Do you want something like this?
template <typename T, int N> class Foo
{
Foo(); // general
template <typename U> Foo<U, 2>(); // specialized, NOT REAL CODE
};
This doesn't work. You always have to specialize the entire class. The reason is simple: You have to know the full type of the class first before you even know which member functions exist. Consider the following simple situation:
template <typename T> class Bar
{
void somefunction(const T&);
};
template <> class Bar<int>
{
double baz(char, int);
};
Now Bar<T>::somefunction() depends on T, but the function only exists when T is not int, because Bar<int> is an entirely different class.
Or consider even another specialization template <> class Bar<double> : public Zip {}; -- even the polymorphic nature of a class can be entirely different in a specialization!
So the only way you can provide specializations new declarations of members, including constructors, is by specializing the entire class. (You can specialize the definition of existing functions, see #Alf's answer.)
There are basically two options I see for this:
Use a variadic function for construction (ie. "..." notation), you can use the value n inside that function to get your arguments from the stack. However, the compiler will not check at compile time if the user provides the correct number of arguments.
Use some serious template magic to allow a call chaning initialization, that would look like this: vector(2.0f)(3.0f). You can actually build something that at least ensures the user does not provide too many arguments here. However tha mechanism is a little more involved, I can assemble an example if you want.
You can always specialize a member, e.g.
#include <stdio.h>
template< class Type >
struct Foo
{
void bar() const
{ printf( "Single's bar.\n" ); }
};
template<>
void Foo< double >::bar() const
{ printf( "double's bar.\n" ); }
int main()
{
Foo<int>().bar();
Foo<double>().bar();
}
But you want effectively different signatures, so it's not directly a case of specializing a member.
One way forward is then to declare a constructor with a single argument, of a type dependent on the template parameters.
Then you can specialize that, as you want.
Cheers & hth.,
Since constructor is a function, you need to fully specialize the containing class to address your specific problem. No way out.
However, functions cannot be partially specialized (in all compilers). So suppose if you know that you need n = 2 when t = int or double then following is one alternative.
template<>
TDerived<int,2>::TDerived()
{
//...
}
template<>
TDerived<double,2>::TDerived()
{
//...
}
and so on.
[Note: If you use MSVC, then I think it supports partial specialization; in that case you can try:
template<typename t>
TDerived<t,2>::TDerived()
{
//...
}
though, I am not sure enough for that.]
You could give the most common definitions in the non-specialized class and static_assert (BOOST_STATIC_ASSERT for non C++0x) on the array length. This could be considered a hack but is a simple solution to your problem and safe.
template<typename T, unsigned int n>
struct Foo {
Foo(const T& x) { static_assert(n == 1, "Mooh!"); }
Foo(const T& x1, const T& x2) { static_assert(n == 2, "Mooh!"); }
};
The "evil" way would be variadic arguments.
template<typename T, unsigned int n>
struct Foo {
Foo(...) {
va_list ap;
va_start(ap, n);
for(int j=0; j < n; ++j)
bork[j] = va_arg(ap, T);
va_end(ap);
}
};
Then there is also C++0x and the good old make_something trick which is more difficult then one would think.
template<typename... T, unsigned int n>
Foo<T, n> make_foo(T&&...) {
// figure out the common_type of the argument list
// to our Foo object with setters or as a friend straight to the internals
Foo< std::common_type< T... >::type, sizeof(T) > foo;
// recursive magic to pick the list apart and assign
// ...
return foo;
}

C++ template specialization problem

I need a C++ template that, given a type and an object of that type, it can make a decision based on whether the type is an integer or not, while being able to access the actual objects. I tried this
template <typename T, T &N>
struct C {
enum { Value = 0 };
};
template <int &N>
struct C<int, N> {
enum { Value = N };
};
but it doesn't work. Is there any way I can achieve something similar?
Edit
What I was trying to achieve was something like this, that would happen at compile time:
if (type is int) {
return IntWrapper<int_value>
else {
return type
}
You can actually pass pointers or references to objects in a template instantiation, like so:
struct X {
static const int Value = 5;
};
template <X *x>
struct C {
static const int Value = (*x).Value;
};
X x;
std::cout << C<&x>::Value << std::endl; // prints 5
but apparently all this accomplishes is to initialize the template by inferring x's type, and x also needs to be declared globally. No use for what I'm trying to do, which I think is not possible after all at compile time.
What you are attempting to do isn't valid C++ templating. You can't use arbitrary objects as template parameters, all you can use are types, integral literals and in certain specialised cases string literals.
Unless i misunderstand you, what you want is impossible. In your example you show an invalid use of a pointer template parameter.
template <X *x>
struct C {
static const int Value = (*x).Value;
};
That's not valid, since (*x).Value must be a constant expression for it to be able to initialize Value. Sure Value within class X would be fine as a constant expression when used as X::Value instead. But this time, it's not since it involves a pointer (references are equally invalid in constant expressions).
To sum up, you can't do this:
Magic<T, someT>::type
And expect ::type to be T if T isn't int, and IntWrapper<someT> otherwise, since T can only be an enumeration, integer, pointer or reference type. And in the latter two cases, you won't get at the "value" of anything pointed to by the pointer or referred to by the reference at compile time. If you are satisfied with that, it's easy to solve your problem and i'm not going to show you how (i suspect you already know how).
I think you have driven yourself into a situation where solving your problem has become impossible to do with the rules as given. Drive back some steps and show us the real problem you are trying to solve, when the matter still allows to solve things.
Perhaps a simple overloaded template method works in your case?
template<typename T>
void doSomething(const T& x)
{
// ...
}
void doSomething(int x)
{
// ...
}
Addition to the other posts: You don't need to use the enum {}-hack any more:
template<typename T, int val>
struct Test {
static const int Value = 0;
};
template <int val>
struct Test<int, val> {
static const int Value = val;
};
int main(int argc,char *argv[]) {
const int v = Test<int,1>::Value;
}
template <typename T> struct A
{
enum { Value = false };
};
template <> struct A<int>
{
enum { Value = true };
};
How about this then:
template <typename T> struct A
{
T value_;
A() : value() {}
enum { is_int = false };
};
template <> struct A<int>
{
int value_;
explicit A( int v ) : value_( v ) {}
enum { is_int = true };
};
I need a C++ template that, given a
type and an object of that type, it
can make a decision based on whether
the type is an integer or not, while
being able to access the actual
objects.
You can make decisions based on the type being an integer or not, the problem is it's impossible to declare a template with an object of any type. So the question on how to decide wether a type is an integer is moot.
Note that in all answers your original template is neatly changed to
template < typename T, int >
class C {};
instead of your
template< typename T, T >
class C {};
But while C<int, 5> is a perfectly valid declaration, this is not the case for an arbitrary type T, case in point C<float, 5.> will give a compiler error.
Can you post what you're trying to achieve exactly?
And for the record, if the second template argument is always an int, and you simply want to take its value if the type is an integer type, and 0 otherwhise, you can simply do:
#include <limits>
template< typename T, int N >
class C {
static const int Value = (std::numeric_limits<T>::is_integer) ? N : 0;
};
You can do it like this:
template<typename T, int val>
struct Test
{
enum {Value = 0};
};
template <int val>
struct Test<int, val>
{
enum {Value = val};
};
int main(int argc,char *argv[])
{
int v = Test<int,1>::Value;
}
simple fix to your code - loose the reference:
template <typename T, T N>
struct C {
enum { Value = 0 };
};
template <int N>
struct C<int, N> {
enum { Value = N };
};
using reference in a template argument is meaningless anyway because you're not actually passing the argument anywhere.
Check out Alexandrescu's Modern C++ Design. I believe chapter 2 has a correct example of what you want to do.
Template specialization can be achieved like this (code taken from www.cplusplus.com):
// template specialization
#include <iostream>
using namespace std;
// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {element=arg;}
T increase () {return ++element;}
};
// class template specialization:
template <>
class mycontainer <char> {
char element;
public:
mycontainer (char arg) {element=arg;}
char uppercase ()
{
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};
int main () {
mycontainer<int> myint (7);
mycontainer<char> mychar ('j');
cout << myint.increase() << endl;
cout << mychar.uppercase() << endl;
return 0;
}
In your case you would have to replace the char by what you want in the class template specialization. Now, I am not really sure what you are trying to accomplish but I hope the example above is a good indicator to how you can do some template specialization.
What I was trying to achieve was something like this, that would happen at compile time:
if (type is int) {
return IntWrapper<int_value>
else {
return type
}
I'm not sure why you aren't using IntWrapper to begin with. Where does the need come from to wrap a compile-time integer constant into an IntWrapper, if it is int?
Otherwise it looks a bit that you are trying to instantiate templates with data that is only available at run-time.