考虑以下头文件:
// Foo.h
class Foo {
public: template <typename T> void read(T& value);
};
似乎分配了一个指针到Foo::read<T>
在类的构造函数中,然后声明变量,导致实例化:
// Foo.cc
#include "Foo.h"
template <typename T>
void Foo::read(T& value) { /* do something */ }
template <typename T> struct Bar {
Bar<T>() { void (Foo::*funPtr)(T&) = &Foo::read<T>; }
};
static Bar<int > bar1;
static Bar<long > bar2;
static Bar<float> bar3;
该解决方案可靠/便携/符合标准吗? (它至少适用于 Intel 和 GNU 编译器。)
如果您想知道为什么不简单地使用template Foo::read<int>(int&);
请参阅this question .
最佳答案
是的,您的解决方案是可移植的。这是一种不同的方式
template <typename T, T> struct user { };
template <typename T> struct Bar {
typedef user< void (Foo::*)(T&), &Foo::read<T> > user_type;
};
现在无论何时Bar<T>
被隐式实例化,它将隐式实例化 Foo::read<T>
。不需要创建任何对象。
关于c++ - 构造函数内指向模板成员函数的指针是否会强制实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5728512/