Class template argument deduction for template type which is itself an argument for a template

Viewed 70

Is class template argument deduction supported for template types with default arguments which are used within another template type declaration? The following code does not compile with both Clang/GCC trunk, it fails on the line defining y:

#include <optional>

template <class T = char>
struct C {};

int main() {
    C x;
    std::optional<C> y;
}

(https://godbolt.org/z/SgxY90)

Modifying the code to read std::optional<C<>> y fixes the issue, but I am a bit surprised this is needed. Is this a compiler issue, or a known language limitation?

1 Answers

The compiler has to verify that what is passed to the template matches the anticipated template parameter. Now consider I were to write this with your example, where you don't see foo:

foo<C> f;

Is it a instance of CTAD, or am I passing the template itself? Since one can already pass templates as arguments to other templates.

template< template<typename> class T > struct foo {};

Allowing for CTAD in that context would make the use of C context dependent. In contrast, a template name has no other use when declaring a variable. There is no ambiguity when writing...

C c;

... that can mean something other than CTAD, so it's allowed here. But context matters when the template name is used as a template argument. C++ has a lot of context dependent constructs already, so adding more is usually a bad idea.

Related