加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 实例化和名称绑定点

发布时间:2020-12-16 09:58:06 所属栏目:百科 来源:网络整理
导读:我对以下示例的实例化问题感到困惑: #include iostreamvoid f(int){std::cout"int"std::endl;}//3template typename Tvoid g(T t){ f(t);//4}void f(double){std::cout"double"std::endl;}int main(){ gint(1);//1.point of instantiation for gint gdouble
我对以下示例的实例化问题感到困惑:

#include <iostream>

void f(int){std::cout<<"int"<<std::endl;}//3

template <typename T>
void g(T t)
{
    f(t);//4
}

void f(double){std::cout<<"double"<<std::endl;}

int main()
{
    g<int>(1);//1.point of instantiation for g<int>
    g<double>(1.1);//2.point of instantiation for g<double>,so f(double) is visible from here?
    return 0;
}

我虽然f是一个从属名称,但是1是g<的实例化点. int>和2.是g< 2的实例化点. double>,所以对于g(1.1),f(double)是可见的,但输出是

int
int

如果我在3处评论f(int)的声明,gcc报告错误(不是惊讶),并指出f(t)在4是实例化点(惊讶!!).

test.cpp: In instantiation of ‘void g(T) [with T = int]’:
test.cpp:16:10:   required from here
test.cpp:9:5: error: ‘f’ was not declared in this scope,and no    declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
  f(t);
     ^

任何人都可以为我清除实例化和名称绑定的概念吗?

解决方法

f(t)是依赖的非限定函数调用表达式,因此只有在定义上下文中找到的函数和通过ADL找到的函数才是候选函数. f(int)在定义上下文中是可见的,但不是f(double),因此对于两个调用,重载决策都解析为f(int).

ADL无法找到f(double),因为内置类型没有关联的类或名称空间.如果传入类类型的参数,并且f类型的重载采用此类型,则ADL将能够找到它.例如:

void f(int);

template <typename T>
void g(T t)
{
    f(t);
}

class A {};
void f(double);
void f(A);

int main()
{
    g(1);   // calls f(int)
    g(1.1); // calls f(int)
    g(A{}); // calls f(A)
}

调用f(A)是因为它位于全局命名空间中,而A的关联命名空间集是全局命名空间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读