简体   繁体   中英

Templated function Return type at compile time no arguments

I have a function that right now can return a value of a certain type for me. It looks like this

template<typename T>
T getNullValue(){
    if(std::is_same<T,long long>::value){
        return NULL_LONG;
    }else if(std::is_same<T,double>::value){
        return NULL_DOUBLE;
    }

}

This works but I do not like it resolving at run time as opposed to compile time but this allows me to do

double x = getNullValue<double>();
long long y = getNullValue<long long>();

How can I make it so that I can just overload different versions of getNullValue depending on what I want to return without having to resolve that at runtime.

getNullValue<type i need>();

Template specialization should do the trick nicely. An optimizing compiler should convert this to a simple assignment.

// getNullValue.hpp :

template <class T>
T getNullValue() {
   return 0;
}

// remember to declare specialization in header or strange linking errors may occur
template <> long long getNullValue<long long>()
template <> double getNullValue<double>()


 // getNullValue.cpp:

 template <> long long getNullValue<long long>() {
   return NULL_LONG;
 }
template <> double getNullValue<double>() {
   return NULL_DOUBLE;
}

int main() {
    double x = getNullValue<double>();
    long long y = getNullValue<long long>();
}

See http://en.cppreference.com/w/cpp/language/template_specialization for more examples of specialization.

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