Ratnesh Tiwari
Ratnesh Tiwari

Reputation: 107

How to delete instantiation of a member function template?

I am learning how to stop instantiation of a member function template. In c++20 requires clause is used to put constraint on template arguments and using this I am able to stop instantiation in c++20.

What line of code could replace the requires clause in c++11/14/17 in this code.

#include <iostream>
#include <string>

struct St {
    template<typename T>
    // C++11/14/17 ???
    requires ( !(std::is_same<T, bool>::value || std::is_same<T, std::string>::value)) // C++20
    constexpr auto increment_by_one(T targ) const noexcept { return targ+1; }

};

int main() {
    St s;
    std::cout << s.increment_by_one(5) << '\n';
    std::cout << s.increment_by_one(8.6) << '\n';
    std::cout << s.increment_by_one(6.6f) << '\n';
    //std::cout << s.increment_by_one(true) << '\n';
    //std::cout << s.increment_by_one(std::string("test string")) << '\n';

    return 0;
}

https://gcc.godbolt.org/z/vjc5cE

Upvotes: 2

Views: 198

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

Using the type trait std::enable_if:

#include <type_traits>

// ...

    template<typename T,
        typename std::enable_if<
          !(std::is_same<T, bool>::value || std::is_same<T, std::string>::value),
          int
        >::type = 0
    >
    constexpr auto increment_by_one(T targ) const noexcept -> decltype(targ+1) {
        return targ+1;                                  //    ^^^^^^^^^^^^^^^^
    }                                                   // trailing return type 

Note that before C++14 you need to add a trailing return type if you're using auto.

Upvotes: 1

Related Questions