简体   繁体   English

为什么 C++17 class 模板参数推导失败?

[英]Why C++17 class template argument deduction fails?

C++17 offers class template argument deduction . C++17 提供class 模板参数推导

I have the following small example (you can paste into onlinegdb with C++17 enabled, no problem) where it fails under certain circumstances but I do not know why:我有以下小示例(您可以在启用 C++17 的情况下粘贴到 onlinegdb,没问题)在某些情况下它会失败,但我不知道为什么:

#include <iostream>
enum class Res{
    ResA,
    ResB
};

template<Res>
class B{   
};

template<Res T>
class A{
    //If I remove this construtor, template type deduction will not work anymore
    public:   
    A(B<T> b){       
    }
};

template<>
class A<Res::ResA>{
    public:
    A(B<Res::ResA> b){
        std::cout<<"A res A\n";
    }  
};

int main()
{
    B<Res::ResA> b;
    A a(b);
}

The code above works.上面的代码有效。 But as soon as I change A 's constructor to be the any other constructor than in the template specializations, the template argument deduction will not work and A has to be initialized by A<Res::ResA> .但是,一旦我将A的构造函数更改为模板特化之外的任何其他构造函数,模板参数推导将不起作用,并且A必须由A<Res::ResA>初始化。

I am at loss.我不知所措。 Why could this be the case?为什么会这样? Thank you for any ideas!谢谢你的任何想法!

Generated CTAD are only from primary template.生成的CTAD仅来自模板。

If you don't want to add that constructor in primary template, you can still provide custom deduction guide.如果您不想在主模板中添加该构造函数,您仍然可以提供自定义推导指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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