gpt4 book ai didi

c++ - 在调用函数上实现 C++ 转换

转载 作者:行者123 更新时间:2023-11-30 04:44:43 24 4
gpt4 key购买 nike

我想使用 C++11/14 实现对参数进行额外转换的专门调用。基本上,这个想法是:

struct Foo {
private:
void* ptr;
public:
void* get();
};


template <typename F, typename... Args>
auto convert_invoke(F&& f, Args&&... args) {
// not sure how to do here with C++11/14
}

// caller side
int simple(float* f1, size_t N) {
// doing something interesting
}

// ideally I would like to call the following:
Foo foo;
size_t n = 10;

convert_invoke(simple, foo, n); // internally calls simple((float*)foo.get(), n);

这里的想法是当参数是Foo类型时,我会做一些特殊的处理,比如获取void*指针并将其转换为定义的相应参数类型在简单中。我如何在 convert_invoke 中实现它?

最佳答案

你可以这样做:

// Wrapper to allow conversion to expected pointer.
struct FooWrapper
{
void* p;

// Allow conversion to any pointer type
template <typename T>
operator T* () { return (T*) p; }
};

// Identity function by default
template <typename T>
decltype(auto) convert(T&& t) // C++14
// auto convert(T&& t) -> decltype(std::forward<T>(t)) // C++11
{ return std::forward<T>(t); }

// special case for Foo, probably need other overloads for Foo&& and cv versions
auto convert(Foo& foo) { return FooWrapper{foo.get()}; }

// Your function
template <typename F, typename... Args>
auto convert_invoke(F&& f, Args&&... args) {
return f(convert(std::forward<Args>(args))...);
}

Demo

关于c++ - 在调用函数上实现 C++ 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600701/

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