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

标签 c++ templates c++11

我的目标是 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/

相关文章:

c++ - 命名实体作为模板参数列表中 T 的指针

c++ - 模棱两可的错误 : C++11 use variadic template multiple inheritance

c++ - 有没有办法在编译时检查 std::initializer_list 参数的数量?

c++ - 使用值类在 C++ 中实现 STL 映射

c++ - 如何使用 vector 和整数作为类的构造函数

android - YUV 缓冲区转换为 RGB 的内存分配

templates - 如何制作插入其他较小内容项 View 的平面 View ?

C++设计模式以避免固定大小数组的模板

c++ - 构建本身就是 shared_ptr 类型的模板化容器

c++ - 错误 : ‘length’ was not declared in this scope c++