const /非const成员函数基于编译时条件

时间:2014-11-17 20:39:26

标签: c++ templates c++11

让我们考虑以下课程:

struct InputArgument{};
struct SpecialInputArgument{};
struct MoreSpecialInputArgument{};

struct OutputArgument{};
struct SpecialOutputArgument{};
struct MoreSpecialOutputArgument{};

我需要一个成员函数,它接受所有以前的类作为参数并对它们进行操作。为了简化实现(不要反复重复相同的代码),我创建了成员函数模板,并将实际代码分派给非成员函数:

template<typename T>
typename std::enable_if<std::is_fundamental<T>::value>::type DoSomething(T&, const InputArgument&)
{
}

template<typename T>
typename std::enable_if<std::is_fundamental<T>::value>::type DoSomething(const T&, OutputArgument&)
{
}

template<typename T>
typename std::enable_if<std::is_fundamental<T>::value>::type DoSomething(T&, const SpecialInputArgument&)
{
}

template<typename T>
typename std::enable_if<std::is_fundamental<T>::value>::type DoSomething(const T&, SpecialOutputArgument&)
{
}

template<typename T>
typename std::enable_if<std::is_fundamental<T>::value>::type DoSomething(T&, const MoreSpecialInputArgument&)
{
}

template<typename T>
typename std::enable_if<std::is_fundamental<T>::value>::type DoSomething(const T&, MoreSpecialOutputArgument&)
{
}

struct MyGloriuosClass
{
    template<typename T>
    void DoSomething(T& arg)
    {
        ::DoSomething(myIntMember, arg);
        ::DoSomething(myFloatMember, arg);
    }

    int     myIntMember = 0;
    float   myFloatMember = 0.f;
};

这很有效:

MyGloriuosClass myGloriuosObject;

InputArgument inputArgument;
SpecialInputArgument specialInputArgument;
MoreSpecialInputArgument moreSpecialInputArgument;

OutputArgument outputArgument;
SpecialOutputArgument specialOutputArgument;
MoreSpecialOutputArgument moreSpecialOutputArgument;

myGloriuosObject.DoSomething(inputArgument);
myGloriuosObject.DoSomething(specialInputArgument);
myGloriuosObject.DoSomething(moreSpecialInputArgument);

myGloriuosObject.DoSomething(outputArgument);
myGloriuosObject.DoSomething(specialOutputArgument);
myGloriuosObject.DoSomething(moreSpecialOutputArgument);

在一种情况下,我使用的对象是const:

const MyGloriuosClass myConstGloriousObject = MyGloriuosClass();
myConstGloriousObject.DoSomething(outputArgument);
myConstGloriousObject.DoSomething(specialOutputArgument);
myConstGloriousObject.DoSomething(moreSpecialOutputArgument);

正如您所看到的,当参数类型为const时,所有实际代码都在接受Output对象的函数中完成,因此没有理由将此限制为仅non-const对象或编写我的成员函数两次,一次为const,一次为non-const。在我的理想世界中,我将根据参数的const/non-const type trait来推断函数是否为std::is_base_of,但我不知道这是否可行。

是否可以根据编译时条件声明成员函数const / non-const?

1 个答案:

答案 0 :(得分:1)

成员函数是const或非const成员函数。没有第三种选择。如你所知,类可以定义const函数,非const函数,甚至两者都可以。

我怀疑你可能会遗漏的是,可以为非const类实例调用const成员函数。

因此,如果您的成员函数不需要修改类实例的任何其他成员,只需将您的成员函数声明为const函数,并且可以为const或非const类实例调用它。 / p>

相关问题