Lately I practiced the use of template in c++, and I am confused about one of the template parameters during the process.
For instance, in the following code, the input A of template<typename A> served as a 'type' to construct function and variables.
template <typename A>
A add_simple(A a, A b)
{
return a + b;
}
However, in the following example, a unit conversion operation, it seems the input M1 and M2 serve as objects. In main(), I've shown how the struct is expected to be called.
// create a template struct Measure with value and unit. e.g. Measure<int, Unit>::value
template<int v, Unit u> struct Measure{
static const int value=v;
static const Unit unit=u;
};
// Conversion struct. expected input two 'Measure' objects.
template <typename M1, typename M2>
struct Measure_add {
public:
// other implementation
static constexpr int value=M1::value+M2::value;
};
int main(int, char**) {
std::cout << Measure_add< Measure<10,Unit::m>,
Measure<20,Unit::m> >::value << std::endl;
}
So my confusion about template is:
Is
<template>designed to be such flexible that it dynamically distinguish the input so both a 'type' input and 'object' input works. Or the difference met here because the expected inputs are constructed template inputMeasure? As a result, M1 and M2 are still 'type',Measure. And in this case, whyM1::valueis available if M1 is a type instead of an object?Why is it available to get access to
M1::valueorM2::valuein template structMeasure_addthough the inputs are unknown to such struct. In other words, if I input other parameters which don't contain attributevalue, would it cause problem?