我有以下模板:
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/