gpt4 book ai didi

c++ - 获取模板化函数的地址是否应该触发其编译?

转载 作者:可可西里 更新时间:2023-11-01 18:38:59 26 4
gpt4 key购买 nike

我得到了 this question 的官方答复decltype 应该 触发函数编译。事实上,声明但未定义的函数的 decltype 是合法的。

下一个问题,获取函数的地址是否应该触发函数的编译?取this example :

template <typename T>
void foo(T&& x) { x.func(); }

int main()
{
auto bar = &foo<int>;
}

我测试过的所有编译器都失败并出现如下错误:

Request for member func in x, which is of non-class type int

但是,如果我只定义 foo 并且不声明它,则代码可以正常编译。有人可以向我提供有关获取函数地址是否需要编译的官方资源吗?

最佳答案

3.2/2:

An expression is potentially evaluated unless it is an unevaluated operand (Clause 5) or a subexpression thereof. ... A non-overloaded function whose name appears as a potentially-evaluated expression or a member of a set of candidate functions, if selected by overload resolution when referred to from a potentially-evaluated expression, is odr-used, unless it is a pure virtual function and its name is not explicitly qualified.

然后 3.2/3:

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see 12.1, 12.4 and 12.8). An inline function shall be defined in every translation unit in which it is odr-used.

函数名称绝对不是未求值的操作数(例如 sizeofdecltype),并且它出现在表达式中,因此可能会求值。然后第二个需要在每个翻译单元中恰好有一个非内联定义,或相同的内联定义。

关于c++ - 获取模板化函数的地址是否应该触发其编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38402133/

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