C++Guns – RoboBlog

23.01.2018

C++ Guns - C++17 class template argument deduction user guide

Filed under: Allgemein — Tags: — Thomas @ 16:01

Es ist ja bekannt, dass der Compiler die Template Parameter von Funktionen selbst bestimmen kann.

template<typename T>
T func(T val) {
  return val;
}

auto i = func(1); // i int

Seit C++17 funktioniert das nun auch mit Klassen. Das Feature hierfür nennt sich __cpp_deduction_guides und wird seit GCC 7 unterstützt.
https://en.cppreference.com/w/cpp/language/class_template_argument_deduction
Mehr noch, es können User Guides angegeben werden. Mit denen wird festgelegt, wie genau sich der Type der Klasse ableiten soll.
Hier ein einfaches Beispiel:

#include <type_traits>

#ifndef __cpp_deduction_guides
#error "need gcc 7"
#endif

template<class T>
struct A {
    using value_type = T;

    template<typename U, typename V>
    constexpr A(U, V) {
    }
};

// Das ist der  class template argument deduction user guide
// Der gemeinsame Type von U und V soll T von der Klasse A sein.
template<typename U, typename V>
A(U, V) -> A<std::common_type_t<U, V>>;


constexpr A x(1, 2.0);
// Der gemeinsame Type von int und double ist double
// Zur Compilezeit getestet!
static_assert(std::is_same_v<decltype(x)::value_type, double>);
// yeah

Sehr geiles feature.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress