C++模板函数以模板类为参数

Sha*_*man 7 c++ parameters templates

我正在努力使用以下代码.基本上,我有一个类Foo和嵌套类Bar,现在我想将一个类Bar对象的指针传递给一个函数,但它不能编译.任何人都可以帮我这个吗?谢谢.

template <typename T>
struct Foo
{
    struct Bar
    {
        T data_;
    };
    Bar bar_;
};

template <typename T>
void func(Foo<T>::Bar* bar) // Why is this line wrong???
{
}

int main()
{
    Foo<int> foo;
    foo.bar_.data_ = 17;
    func(&foo.bar_);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

jos*_*mas 15

您需要具有以下签名

template <typename T>
void func(typename Foo<T>::Bar* bar) // Why is this line wrong???
Run Code Online (Sandbox Code Playgroud)

但是,这不是唯一的问题

func(&foo.bar_);
Run Code Online (Sandbox Code Playgroud)

也需要

func<int>(&foo.bar_);
Run Code Online (Sandbox Code Playgroud)

这是因为您正在调用模板化函数"func",但无法推断其类型.没有它的类型,它会给出一个错误,例如

no matching function for call to 'func(Foo<int>::Bar*)'
Run Code Online (Sandbox Code Playgroud)

  • +1.正确答案.更大的问题是:`T`无法推断,因此需要明确传递. (2认同)
  • +1我喜欢新人给出"深刻"答案!仅供参考,这里无法推断出"T"这一事实被称为**不可推导的背景**. (2认同)