D
D
Dmitry Ivanov2018-02-09 11:06:11
C++ / C#
Dmitry Ivanov, 2018-02-09 11:06:11

How to restrict allowed types when describing a type template in C++?

There is some class (Float2) with a constructor that takes several parameters. For example: Further there was a need to accept other data types as arguments. It would be possible to use a template , but it is required to restrict types - in my case only float and string . Yes, you can write something like thisvoid Float2(float x, float y);
template <typename T>

void Float2(float x, float y);
void Float2(float x, string y);
void Float2(string x, float y);
void Float2(string x, string y);

However, in addition to such a class, there is also a similar one with 4 arguments, and these are already 16 variations of constructors. So things won't work.
Question : Is it possible to describe a type template so that it is limited to float and string types only , and the constructor itself is reduced to a kind or something similar void Float2(T x, T y);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-02-09
@IDma88

Since C++17, you can use constexpr if in templates: en.cppreference.com/w/cpp/language/if . In the condition itself, something like en.cppreference.com/w/cpp/types/is_same, well, give a compilation error if the types do not match. True, you still have to write down the rules with your hands or read the advanced template metaprogramming.
There is another option with boost::mpl, for example, use mpl::vector.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question