我正在使用 C++03(真的是 CUDA nvcc,但这没关系)。我有以下一些工作代码:
template<typename T> void baz(T*);
template<typename T>
void bar() {
typedef void (*foo_t)(T*);
static const foo_t dummy = baz;
// use dummy
};
现在,我想将虚拟变量移出函数,使其成为全局变量。
第一次尝试:
template<typename T> void baz(T*);
template<typename T> typedef void (*foo_t)(T*);
template<typename T> const foo_t dummy = baz;
template<typename T>
void bar() {
// use dummy
};
这不起作用,因为 C++(至少 C++03)没有模板化 typedef:
error: "typedef" may not be specified here
error: "foo_t" is not a function or static data member
为什么 C++03 没有这个?打败我。如果我可以在一个函数中做到这一点,我不明白为什么我也不能在外面做到这一点。我认为 C++11 也没有(但是有模板化的using
,对吧?)
好的,所以我读了Template typedefs - 你的工作是什么?,并寻求接受的答案 - 使用帮助程序类。
第二次尝试:
template<typename T> void baz(T*);
template<typename T> class TemplatingHeler {
typedef void (*foo_t)(T*);
static const foo_t dummy = baz;
}
...这得到:
error: a member of type "void (*const)(T *)" cannot have an in-class initializer
第三次尝试:
template<typename T> void baz(T*);
template<typename T> class TemplatingHelper {
typedef void (*foo_t)(T*);
static foo_t dummy;
};
template<typename T> TemplatingHelper::dummy = baz;
error: name followed by "::" must be a class or namespace name
error: argument list for class template "TemplatingHelper" is missing
...和 nvcc 段错误(!)
为什么会发生这一切,我怎样才能让它发挥作用?