如何删除成员函数模板的实例化?

How to delete instantiation of a member function template?

我正在学习如何停止成员函数模板的实例化。在 c++20 中,requires 子句用于对模板参数施加约束,使用它我可以在 c++20 中停止实例化。

这段代码中哪一行代码可以替换c++11/14/17中的requires子句

#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

使用类型特征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 

请注意,在 C++14 之前,如果您使用 auto,则需要添加尾随 return 类型。