c++ - 在类中强制可变参数模板成员函数实例化

标签 c++ templates c++11 variadic-templates

我有一个具有可变成员函数的类:

class class_name {
  template<ArgTypes.. args>
  some_return_type memberMethod(ArgTypes... args) {
    //stuff...
  }
}

我需要在类定义 block 中强制实例化此方法。 我将方法名称放在类定义 block 之外,因为该类是由一堆宏生成的。

我尝试通过将指针复制到专门的成员函数(伪代码)来强制实例化:

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...>;

我猜这个错误是由于成员函数是可变参数模板这一事实造成的。

有什么方法可以在类定义 block 中强制可变参数模板成员函数实例化吗?

最佳答案

(重复我对 OP 的评论。)

实际问题在instate force = &Self::memberMethod<ArgTypes...>;行缺少template关键词:

instate force = &Self::template memberMethod<ArgTypes...>;

参见,例如Where and why do I have to put the “template” and “typename” keywords?

实际上,这里不需要显式模板参数[over.over]/1:

A use of an overloaded function name without arguments is resolved in certain contexts to [...] a pointer to member function for a specific function from the overload set. A function template name is considered to name a set of overloaded functions in such contexts. The function selected is the one whose type is identical to the function type of the target type required in the context.

即,因为 instate定义函数类型,编译器能够确定为名称 Self::memberMethod 选择哪个重载(此处: 模板特化) .


可能有更简单的解决方案来强制实例化函数模板,即使在类定义内部也是如此。我想到的一个是使用私有(private) typedef喜欢using dummy = integral_constant<instate, &Self::memberMethod>; (或 static constexpr instate dummy = &Self::memberMethod; )。

我很确定,但不是 100% 确定 typedef强制实例化成员函数模板。当需要该函数的定义时,函数模板被实例化,并且 ODR 表明这里是这种情况:“如果它是唯一的查找结果,则 ODR 使用其名称显示为潜在评估表达式的函数或一组重载函数的选定成员”“每个程序都应包含该程序中 odr-使用的每个非内联函数或变量的一个定义”

关于c++ - 在类中强制可变参数模板成员函数实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18355814/

相关文章:

c++ - 为什么我们需要在不分配变量的情况下强制转换它?

c++ - OCCI C++ 应用程序的 Visual Studio 调试运行时错误

c++ - 模板是否需要重载构造函数?

c++ - 引用作为参数的模板参数推导

c++ - 使用 cryptopp 库编译时收到警告

c++ - Mingw 不编译由于 "' isblank' 未在此范围内声明“错误

c++ - 无法在 C++ Visual Studio 中编译 C 文件

c++ - 带有插入符号操作的字符 XOR

c++ - C++编译错误中vector的模板

c++ - 为什么我不能使用 fstream vector ?