使用CRTP获取方法重载的类型



我一直在想,是否有可能与c++ 20,以某种方式获得方法重载的类型到元组:

template<typename CRTP>
struct Template {
// ERROR! But how to make it work? Some metaprogramming magic?
static inline constexpr std::tuple t{&CRTP::f...};
};
struct S : Template<S> {
void f(int) { }
void f(bool) { }
};

我希望元组有效地包含:&S::f(int), &S::f(bool).

编辑:我们的想法是能够有多个不同的类可以利用模板:

struct S1 : Template<S> {
void f(int) { }
void f(bool) { }
};
struct S2 : Template<S> {
void f(std::string) { }
void f(double) { }
void f(std::vector<unsigned>) {}
void f(SomeOtherType) {}
};

如果您需要某种反射-查找所有方法有一个给定的名字,然后没有,在c++中(还)没有反射。您可以像这里描述的那样向编译器添加一次传递,但这不是语言的一部分。

也就是说,您可以构建一个先验的表,以便稍后查询,如下面的示例所示。
#include <tuple>
#include <iostream>
template<typename CRTP>
struct Template {
typedef void (CRTP::*IntFn)(int);
typedef void (CRTP::*BoolFn)(bool);
static inline constexpr std::tuple<IntFn,BoolFn> t{&CRTP::f,&CRTP::f};
};
struct S : Template<S> {
void f(int i) { std::cout << "int " << i << std::endl; }
void f(bool b) { std::cout << "bool " << (b?"true":"false") << std::endl; }
};
int main() {
S s;
(s.*std::get<0>(S::t))(1);
(s.*std::get<1>(S::t))(1);
}

生产

Program stdout
int 1
bool true

Godbolt: https://godbolt.org/z/Gbjj6Y7KK

最新更新