Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
575 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...