接下来的问题,应该取一个函数的地址触发一个函数的编译?以this example为例:
template <typename T> void foo(T&& x) { x.func(); } int main() { auto bar = &foo<int>; }
我测试的所有编译器都失败了,例如:
Request for member
func
inx
,which is of non-class typeint
但是,如果我只是定义foo并且不声明它,那么代码编译得很好.有人可以向我提供官方消息来源,了解是否需要获取函数的地址需要编译吗?
解决方法
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.
函数名称绝对不是未评估的操作数(例如sizeof,decltype),它出现在表达式中,因此可能会对其进行评估.然后第二个只需要一个非内联定义,或每个翻译单元中相同的内联定义.