模板函数成员作为模板参数

问题描述 投票:0回答:1

我想用相同的输入类型序列调用不同的模板成员函数,为了减少样板代码,我尝试实现一个调度程序函数,

for_each_type


struct A {
    template<typename T>
    void a() {}

    template<typename T>
    void b() {}

    template<template<typename> class Fn>
    void for_each_type() {
        Fn<char>();
        Fn<int>();
        Fn<float>();
        ...
    }
};

int main() {
    A obj;

    // This doesn't compile
    // obj.for_each_type<A::a>();
    // obj.for_each_type<A::b>();
}

这样的功能可以实现吗?

c++ templates template-meta-programming template-templates
1个回答
0
投票

您不能使用模板模板参数来标识函数模板,但您可以提供类模板,该类模板又返回指向该函数的正确实例的函数指针。

示例:

struct A {
    template<typename T>
    void a() {
        std::cout << "a called\n";
    }
    template<class T>
    struct a_caller {
        auto operator()() { return &A::a<T>; }
    };

    template<typename T>
    void b() {   
        std::cout << "b called\n";
    }
    template<class T>
    struct b_caller {
        auto operator()() { return &A::b<T>; }
    };

    template<template<class> class Fn>
    void for_each_type() {
        (this->*Fn<char>{}())();
        (this->*Fn<int>{}())();
        (this->*Fn<float>{}())();
    }
};

然后,您需要提供类模板

a_caller
b_caller

int main() {
    A obj;

    obj.for_each_type<A::a_caller>();
    obj.for_each_type<A::b_caller>();
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.