c++ - 如何从模板生成具有 const 或非常量成员函数的类?

标签 c++ templates c++11

我有以下模板:

template<typename Signature>
class TypeErasedFunctor;

template<typename R, typename... Args>
class TypeErasedFunctor<R(Args...)>
{
public:

    virtual R operator()(Args... args) = 0;
};

它可以用来为像这样的仿函数生成接口(interface)类:

using SemaphoreFunctor = TypeErasedFunctor<int(Semaphore&)>;

可以看出成员函数operator()是非常量。我想问以下问题 - 除了这两个之外,是否有任何选项可以选择是否应创建 const 或非 const 变体:

  • 使用 SFINAE(可能与 std::enable_if<> 一起使用)和模板的附加参数,
  • 使用单独的模板 ConstTypeErasedFunctor

最佳答案

您可以在同一个对象上同时使用两个(const 和非 const)版本的 operator () 作为重载。但是如果你想在声明对象时轻松地只选择一个,你可以使用类似的东西:

template<bool b, typename Signature>
class TypeErasedFunctor;

template<typename R, typename... Args>
class TypeErasedFunctor<true,R(Args...)>
{
    public:
        virtual R operator() (Args... args) const = 0;
};

template<typename R, typename... Args>
class TypeErasedFunctor<false,R(Args...)>
{
    public:
        virtual R operator()(Args... args) = 0;
};

template<bool b>
using SemaphoreFunctor = TypeErasedFunctor<b,int(Semaphore&)>;

稍后,在客户端代码中,您可以使用剩余的通用参数进行选择:

SemaphoreFunctor<true> object_with_const_op;
SemaphoreFunctor<false> object_with_no_const_op;

关于c++ - 如何从模板生成具有 const 或非常量成员函数的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27411272/

相关文章:

c++ - FBXSDK,使用四元数设置旋转键?

c++ - 在 Visual Studio 和 Linux IDE 中同时开发

C++接口(interface)队列或priority_queue作为类的模板参数

c++ - Visual Studio 中可变参数模板扩展的问题

c++ - 为什么(void)在for循环中的两个逗号分隔语句之间

c++ - 为什么 FFMPEG 屏幕录像机输出仅显示绿屏?

从 lambda 推导 C++ 模板

c++ - C++ 中嵌套模板函数的 const 限定符

c++ - 对于对象图,我可以放置对象还是成对放置对象?

c++ - 右值引用参数和模板函数