简体   繁体   English

带有类型条件的 C++ 模板

[英]C++ template with condition for type

I have class with template.我有模板类。 I want to add template condition for one of the class methods.我想为其中一种类方法添加模板条件。

The idea is for float types I want separate passed method to call this with some epsillon value.这个想法是对于浮点类型,我希望单独传递的方法用一些 epsilon 值调用它。

Is it possible?是否可以? The example what I want:我想要的例子:

template<typename ValueType>
class Comparator {
public:

...

bool passed(ValueType actualValue);

template<
    typename ValueType,
    typename = std::enable_if_t<
        std::is_floating_point<std::remove_reference_t<ValueType>>::value
    >
>
bool passed(ValueType actualValue, ValueType eps) { ... }

...

};

Environment: Debian 11, C++14, gcc (Debian 10.2.1-6) 10.2.1 20210110环境:Debian 11、C++14、gcc(Debian 10.2.1-6)10.2.1 20210110

Yes, you can do this:是的,你可以这样做:

#include <type_traits>

template<typename ValueType>
class Comparator {
public:

template<
    typename U = ValueType,
    typename = std::enable_if_t<
        !std::is_floating_point<std::remove_reference_t<U>>::value
    >
>
bool passed(ValueType actualValue);

template<
    typename U = ValueType,
    typename = std::enable_if_t<
        std::is_floating_point<std::remove_reference_t<U>>::value
    >
>
bool passed(ValueType actualValue, ValueType eps);

};

Demo.演示。

You are most of the way there already.你已经完成了大部分工作。 In order to overload SFINAE, you need to use a non-type template parameter with an assigned default value instead of using defaulted type template parameter.为了重载 SFINAE,您需要使用具有指定默认值的非类型模板参数,而不是使用默认类型模板参数。

So, we change both functions to use a non-type paramere with a default value, and just negate the condition like:因此,我们将这两个函数更改为使用具有默认值的非类型参数,并取消条件,例如:

template<typename ValueType>
class Comparator {
public:

...
template<
    typename T = ValueType,
    std::enable_if_t<
        !std::is_floating_point<std::remove_reference_t<ValueType>>::value,
//      ^- not here, so only non-floating point types allowed
        bool> = true // set the bool to true, this lets us call the function without providing a value for it
>
bool passed(T actualValue) { non floating point code here }

template<
    typename T = ValueType,
    std::enable_if_t<
        std::is_floating_point<std::remove_reference_t<T>>::value,
        bool> = true // set the bool to true, this lets us call the function without providing a value for it
>
bool passed(T actualValue, T eps) { floating point code here }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM