Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deduction guides, templates and subobjects: which compiler is right?

Consider the following snippet:

struct S {
    S() {}

    template<typename B>
    struct T {
        T(B &&) {}
    };

    template<typename B>
    T(B &&) -> T<B>;
};

int main() {
    S::T t{0};
}

Clang accepts it while GCC rejects the code with the following error:

prog.cc:10:5: error: deduction guide 'S::T(B&&) -> S::T' must be declared at namespace scope

Is this valid code? Which compiler is right, GCC or Clang?

like image 994
skypjack Avatar asked May 30 '18 09:05

skypjack


People also ask

What is a deduction guide?

Template deduction guides are patterns associated with a template class that tell the compiler how to translate a set of constructor arguments (and their types) into template parameters for the class. The simplest example is that of std::vector and its constructor that takes an iterator pair.

What is template argument deduction in C++?

Class Template Argument Deduction (CTAD) is a C++17 Core Language feature that reduces code verbosity. C++17's Standard Library also supports CTAD, so after upgrading your toolset, you can take advantage of this new feature when using STL types like std::pair and std::vector.


1 Answers

According to http://en.cppreference.com/w/cpp/language/class_template_argument_deduction

User-defined deduction guides must name a class template and must be introduced within the same semantic scope of the class template (which could be namespace or enclosing class) and, for a member class template, must have the same access, but deduction guides do not become members of that scope.

So clang seems correct.

like image 134
Jarod42 Avatar answered Oct 23 '22 07:10

Jarod42