【发布时间】:2013-08-21 11:08:37
【问题描述】:
我有一个具有可变成员函数的类:
class class_name {
template<ArgTypes.. args>
some_return_type memberMethod(ArgTypes... args) {
//stuff...
}
}
我需要在类定义块内强制实例化此方法。 我在类定义块之外放掉了方法名,因为这个类是由一堆宏生成的。
我尝试通过复制指向专用成员函数的指针(伪代码)来强制实例化:
template<typename Self, typename RetType, typename... ArgTypes>
struct force_instantation_imlp<Self, RetType, type_placeholder, type_placeholder<ArgTypes...>> {
force_instantation_imlp() {
using instate = RetType (Self::*)(ArgTypes...);
instate force = &Self::memberMethod<ArgTypes...>;
}
};
class class_name {
template<ArgTypes.. args>
some_return_type memberMethod(ArgTypes... args) {
//stuff...
}
force_instantation_imlp<class_name, some_return_type, rest_of_types_deduced_from_context> force_virtual_instantation;
}
type_placeholder 只是一个“冻结”参数包的帮助模板。
不幸的是,这给了我一个编译错误
error: expected primary-expression before ‘...’ token instate force = &Self::memberMethod<ArgTypes...>;
我猜这个错误是由于成员函数是可变参数模板这一事实造成的。
有没有办法在类定义块中强制可变模板成员函数实例化?
【问题讨论】:
-
您可以只使用
auto而不是instate:auto force = &Self::memberMethod<ArgTypes...>;。这样您就不用编写using来定义类型了。 -
您是否尝试过在
instate force = &Self::memberMethod<ArgTypes...>;中省略显式模板参数? -
@Nawaz 好点。我还是没有养成c++11的习惯。问题仍然存在。
-
...我想你错过了
template:&Self::template memberMethod<ArgTypes...>; -
@Marcin
instate force = &Self::memberMethod;起作用的原因是编译器可以在该上下文中根据所需的类型(instate的类型)来选择重载。对于decltype,这当然是不可能的。因此,在 decltype 中,您需要强制转换或显式指定重载(例如,使用显式模板参数)。这当然是没用的,因为如果您可以访问这些参数类型,您可以直接指定没有decltype的函数类型。
标签: c++ templates c++11 variadic-templates