如何使用SFINAE在模板类中有选择地定义成员变量? [英] can I use SFINAE to selectively define a member variable in a template class?

查看:90
本文介绍了如何使用SFINAE在模板类中有选择地定义成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我要做的是基于传入的模板参数创建一个模板类,该类可以包含也可以不包含成员变量。

So what I want to do is to create a template class which may or may not contain a member variable based on the template argument passed in. like following:

template<typename T, bool flag>
class base
{
   foov<std::enable_if<flag, T>::type> m_var;
};

以上代码无法在编译器中生存。

the above code could not survive the compiler.

有人知道我能做到这一点吗?

Does anyone know how I can achieve this?

推荐答案

基于模板参数具有具有启用/禁用成员的基类:

Have a base class with enabled/disabled members based on template parameters:

template<typename T, typename Enable = void>
class base_class;

// my favourite type :D
template<typename T>
class base_class<T, std::enable_if_t<std::is_same<T, myFavouriteType>::value>>{
    public:
        int some_variable;
};

// not my favourite type :(
template<typename T>
class base_class<T, std::enable_if_t<!std::is_same<T, myFavouriteType>::value>>{
    public:
        // no variable
};

template<typename T>
class derived_class: public base_class<T>{
    public:
        // do stuff
};

这应该为您提供一种基于类型启用/禁用成员的好方法。

This should give you a nice way to enable/disable members based on type.

这篇关于如何使用SFINAE在模板类中有选择地定义成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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