代码之家  ›  专栏  ›  技术社区  ›  Seymore Glass

模板不工作的默认参数

  •  1
  • Seymore Glass  · 技术社区  · 2 年前

    我有一个使用声明的嵌套模板链。它看起来像这样:

    template <typename A, typename B, typename C, typename D>
    class Foo {
    public:
        Foo() : value{0} {};
    
        template <typename AC, typename BC, typename CC, typename DC>
        Foo(const Foo<AC, BC, CC, DC>& rhs) : value{rhs.value} {}
    
        template <typename AC, typename BC, typename CC, typename DC>
        Foo& operator=(const Foo<AC, BC, CC, DC>& rhs) {
            value = rhs.value;
            return *this;
        }
    
        template <typename F>
        F convertTo() {
            return F(*this);
        }
    
        C value;
    };
    
    template <typename ThingC, typename ThingD>
    using Bar = Foo<int, float, ThingC, ThingD>;
    
    template <typename ThingD = long double>
    using Bif = Bar<char, ThingD>;
    

    以下情况给我带来了麻烦:

    int main(int argc, char* argv[]) {
        Bif bifDefault;
        Bif<long> bifLong;
    
        Bif<unsigned> bifUnsigned = bifDefault.convertTo<Bif<unsigned>>();
        Bif<long double> bifLongDouble = bifLong.convertTo<Bif>(); // ERROR...
        // expected a type, got 'Bif'
    }
    

    我在 F convertTo 生产线: template argument deduction/substitution failed

    还有最奇怪的错误,在错误行:

    no instance of function template "Foo<A, B, C, D>::convertTo [ with A=int, B=float, C=char, D=long int]" matches the argument list
    

    D=长整型 哦!这是怎么回事?把它改成双倍也不行。显然,默认模板参数正在传播到函数,但它正在这样做 错误的 对于long double,即使类型正确也不起作用。

    我怎样才能让它工作?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Stephen Newell    2 年前

    问题是 Bif 不是一种类型,而是一种 template d型。当你申报时,你是在逃避惩罚 bifDefault 因为 CTAD ,但打电话时不适用 convertTo (您没有传递非类型 样板 参数)。替换为时,代码会按预期编译 bifLong.convertTo<Bif<>>()

    推荐文章