Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > de.comp.lang.iso-c++ > #1965
| From | Thomas Dorner <td-dclic01@th-dorner.de> |
|---|---|
| Newsgroups | de.comp.lang.iso-c++ |
| Subject | Re: typedef auf variadic template |
| Date | 2016-11-21 15:42 +0100 |
| Organization | solani.org |
| Message-ID | <6ebmx8rj0s.fsf@umbra.opacus> (permalink) |
| References | <o0n81u$jmv$1@news.albasani.net> <o0s0im.1v4.1@stefan.msgid.phost.de> |
> template<typename T>
> inline bool is_in(const T& item, const T& value)
> {
> return item == value;
> }
>
> template<typename T, typename... Values>
> inline bool is_in(const T& item, const T& value, Values... values)
> {
> return item == value || is_in(item, values...);
> }
>
>Aufruf als 'is_in(n, 3, 5, 27, -1327)'. Nachteil: da der Typ nicht
>angegeben ist, müssen die Parametertypen halt von vornherein passen.
Nette Lösung und nettes Problem. Ich hätte noch eine Variante
vorzuschlagen, die auch Unterschiede zwischen den Typen von Variable und
Werten erlaubt:
template<typename T1, typename T2>
inline bool is_in(const T1& item, const T2& value)
{
return item == value;
}
template<typename T1, typename T2, typename... Values>
inline bool is_in(const T1& item, const T2& value, Values... values)
{
return item == value || is_in(item, values...);
}
Dann funktioniert das Ganze sogar mit standard C++ Strings gegen
Stringliterale (oder anderen Klassen, die operator== implementieren):
std::string aString(...);
if (is_in(aString, "OK", "true"))
Achtung, nicht für standard C "char*" Strings geeignet, da sich "=="
nicht entsprechend verhält.
Aber für C++ 11 enums geht es (aber da klappt wohl auch schon die
ursprüngliche Variante):
enum class Traffic { green, yellow, red };
Traffic light = Traffic::red;
if (is_in(light, Traffic::red, Traffic::yellow))
Viele Grüße, Thomas
Back to de.comp.lang.iso-c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
typedef auf variadic template Markus Donath <nntp@online.de> - 2016-11-18 16:51 +0100
Re: typedef auf variadic template Stefan Reuther <stefan.news@arcor.de> - 2016-11-20 11:14 +0100
Re: typedef auf variadic template Markus Donath <nntp@online.de> - 2016-11-21 08:58 +0100
Re: typedef auf variadic template Markus Donath <nntp@online.de> - 2016-11-21 11:45 +0100
Re: typedef auf variadic template Thomas Dorner <td-dclic01@th-dorner.de> - 2016-11-21 15:42 +0100
Re: typedef auf variadic template Markus Donath <nntp@online.de> - 2016-11-22 10:07 +0100
Re: typedef auf variadic template nntp@mailinator.com - 2016-12-20 09:54 +0000
Re: typedef auf variadic template Markus Donath <nntp@online.de> - 2016-12-22 14:30 +0100
Re: typedef auf variadic template ram@zedat.fu-berlin.de (Stefan Ram) - 2016-12-20 13:58 +0000
Re: typedef auf variadic template Markus Donath <nntp@online.de> - 2016-12-22 14:34 +0100
Re: typedef auf variadic template Markus Donath <nntp@online.de> - 2016-12-22 14:39 +0100
csiph-web