Template Parameter Dilemma

I have a dilemma. Suppose I have a template class:

template <typename ValueT>
class Array
{
public:
    typedef ValueT ValueType;
    ValueType& GetValue()
    {
        ...
    }
};

Now I want to define a function that receives a reference to the class and calls the GetValue () function. I usually consider the following two ways:

Method 1:

template <typename ValueType>
void DoGetValue(Array<ValueType>& arr)
{
    ValueType value = arr.GetValue();
    ...
}

Method 2:

template <typename ArrayType>
void DoGetValue(ArrayType& arr)
{
    typename ArrayType::ValueType value = arr.GetValue();
    ...
}

There is practically no difference between the two methods. Even a call to both functions will look exactly the same:

int main()
{
    Array<int> arr;
    DoGetValue(arr);
}

Now, which of the two best? I can think of some minuses and pluses:

Method 1:

The parameter is a real class, not a template, so it’s easier for the user to understand the interface - it is very obvious that the parameter must be an array. In method 2, you can only guess this on behalf of. We use ValueType in the function, so this is more clear than when it is hidden inside the array and should be accessible using the scope operator.

, typename .

2:

"" . , , , Array. , GetValue ValueType. . .

Array. , ? DoGetValue? , .

, , , . ?

+3
3

ArrayType, , # 1, : , ArrayType.

, DoGetValue, # 2, .

, .

+1

. : " " " :" , ". , , . GetValue. , (), (). , , -, .

+4

, :

3: , :: ValueType.

template <typename ArrayType, typename ValueType = ArrayType::ValueType>
void DoGetValue(ArrayType& arr)
{
    ValueType value = arr.GetValue();
    ...
}

4: .

template <template <typename> class ArrayType, typename ValueType>
void DoGetValue(ArrayType<ValueType>& arr)
{
    ValueType value = arr.GetValue();
    ...
}
0
source

Source: https://habr.com/ru/post/1728814/


All Articles