Home > Net >  Understanding the usage of the syntax "<DataType>" in C
Understanding the usage of the syntax "<DataType>" in C

Time:10-01

I want to understand the usage of the "<DataType>" in C . As far as I read about, it is the syntax used for templates, which uses the specified data type for specialization of function or class instantiation.

Coming from python, I understand that all data types are by definition a class (correct me if it does not apply for C ), so if you look for the int implementation in python, you will find:

class int: 
    @overload 
    def __new__(cls: Type[_T], x: str | bytes | SupportsInt | SupportsIndex | _SupportsTrunc = ...) -> _T: ...
 ... 

Which constructor is overloaded based in arguments. So why in C it does not use (dataType) instead of <dataType> and overload the constructor based on the type of the arguments?

Also, can I safely state that every time <DataType> appears, it is surely a template there?

some examples:

std::vector<int> x;
std::vector< std::vector<int> >& someVar;

cv::Mat opencvMat;
int x = static_cast<int>(opencvMat.at<float>(i, 3) * frameWidth);

CodePudding user response:

I'll use your examples:

std::vector<int> x;

x is a vector (dynamic-length array) that contains ints.

std::vector< std::vector<int> >& someVar;

someVar is a reference to a vector of vectors. The inner vectors holds ints. This would be a common way to make a reference to a two-dimensional dynamic array, where each row could have a different number of columns.

int x = static_cast<int>(opencvMat.at<float>(i, 3) * frameWidth);

This is how you do various styles of cast. I'll break it into two:

opencvMat.at<float>(i, 3)

I don't use this library, but the at method is probably a template, and it means you're going to receive a float.

The static_cast forces the calculated value to an int without a compiler warning for loss of precision.

As you've figured out, this is all related to templates, and you'll see templates are defined using <>. For instance:

template <class ObjectType>
class Foo:
public:
     ObjectType value;
};

Foo<std::string> myFoo;

In this case, myFoo.value is a string.

  • Related