简体   繁体   中英

C++ Template Parameter that evaluates a Template (template template parameter)

I have a templated struct that maps an ID to an type using template specialisation (taken from https://www.justsoftwaresolutions.co.uk/articles/exprtype.pdf ).

template<int id>
struct IdToType
{};
template<>
struct IdToType<1>
{
typedef bool Type;
};
template<>
struct IdToType<2>
{
typedef char Type;
};

Now i want to call a function like this getValue()

where the return value of the function is the corresponding type of the ID.

template</*.... I don't know what to put here...*/ T>
idToType<T>::Type getValue() // I don't know exactly how to define the return value
{
    // whant to do some things with the provided ID and with the type of the id
}

So in short: - I want a templated Function where I can use an ID as template argument. - The function needs to have the type corresponding to the ID as return value (I get the corresponding type from IdToType::Type). - In the body of the function I want to have access to the ID and the type of the ID. - I think this should be possible with template template paramters. But I'm not sure about that.

I hope that is somwhat clear...

Thanks in advance!

template <int id>
typename IdToType<id>::Type getValue() 
{
    using T = typename IdToType<id>::Type;
    return 65;
}

DEMO

This code gives warning that the variable 'val' is unused. But since we don't what you want to do with the type inside getValue(), I left the code that way.

char getValueImpl(char)
{
    return 'c';
}


bool getValueImpl(bool)
{
    return true;
}

template<int X>
typename IdToType<X>::Type getValue()
{
    typename IdToType<X>::Type val;
   return getValueImpl(val);

}


int main()
{

   std::cout << getValue<2>() << "\n";
   std::cout << getValue<1>() << "\n";

}

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