简体   繁体   中英

Class Template Argument Deduction in member variables

Expanded version here .

We can create objects of class templates that have default template parameters without typing angle brackets:

int main()
{
    std::less a;
}

But we can't do that for member variables:

struct S
{
    std::less a; // I want only type std::less<void> here
};

It looks like the first case works due to CTAD but why can't compiler deduce std::less<void> in the second case? Maybe we shouldn't apply CTAD there but provide different mechanism.

Is this considered a bug in the standard? Is there a proposal to fix it?

My use case:

I have a class template which provides default argument, like this:

template <typename T = int>
class Foo {};

The template parameter is an expert-only feature that I myself never use but it is there for those 1% of experts who want that total flexibility. Now for other 99% I want to hide the fact that Foo is actually a class template but it doesn't work because users have to type Foo<> when declaring it as a member variable, current solution is this:

template <typename T = int>
class BasicFoo {};

using Foo = BasicFoo<>;

But it complicates implementation code and is not elegant at all.

No, it is not a bug. It is because there could be different constructors called for the same member variable (called through class' constructor init list), potentially yielding different deduction result.

To prevent the potential for such conflict, you have to provide template arguments to non-static members. (Static members are not a problem, because there will a be a single constructor call for them)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM