未通过模板函数查找

BЈо*_*вић 1 c++ templates language-lawyer

考虑以下示例.

#include <iostream>
#include <boost/optional.hpp>

template < typename A >
int boo( const boost::optional< A > &a );

template < typename A >
int foo( const A &a )
{
    return boo( a );
}

template < typename A >
int boo( const boost::optional< A > & )
{
    return 3;
}


int main()
{
    std::cout << "foo = " << foo( 3 ) << std::endl;
    std::cout << "boo = " << boo( 3 ) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

使用g ++ 4.3.0进行编译会引发下一个编译错误:

dfg.cpp: In function ‘int main()’:
dfg.cpp:25: error: no matching function for call to ‘boo(int)’
dfg.cpp: In function ‘int foo(const A&) [with A = int]’:
dfg.cpp:24:   instantiated from here
dfg.cpp:12: error: no matching function for call to ‘boo(const int&)’
Run Code Online (Sandbox Code Playgroud)

我应该做些什么(如果可能的话,使用C++标准的参考资料)?为什么会这样,我该如何解决?

编辑

修复是在以下位置创建正确的类型foo:

template < typename A >
int foo( const A &a )
{
    const boost::optional< A > optA( a );
    return boo( optA );
}
Run Code Online (Sandbox Code Playgroud)

但问题仍然存在:为什么它不是自动创建的?

Naw*_*waz 5

return boo( a );
Run Code Online (Sandbox Code Playgroud)

这里的类型aint,并且没有boo接受类型的参数的名称的函数int.因此,您会看到此错误:

dfg.cpp:25:错误:没有匹配函数来调用'boo(int)'

即使int可以隐式转换为boost::optional<int>,编译器也无法boost::optional<T>从调用站点推断出模板参数.这是非推断的上下文之一,您明确需要提及类型,

   return boo<A>(a);
Run Code Online (Sandbox Code Playgroud)

该标准以14.8.2.1美元计价,

如果模板参数未在函数模板的任何函数参数中使用,或者仅在非推导的上下文中使用,则无法从函数调用推断出其对应的模板参数,并且必须明确模板参数指定的.