简体   繁体   中英

passing multiple(different) types of arguments to a template function

#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;
}

So I am getting this error, i think its because its testing the map with value of the type int (map<int,int>) on a part of the template function which shouldn't reach its an int not a struct, even though I tried specialization the type before using the function, still not working.

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 is evaluated only at runtime.

At compile time, the compiler doesn't know whether the if is going to be true or false when compiling. So in general, all the code has to be compilable irrespective of whether it's inside a condition or not.

You need to use an overloaded function.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM