gpt4 book ai didi

c++ - 在运行时选择正确的模板特化

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:36 25 4
gpt4 key购买 nike

我有

template <int i> struct a { static void f (); };

在代码的不同地方进行特化。如何调用正确的 a<i>::f对于 i只在运行时知道?

void f (int i) { a<i>::f (); } // won't compile

我不想列出 i 的所有可能值在一个大switch .

编辑:

我想到了类似的东西

#include <iostream>

template <int i> struct a { static void f (); };

struct regf {
typedef void (*F)();
enum { arrsize = 10 };
static F v[arrsize];
template < int i > static int apply (F f) {
static_assert (i < arrsize, "");
v[i] = a<i>::f;
return 0;
}
};
regf::F regf::v[arrsize];

template <int i> struct reg { static int dummy; };
template <int i> int reg<i>::dummy = regf::apply<i> ();

void f (int i) { return regf::v[i] (); }

#define add(i) \
template <> struct a<i> : reg<i> { \
static void f () { std::cout << i << "\n"; } \
};

add(1)
add(3)
add(5)
add(7)

int main () {
f (3);
f (5);
}

但它崩溃了(我是不是错过了强制实例化的东西?),而且我不喜欢那个假人不是 static const (并使用内存)当然还有 arrsize比必要的更大。


实际问题:要有一个函数generate (int i)那叫a<i>::generate ()生成类 a<i> 的实例对于 i仅在运行时给出。给出了设计(类 a<i>),它们继承自基类,并且可以随时在代码中的任何位置添加更多的 a 特化,但我不想强制所有人更改我的 generate (i)手动操作,因为这很容易被遗忘。

最佳答案

我不确定这是您可以获得的最佳解决方案,因为可能会有更好的设计,无论如何您可以使用一些元编程来触发函数的实例化和注册:

// in a single cpp file
namespace {
template <unsigned int N>
int register_a() { // return artificially added
register_a<N-1>(); // Initialize array from 0 to N-1
regf::v[N] = &a<N>::f; // and then N
return N;
}
template <>
int register_a<0>() {
regf::v[0] = &a<0>::f; // recursion stop condition
return 0;
}
const int ignored = register_a<regf::arrsize>(); // call it
}

该代码将实例化函数并注册指向静态成员函数的指针。需要假返回类型才能在静态上下文中强制执行函数(通过使用该函数初始化静态值)。

这很容易导致静态初始化失败。虽然 regf::v 没问题,但任何依赖 regf::v 且在静态初始化期间包含适当指针的代码都注定会失败。您可以使用通常的技术改进它...

根据您实际发布的点点滴滴,我的猜测是您正在尝试使用一个抽象工厂,并从每个具体工厂自动注册。有更好的方法来解决这个问题,但我认为这个答案解决了你的问题(我不确定这是否能解决你的问题)。

关于c++ - 在运行时选择正确的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5621810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com