函数重载取决于编译时对象状态

问题描述 投票:0回答:1

考虑有一个简单的类,根据其状态将整数写入

cout

#include <iostream>

class NotAWriter{
public:
    NotAWriter& operator<<(const int& arg) {
        if (on) std::cout << arg;
        return *this;
    }
    void toggle() {on=!on;}
private:
    bool on = false;
};

现在考虑一下我有一个编译时恒定数量的切换(即调用

NotAWriter.toggle()
)。

我希望程序根据编译时的变量

on
来选择是否打印,如下所示:

NotAWriter& operator<<(const int& arg) {
    if constexpr (on) std::cout << arg;
    return *this;
}

或者这个

std::enable_if<on, NotAWriter&> operator<<(const int& arg) {
    std::cout << arg;
    return *this;
}
std::enable_if<!on, NotAWriter&> operator<<(const int& arg) {return *this;}

但是,禁止在常量表达式中使用

this

error: use of ‘this’ in a constant expression
  |      if constexpr (on) std::cout << arg;
  |      ^~

有没有办法根据编译时的成员变量来做到这一点(选择重载或 if 分支)?当然,如果我确定变量更改的数量是编译时常数。

c++ overloading metaprogramming compile-time if-constexpr
1个回答
0
投票

您是否有理由不能依赖这样或类似的东西:

#include <iostream>

template <bool on>
class NotAWriter
{
public:
    NotAWriter& operator<<(const int& arg)
    {
        if constexpr (on)
            std::cout << arg;
        return *this;
    }
};

int main()
{
    NotAWriter<false>() << 4;
    NotAWriter<true>() << 4;
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.