I ran into the following problem. I have the following template Number
:
template<int n>
struct Number
{
static const int value = n;
};
Suppose now that I want to add two such Numbers at compile time. Specifically, I want to get the following snippet to work:
//The following code should display 7:
std::cout << Number_add< Number<3>, Number<4> >::value << std::endl;
I tried something like this, but my compiler doesn't like it.
template<Number<int> n1, Number<int> n2>
struct Number_add
{
static const int value = n1::value + n2::value;
}
What is the correct way to implement Number_add? I think that template template parameters might be needed here, but I couldn't get that to work either. Help would be greatly appreciated.
Number<int>
cannot be used as a non-type template parameter because User defined classes aren't one of the allowed types. The allowed types are (reproduced from cppreference.com):
- std::nullptr_t (since C++11);
- integral type;
- lvalue reference type (to object or to function);
- pointer type (to object or to function);
- pointer to member type (to member object or to member function);
- enumeration type.
You can simply do as n.m
suggested in the comments
template<typename n1, typename n2>
struct Number_add
{
static const int value = n1::value + n2::value;
}