gpt4 book ai didi

C++模板代码解释

转载 作者:行者123 更新时间:2023-11-28 05:37:33 25 4
gpt4 key购买 nike

<分区>

template <typename Function>
struct function_traits
: public function_traits<decltype(&Function::operator())> {
}; //1 why function_traints inherit from itself?

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
typedef ReturnType (*pointer)(Args...);
typedef std::function<ReturnType(Args...)> function;
}; //2 this class do nothing just typedef type ?

template <typename Function>
typename function_traits<Function>::function
to_function (Function & lambda) {
return static_cast<typename function_traits<Function>::function>(lambda);
}

template <typename Lambda>
size_t getAddress(Lambda lambda) {
auto function = new decltype(to_function(lambda))(to_function(lambda));
//3 func is std::function pointer,this conversion is ok?
void * func = static_cast<void *>(function);
return (size_t)func;
}

int f(int, int) { return 1; }
int g(int, int) { return 2; }
std::function<int(int, int)> lambda1 = [](int a, int b)->int
{
return 1;
};
std::function<int(int, int)> lambda2 = [](int a, int b)->int
{
return 1;
};

void test(std::function<int(int, int)> const& arg,const char* info)
{
std::cout << "test function: ";
std::cout << (void*)getAddress(arg) << " " << info << std::endl;
}

int main()
{
test(lambda1,"lambda1");
test(lambda1,"lambda1");
test(lambda2,"lambda2");
test(lambda2,"lambda2");
test(std::function<int(int, int)>(std::plus<int>()),"plus");
test(std::function<int(int, int)>(std::minus<int>()),"minus");
test(std::function<int(int, int)>(f),"f");
test(std::function<int(int, int)>(g),"g");
}

1 为什么 function_traints 继承自自身?

我知道这是 Curiously recurring 模板模式。 function_traints 同时被编译为两个不同的类。

2 第二个类什么都不做只是 typedef 类型?

是的,只是为了方便

3 func是std::函数指针,这样转换可以吗?

[待办事项]

4 主函数结果为:

test function: 0x7f9440407f50 lambda1
test function: 0x7f9440407f80 lambda1
test function: 0x7f9440407fb0 lambda2
test function: 0x7f9440407fe0 lambda2
test function: 0x7f9440408010 plus
test function: 0x7f9440408040 minus
test function: 0x7f9440408070 f
test function: 0x7f94404080a0 g

上面这些函数有错吗?我不能用它来检查两个函数是否相等?

[待办事项]

你能解释一下上面的代码吗?非常感谢!

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