gpt4 book ai didi

c++ - 模板链接错误

转载 作者:行者123 更新时间:2023-11-28 08:11:35 26 4
gpt4 key购买 nike

我有一个标题,其中放置了函数模板的定义:

template <typename FT, typename std::enable_if< !std::is_array<FT>::value, int >::type =0 >
int fieldRW(lua_State* l, FT* ptr, bool write){ return scalarFieldRW<FT>(l, ptr, write); }

在 .cpp 单元中,我得到一个指向此模板函数的指针,我希望编译器实例化该模板:

typedef int (*_fieldRW)(lua_State*, void*, bool);
int dummy=3;
_fieldRW aFunctionPointer=_fieldRW(fieldRW<decltype(dummy)>);

一切都编译。但是我收到以下链接时错误:

/home/pisto/sorgenti/hopmodv4/src/fpsgame/server.cpp:39: undefined reference to `int fieldRW(lua_State*, int*, bool)'

请注意,编译器正确地选择了 header 中定义的模板(因为它添加了模板的默认第二个参数),但显然它无法实际实例化模板。

编辑:这看起来绝对像一个错误。查看这些测试:http://pastebin.com/5Yjsv47H另外,这可能是 g++ 中的错误的另一个线索是,如果我这样做:

int main() {
int dummy=3;
int (*inted)(int*)=asd<decltype(dummy)>;
int (*voided)(void*)=(int (*)(void*))asd<decltype(dummy)>;
voided(&dummy);
}

g++ 警告未使用的变量 inted 但可以很好地编译。

最佳答案

答案可能是函数指针转换规范中的一个微妙之处:

The standard says in [expr.reinterpret.cast] "A function pointer can be explicitly converted to a function pointer of a different type. The effect of calling a function through a pointer to a function type (8.3.5) that is not the same as the type used in the definition of the function is undefined."

So I think the program has undefined behaviour. Because you never call asd as part of a valid expression it doesn't need to be instantiated.

Clang++ fails in the same way as G++ 4.6, but it works with G++ 4.7

(感谢 Jonathan Wakely)

关于c++ - 模板链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8943782/

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