gpt4 book ai didi

c++ - 获取重载函数模板的地址是可能的,有时

转载 作者:可可西里 更新时间:2023-11-01 17:57:36 26 4
gpt4 key购买 nike

gcc 4.9.0 上:

#include <iostream>
#include <map>

struct A
{
typedef int type;
};

template<typename T> void foo(T*) { std::cout << "a" << std::endl; }
template<typename T> void foo(typename T::type*) { std::cout << "b" << std::endl; }

template<typename T>
struct identity
{
typedef T type;
};

template<typename T> void bar(T*) { std::cout << "a" << std::endl; }
template<typename T> void bar(typename identity<T>::type*) { std::cout << "b" << std::endl; }

int main()
{
//auto f = foo<A>; // ambiguous
foo<A>(0); // prints "b", as the second overload is more specific

auto b = bar<A>; // fine
bar<A>(0); // prints "b", as the second overload is more specific (?)
b(0); // prints "b"

return 0;
}

关于为什么在第二种情况下地址可以被占用的任何线索?

最佳答案

auto 的推导与模板推导相同。来自 [dcl.spec.auto]:

When a variable declared using a placeholder type is initialized, [...], the deduced return type or variable type is determined from the type of its initializer. If the placeholder is the auto type-specifier, the deduced type is determined using the rules for template argument deduction. If the placeholder is the auto type-specifier, the deduced type is determined using the rules for template argument deduction.

所以当我们有:

auto f = foo<A>;
auto b = bar<A>;

我们正在执行类型推导,就好像我们调用了(借用 T.C. 的用词):

template <typename M> void meow(M );
meow(foo<A> );
meow(bar<A> );

并分别使用推导出的类型M作为fb的类型。

但是,根据 [temp.deduct.type],强调我的:

If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

The non-deduced contexts are:
— [...]
— A function parameter for which argument deduction cannot be done because the associated function argument is a function, or a set of overloaded functions (13.4), and one or more of the following apply:
    — more than one function matches the function parameter type (resulting in an ambiguous deduction), or
    — no function matches the function parameter type, or
    — the set of functions supplied as an argument contains one or more function templates.
— [...]

在这两种情况下,参数都是一组重载函数,其中包含一个或多个函数模板 - 这使其成为非推导上下文,因此模板参数推导失败。因此,clang 拒绝这两个初始化是正确的。

关于c++ - 获取重载函数模板的地址是可能的,有时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31392020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com