gpt4 book ai didi

c++ - 是否可以从较晚的模板参数推断或默认较早的模板参数?

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

我的目标是 c++11(g++ 4.7 版)和 c++0x(icpc 12.something,intel c++ 编译器)。有一天我可能会使用 clang。

我有以下数据结构:

template<typename mydata_t>
struct mystruct {
template<typename mycmp_t,
int (*cmp)(const mydata_t &, const mycmp_t &)
>
void insert(const mydata_t &value, const mycmp_t &key) {
// use key to search for where to put value, by calling
// cmp(item_already_in_mystruct, key);
}
};

想法是客户端可以做

int double_double_compare_fun(const double &d1, const double &d2) { ...; }
int double_int_compare_fun(const double &d, const int &i) { ...; }
int main(void) {
struct mystruct<double> s;
s.insert<double, double_double_compare_fun>(4.2, 4.2);
s.insert<int, double_int_compare_fun>(6.2, 6);
}

或者一些不那么愚蠢的东西。

我目前正在使用它,而且还不算太疯狂。但我希望我能做得更好。

double_double_compare_fundouble_int_compare_fun已经命名了第二个参数的类型。所以在我的脑海里,我想有一些方法可以让编译器将第一个模板参数推断为 insert .我很想能够说

s.insert<double_double_compare_fun>(4.2, 4.2);
s.insert<double_int_compare_fun>(6.2, 6);

并且有mycmp_tcmp 的签名中推断出或来自 key 的类型.或者,如果 mycmp_t 我会很高兴可以默认为 cmp 的第二个参数的类型.

我尝试了这个主题的变体,但没有奏效,但希望它能提供一些直觉:

template<template<typename mycmp_t>
int (*cmp)(const mydata_t &, const mycmp_t &)
>
void insert(const mydata_t &value, const mycmp_t &key);

(给我 expected 'class' before '(' token, expected identifier before '(' token, expected '>' before '(' token)。我还想象过使用像 template<int (*cmp)(const mydata_t &, const mycmp_t &), typename mycmp_t> 这样的模板但它说 mycmp_t签名中的内容尚未定义(尚未定义)之类的。

最佳答案

通常,您在惯用的 C++ 中以另一种方式传递回调:不绑定(bind)到特定类型或参数,而是作为普通参数:

template<class K, class F>
void insert(T const& v, K const& k, F f);

不过,要回答您的实际问题,不,您不能那样做。

关于c++ - 是否可以从较晚的模板参数推断或默认较早的模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11480771/

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