gpt4 book ai didi

c++ - 非类型模板参数……那是一个模板! (C++)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:19 24 4
gpt4 key购买 nike

我主要是想为通用 C 函数生成一个包装器,而无需手动指定类型。所以我有一个带有固定原型(prototype)的回调,但我需要根据包装函数的类型在包装器中做一些特殊代码......所以基本上我正在考虑在类模板中使用静态方法将我的函数包装到符合标准的接口(interface)中,例如:

// this is what we want the wrapped function to look like
typedef void (*callback)(int);
void foobar( float x ); // wrappee

// doesn't compile
template< T (*f)(S) > // non-type template param, it's a function ptr
struct Wrapper
{
static void wrapped(int x)
{
// do a bunch of other stuff here
f(static_cast<S>(x)); // call wrapped function, ignore result

}
}

然后我想做类似的事情:

AddCallback( Wrapper<foobar>::wrapped );

但是,问题是我不能直接在 Wrapper 模板中的函数参数中使用“S”,我必须首先将其列为参数:

template< class T, class S, T (*f)(S) >
struct Wrapper
// ...

但这意味着使用起来要痛苦得多(Wrapper<void,float,foobar>::wrapped),理想情况下我只想将函数指针传递到那里并让它自动计算出参数的类型(和返回类型)。需要明确的是,在包装函数内部,我需要引用函数指针的类型(因此我确实需要 S 或 T 的某种等价物)。

有没有办法做到这一点?

最佳答案

您可能希望考虑的一件事是使用 LLVM 或类似工具在运行时生成适当的蹦床函数。或者这是一个静态解决方案:

#include <iostream>

void f(float f) { std::cout << f << std::endl; }

template<typename T, typename S> struct static_function_adapter {
template<T(*f)(S)> struct adapt_container {
static void callback(int v) {
f(static_cast<S>(v));
}
};

template<T(*f)(S)> adapt_container<f> adapt() const {
return adapt_container<f>();
}
};

template<typename T, typename S> struct static_function_adapter<T, S> get_adapter(T (*)(S)) {
return static_function_adapter<T, S>();
}

#define ADAPTED_FUNCTION(f) (&get_adapter(f).adapt<f>().callback)

int main() {
void (*adapted)(int) = ADAPTED_FUNCTION(f);
adapted(42);
return 0;
}

get_adapter 函数允许我们推断参数和返回类型; adapt() 然后将其转换为在实际函数上参数化的类型,最后我们在回调中得到一个静态函数。

关于c++ - 非类型模板参数……那是一个模板! (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1133038/

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