Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to whitelist which types are allowed in a template function?

Tags:

c++

I have a template function that I would like to only work with a specific list of types.

 template <class T> void foo(const T f) {/*do stuff with f*/}

 int main() {
        string A= "Hello world";
        char B[10] = "Hello world";
        Int C = 69;

        foo(A); //should work here
        foo(B); //and here
        foo(C); //but it should give an error here, preferably while it is compiling

       return 0;
 }

I expect it to work if I call it with a char[] or with a string, but give an error (possibly while it's compiling, but during runtime works too) when I try to call it with an INT type.

like image 663
lidlessey3 Avatar asked Sep 10 '19 18:09

lidlessey3


2 Answers

For your particular case, I would overload the function foo instead of using a template. This ensures you can only have one of those two types, and with those two types in particular it is quite simple to overload:

void foo(const char* s) {
    // do work with s
}

void foo(const std::string& s) {
    foo(s.c_str()); // use the other overload for const char*
}
like image 171
Will Eccles Avatar answered Oct 04 '22 03:10

Will Eccles


SFINAE might help:

template <class T, std::enable_if_t<!std::is_same<int, T>::value, int> = 0>
void foo(const T f) {/*do stuff with f*/}

or

template <class T,
          std::enable_if_t<std::is_same<std::string, T>::value
                           || std::is_same<const char*, T>::value, int> = 0>
void foo(const T f) {/*do stuff with f*/}

Adjust the condition to your needs.

or static_assert:

template <class T>
void foo(const T f) {
    static_assert(std::is_same<std::string, T>::value
                  || std::is_same<const char*, T>::value, "Incorrect type");
    /*do stuff with f*/
}
like image 36
Jarod42 Avatar answered Oct 04 '22 04:10

Jarod42