LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Can't use template with std::map (https://www.linuxquestions.org/questions/programming-9/cant-use-template-with-std-map-379711/)

astorm 11-03-2005 04:31 PM

Can't use template with std::map
 
I'm writing a small scripting language. I'm using a global std::map to store variables, which can be of any type. However, I can't do
Code:

template <class T>
std::map< string, T > varTable;

outside a function, and I can't do
Code:

void * varTable;

template <class T>
void makeTable()
{
    map< string, T > tVarTable;
    varTable = &tVarTable;
}

because it complains it can't find the function, and I'd probably have problems with dereferencing varTable. If there's no elegant way to do this, I'll have to create a Scalar struct with a void* value and string type. Is there any better way?

Thanks in advance,
Alek

naf 11-03-2005 04:51 PM

You are a dangerous man :)
I got it to create an inherited class like this:
Code:

#include <map>

template <class T>
class varTable : public std::map< std::string, T >
{
    // Your extensions here?  Maybe you do not want public inheritance?
};

int main( int argc, char **argv )
{
    varTable< double > doublesTable;

    return 0;
}

Not sure if this is what you wanted.

astorm 11-03-2005 05:14 PM

Thanks. That would work, but it isn't quite what I wanted. I'd have to create a varTable for every possible type of variable. But hey, that still isn't as clunky as what I had before. I'll go ahead and write the code that way, and change it later if I find a better one. Gives me that adrenaline rush. Thanks again.

ta0kira 11-03-2005 06:55 PM

The problem is that the compiler can't use Koenig Lookup to figure out the type you need since you have no argument; if the function took an argument of type 'T' (or something that uses it, like 'vector <T>'), then the compiler could find out what type you need. Since you have no argument, you need to be explicit with the type in the call:
Code:

makeTable <double> ();
.

FYI: if you DO have an argument, but it can't be used to deduce ALL template parameters, such as
Code:

template <class A, class B> void Function(const A&);
place the deducible template arguments first, and those not deducible last. Then call the function like this:
Code:

char arg;
Function <int> (arg);

The compiler will know 'A' is 'char' and you tell it that 'B' is 'int'.
ta0kira


All times are GMT -5. The time now is 07:36 AM.