模板参数推导失败,并带有默认模板参数 [英] Template argument deduction failed with default template parameter

查看:106
本文介绍了模板参数推导失败,并带有默认模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <cstdint>
#include <iostream>

class MyBar {
public:
    void print() {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

template <class Bar = MyBar>
class Foo{
public:
    Foo(const char* name, const uint32_t i) {
        Bar b;
        b.print();
    }
};

int main(int argc, char** argv) {
    auto pFoo1 = new Foo("abc", 3);
}

编译器给了我:

template_ctor.cpp: In function ‘int main(int, char**)’:
template_ctor.cpp:21:31: error: class template argument deduction failed:
  auto pFoo1 = new Foo("abc", 3);
                               ^
template_ctor.cpp:21:31: error: no matching function for call to ‘Foo()’
template_ctor.cpp:14:2: note: candidate: template<class Bar> Foo(const char*, uint32_t)-> Foo<Bar>
  Foo(const char* name, const uint32_t i) {
  ^~~
template_ctor.cpp:14:2: note:   template argument deduction/substitution failed:
template_ctor.cpp:21:31: note:   candidate expects 2 arguments, 0 provided
  auto pFoo1 = new Foo("abc", 3);

我放<> 新Foo 之后,它将进行编译。

As soon as I put <> after new Foo, it compiles.

起初,我以为<> ; 是强制性的,以提示编译器使用默认模板参数,但随后我注意到,如果我删除 const char * name ,然后我不这样做't pass in abc ,它也可以编译。

At first, I thought <> is mandatory to hint the compiler to use the default template parameter, but then I noticed that if I drop const char* name and then I don't pass in "abc", then it also compiles.

现在,我很困惑。

推荐答案

这应该可以编译,并且基本上是 gcc错误85883 。此问题已在固定在树干上

This should compile, and is basically gcc bug 85883. This has been fixed on trunk:

struct MyBar;

template <class Bar = MyBar>
class Foo{
public:
    Foo(const char* name, int i);
};

auto pFoo1 = new Foo("abc", 3);

该示例在gcc 8.2上失败,但在9上编译。

The example fails on gcc 8.2, but compiles on 9.

这篇关于模板参数推导失败,并带有默认模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆