c++ - 模板特化的成员函数类型

标签 c++ function templates

我正在研究函数类型在模板特化中的使用,我想知道是否有成员函数类型这样的东西(不谈论成员函数指针)。

导致我提出这个问题的案例可以用一个例子更好地解释...

template< typename FunctionType >
struct Function; // Undefined

// Specialize for functions with 0 parameter...
template< typename ReturnType >
struct Function< ReturnType() > // Notice the unusual syntax here...
{
    // Function pointer that fits the signature of the template...
    ReturnType (*m_pointerToFunction)();
};

// Specialize for functions with 1 parameter...
template< typename ReturnType, typename ParameterType >
struct Function< ReturnType(ParameterType) >
{
    ReturnType (*m_pointerToFunction)(ParameterType);
};

// ... etc up to a certain number of parameter.

// To use this template:
void SomeFunctionTakingNoParameter()
{
}

Function< void() > test;
test.m_pointerToFunction = SomeFunctionTakingNoParameter;

现在我想做的是为成员函数创建专门化。我尝试的第一件事是:

template< typename ReturnType, typename ObjectType, typename ParameterType >
class Function< ObjectType, ReturnType(ParameterType) >
{
    ReturnType (ObjectType::*m_memberFunctionPointer)(ParameterType);
};

我这样使用它:

struct Object
{
    void DoSomething()
    {
    }
};
Function< Object, void() > function;
function.m_memberFunctionPointer = &Object::DoSomething;

我必须向模板提供 2 个参数(对象类型和签名)。我想看看是否有一种方法可以在一个参数中完成所有操作。

下一位编译不通过,但我想知道语言中是否有类似的东西?

template< typename ObjectType, typename ReturnType >
struct Function< ObjectType::ReturnType() >
{
    ReturnType (ObjectType::*m_memberFunctionPointer)();
};
Function< Object::void() > function;
function.m_memberFunctionPointer = &Object::DoSomething;

最佳答案

语法 void(Object::*)()定义一个指向成员函数的指针类型。 C++ 中没有成员函数类型。

理论上,您可以使用 std::remove_pointer<void(Object::*)()>::type 获得一个成员函数 类型,但这不是有效的 C++。 boost::remove_pointer 的文档记下这一点。

指向成员函数的指针 类型 T (C::*)()是通过组合一个函数类型T()产生的使用指向成员的指针类型 T C::* .参见 this answer了解这种组合的工作原理。

您可以使用简单的辅助模板执行此组合:

template<typename C, typename T>
struct PointerToMember
{
    typedef T C::* Type;
};

typedef PointerToMember<Object, void()>::Type Type; // void(Object::*)()

这在扩展 Function 时可能很有用支持指向成员的指针。

关于c++ - 模板特化的成员函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184121/

相关文章:

javascript - 单击 html 中的链接不会将我重新路由到正确的页面

c++ - 推导(非)模板类型的签名

c++ - 将模板化的 std::array<std::vector<T>, N> 放入构造函数初始化列表中

android - OpenGL ES 有不同的 UV 坐标?

c++ - 尝试读取二进制文件 C++ 时出现问题

angular - 这个函数的签名是什么意思?

javascript - 如何缩短 JavaScript if/else 语句?

c++ - 模板模板代码不起作用

c++ - 求圆内坐标的角度

c++ - 如何强制编译器使用显式复制构造函数?