User Defined Definitions and Auto Deletion of Templates

Say we have a class like this with a user-defined subtraction guide:

template<typename T, typename... Args> struct Foo { Foo(Args&&...) { std::cout << "just Args: " << __PRETTY_FUNCTION__ << std::endl; } Foo(Args&&..., T&&) { std::cout << "Args and T: " << __PRETTY_FUNCTION__ << std::endl; } }; template<typename... Args> Foo(Args&&...) -> Foo<Void, Args...>; 

Now try to instantiate this class: Foo foo { 10 }; . What will be the template arguments output and which constructor will be called?

After some experimentation, this depends on the compiler. Namely, gcc 7 and clang 6 (from the trunk) seem to choose an automatic manual by creating T with int and Args with an empty package, so the output is

 Args and T: Foo<T, Args>::Foo(Args&& ..., T&&) [with T = int; Args = {}] 

clang 5, on the other hand, selects a user-defined guide:

 just Args: Foo<Void, int>::Foo(Args &&...) [T = Void, Args = <int>] 

Which choice is the right one, and how can I use a custom pin index in this case?

A complete example is available on wandbox .

+5
source share
1 answer

Give up the first principles. Attempting to deduce from Foo{10} involves performing overload resolution on this set:

 template <typename T, typename... Args> Foo<T, Args...> __f(Args&&... ); // ctor #1 template <typename T, typename... Args> Foo<T, Args...> __f(Args&&..., T&&); // ctor #2 template <typename... Args> Foo<Void, Args...> __f(Args&&... ); // deduction guide 

In a function synthesized from the first constructor, T is a non-deducible context. In a function synthesized from the second constructor, Args is a non-deduced context. Therefore, none of them is viable. The deduction guide is viable, so this is the trivially best viable candidate, so we end up with Foo<Void, int> .

Once we are there, we again execute the overload resolution to select the constructor. This is more straightforward, the first of them is viable, and the second is not, therefore it must be called up.

Any other behavior is a compiler error (filed 83447 ).

+3
source

Source: https://habr.com/ru/post/1274121/


All Articles