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

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...