c++ - 将多种(不同)类型的参数传递给模板函数

标签 c++ templates

#include <iostream>
#include <typeinfo>
#include <map>
#include <stdlib.h>
using namespace std;

struct foo {
    int one;
    int i;
    int s;  
};

template<class myType>
void serialize(myType b, string &a, int epe) {

    //three.resize(42);
    int type = typeid(b).name()[35] == 'S' ? 1 : 0; // testing if the map(b) value weather a struct                                or an int

    if (type) {
        auto it = b.begin();
        cout << sizeof(it->second) / sizeof(int) << endl;
        cout << it->second.one;
    } else {
        cout << sizeof(b) / sizeof(int) << endl;
    }

}

int main() {
    cout << "Hello world!" << endl;
    map<int, int> hey;

    map<int, foo> heya {
        { 1, { 66 } },
    };

    typedef map<int, foo> mappy;
    typedef map<int, int> happy;

    string duck;
    auto it = heya.begin();
    serialize<happy>(hey, duck, 4);
    serialize<mappy>(heya, duck, 4);

    return 0;
}

所以我收到这个错误,我认为是因为它正在测试 map 具有 int 类型的值 (map<int,int>)在模板的一部分 函数不应该达到它的 int 而不是结构,即使我 在使用该函数之前尝试对类型进行特化,但仍然无法正常工作。

serialize\main.cpp|36|error: request for member 'one' in      'it.std::_Rb_tree_iterator<_Tp>::operator->
   [with _Tp = std::pair<const int, int>, std::_Rb_tree_iterator<_Tp>::pointer = std::pair<const int, int>*]()->std::pair<const int, int>::second', 
  which is of non-class type 'int'|
  ||=== Build finished: 1 errors, 1 warnings ===|

最佳答案

if 仅在运行时计算。

在编译时,编译器不知道编译时if 是真还是假。所以一般来说,所有代码都必须是可编译的,无论它是否在条件内。

您需要使用重载函数。

typedef map<int, foo> mappy;
typedef map<int, int> happy;

template<class myType>
void serialize(myType b, string &a, int epe) {
    cout << sizeof(b) / sizeof(int) << endl;
}

void serialize(mappy b, string &a, int epe) {
    auto it = b.begin();
    cout << sizeof(it->second) / sizeof(int) << endl;
    cout << it->second.one;
}

serialize<happy>(hey, duck, 4);
serialize(heya, duck, 4);

关于c++ - 将多种(不同)类型的参数传递给模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16593424/

相关文章:

c++ - 在类模板中正确初始化静态 constexpr 数组?

c++ - 使用自定义分配器及其替代方案重载基本类型

c++ - 如何不关心类成员模板

c++ - 当实例变量未初始化时,如何使 C++ 编译器产生错误或警告?

c++ - 为什么 seekg 不能与 getline 一起使用?

c++ - 获取网络上事件 IP 的列表 (Linux)

html - 在 "Miniport"html5 模板中居中 DIV

c++ - 海湾合作委员会错误?链接方法,断序列点

c++ - 奇怪的是,SFINAE 无法进行递归模板调用

python - 如何在Python中访问模板?