在派生类中绑定非静态模板化成员函数

bind non static templated member function in derived class

本文关键字:成员 函数 静态 派生 绑定      更新时间:2023-10-16
#include <functional>
#include <iostream>
class Plain {
public:
template <typename Type>
void member_function(const Type& s) {
std::cout << "Recived: " << s << std::endl;
}
};
template <typename Type>
class Templated : private Plain {
public:
};
int main() {
Plain b;
b.member_function<int>(10); // done!
Templated<int> d;
// d.member_function();  /* how to achive this */
return 0;
}

我正在尝试通过两种方法调用class Plain中的成员函数:

  1. 调用函数时创建非模板化类和填充类型
Plain p;
p.member_function<int>();
  1. 创建类和调用时传递类型,无需模板参数
Templated<int> t;
t.member_function(); // achive this

我尝试在派生类中绑定函数,例如

struct Plain{
template<typename T>
static void member_function(const T& s){std::cout << s << std::endl;}
}
template<typename T>
struct Templated : private Plain {
std::function<void(const T&)> print = Templated::Plain::member_function;
}

在那之后我能够做到

Templated t<std::string>;
t.print();

当你使用私有继承时,外部代码无法访问 Plain 中的方法,你需要在 Templated 内部有一些东西来调用 Plain 中的方法;你可以这样做,或者你可以使用公共继承并能够直接点击它。

class Plain {
public:
template <typename T>
void print(const T & s) {
std::cout << "Received: " << s << std::endl;
}
};
template <typename T>
class Templated : private Plain {
public:
void print(const T & s) {
Plain::print<T>(s);
}
};
template <typename T>
class Alternative : public Plain {};
int main() {
Templated<int> t;
t.print(3); // This could work
Alternative<int> a;
a.print(4); // As could this
return 0;
}

我找到了解决方法

#include <functional>
#include <iostream>
using namespace std::placeholders;
struct Test {
template <typename Type>
void foo(const Type&) {
std::cout << "I am just a foo..." << std::endl;
return;
}
};
template <typename T>
struct Foo {
private:
Test* obj;
public:
Foo() : obj(new Test) {}
std::function<void(const int&)> foo = std::bind(&Test::foo<T>, obj, _1);
~Foo() { delete obj; }
};
int main() {
Foo<int> me;
me.foo(10);
Test t;
t.foo<int>(89);
std::cout << std::endl;
return 0;
}