c++ - 模板链接错误

标签 c++ g++ c++11

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

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/

相关文章:

c++ - 在 C++03 中模拟显式转换

c++ - 为什么我们不能在未评估的上下文中使用大括号初始化程序?

c++ - 简单继承获取 Vtable 错误

c++ - 使用 emscripten 从 C++ webassembly 代码将输出写入 json

c++ - 在 linux 下的 c++ 程序中包含 amp.h 库

c++11 在不同类之间共享固定大小的数组

c++ - clang 不应该抑制来自/usr/local/include 中头文件的警告吗?

javascript - Duktape中,如何将一个JS源文件内容转为字节码

c++ - 为什么在我的计算机上没有 g++ 中的 -O2 时 sqrt 会变得更快?

multithreading - Mac OS-X 10.5上的g++ 4.6 std::thread错误