enable_if:无参数的void成员函数的最小示例 [英] enable_if: minimal example for void member function with no arguments

查看:133
本文介绍了enable_if:无参数的void成员函数的最小示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更好地理解C ++ 11中的 std :: enable_if ,并且一直在尝试编写一个最小的示例:类 A 具有成员函数 void foo()的成员函数,根据类型 T 来自类模板。

下面的代码给出了所需的结果,但我尚未完全理解。为什么 V2 版本有效,但 V1 无效?为什么需要冗余类型 U

I am trying to get a better understanding of std::enable_if in C++11 and have been trying to write a minimal example: a class A with a member function void foo() that has different implementations based on the type T from the class template.
The below code gives the desired result, but I am not understanding it fully yet. Why does version V2 work, but not V1? Why is the "redundant" type U required?

#include <iostream>
#include <type_traits>

template <typename T>
class A {

    public:

        A(T x) : a_(x) {}

        // Enable this function if T == int
        /* V1 */ // template <           typename std::enable_if<std::is_same<T,int>::value,int>::type = 0>
        /* V2 */ template <typename U=T, typename std::enable_if<std::is_same<U,int>::value,int>::type = 0>
        void foo() { std::cout << "\nINT: " << a_ << "\n"; }

        // Enable this function if T == double
        template <typename U=T, typename std::enable_if<std::is_same<U,double>::value,int>::type = 0>
        void foo() { std::cout << "\nDOUBLE: " << a_ << "\n"; }

    private:

        T a_;

};

int main() {
    A<int> aInt(1); aInt.foo();
    A<double> aDouble(3.14); aDouble.foo();
    return 0;
}

是否有更好的方法来实现所需的结果,即具有不同的实现类模板参数的 void foo()函数的作用?

Is there a better way to achieve the desired result, i.e. for having different implementations of a void foo() function based on a class template parameter?

推荐答案

我知道这不能完全回答您的问题,但是它可能会给您带来更多的想法和理解,从而使您可以使用 std :: enable_if

I know this wont fully answer your question, but it might give you some more ideas and understanding of how you can use std::enable_if.

您可以使用以下命令替换foo成员函数并具有相同的功能:

You could replace your foo member functions with the following and have identical functionality:

template<typename U=T> typename std::enable_if<std::is_same<U,int>::value>::type
foo(){ /* enabled when T is type int */ }

template<typename U=T> typename std::enable_if<std::is_same<U,double>::value>::type
foo(){ /* enabled when T is type double */ }

前一段时间,我对enable_if的工作方式有了很好的了解,但可悲的是我忘记了它的大多数复杂性,只记得更实用的方法使用它。

A while back I gained a pretty good understanding of how enable_if works, but sadly I have forgotten most of its intricacies and just remember the more practical ways to use it.

这篇关于enable_if:无参数的void成员函数的最小示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆