【问题标题】:Partial template class specialization with member function pointer具有成员函数指针的部分模板类特化
【发布时间】:2012-12-05 09:25:50
【问题描述】:

我有以下工作代码:

class person
{
private:
    int age_;
public:
    person() : age_(56) {}
    void age(int a) { age_ = i; }
}

template < class T, void (T::* ...FUNC)(int) > class holder;

template < class T, void (T::*FUNC)(int)>
class holder<T, FUNC>
{
public:
    typedef typename T::value_type value_type;
public:
    explicit holder() : setter(FUNC) { std::cout << "func\n"; } 
private:
    std::function<void (value_type&, int)> setter;
};

template < class T>
class holder<T>
{
public:
    explicit holder() { std::cout << "plain\n"; }
};

int main()
{
    holder<person> h1;
    holder<person, &person::age> h2;

    // this does not work:
    holder<int> h3;
}

我知道在 int(或任何其他非类、结构或联合类型)的情况下,由于第二个模板参数中的期望成员函数,代码不起作用。

我的问题是如何更改代码以使其工作。我需要它以这种方式工作,以使我的持有者类的使用变得简单。

我已经尝试过使用类型特征并将成员函数指针移动到类的构造函数。没有成功。

有什么建议吗?提前致谢!

【问题讨论】:

  • 特征是要走的路 - 什么对他们不起作用?
  • 为了测试一个尝试使用 enable_if 进行 int 特化,但编译器总是提到第一个持有者定义中缺少的成员函数。

标签: c++ templates c++11 typetraits


【解决方案1】:

更新:我可以使用 std::conditional

template < class T, void (std::conditional<std::is_class<T>::value, T, struct dummy>::type::* ...FUNC)(int) > class holder;

另一种可能的解决方案是使用子类:

template < class T, void (T::*FUNC)(int) >
class class_holder
{
public:
    typedef typename T::value_type value_type;
public:
    explicit class_holder() : setter(FUNC) { std::cout << "func\n"; } 
protected:
    std::function<void (value_type&, int)> setter;
}

template <class T, bool IsClass = std::is_class<T>::value>
class holder;

template <class T>
class holder<T, true> : public class_holder<T>
{
public:
    template <void (T::*FUNC)(int) >
    class with_member : public class_holder<T, FUNC>
    {
    };
};

template <class T>
class holder<T, false>
{
public:
    explicit holder() { std::cout << "plain\n"; }
};

int main()
{
    holder<person> h1;
    holder<person>::with_member<&person::age> h2;
    holder<int> h3;
}

我还没有编译这个,如果有什么不工作请告诉我。

【讨论】:

  • 条件方式对我来说非常有用!非常感谢。没有检查子类版本,因为有条件它按我想要的方式工作。
  • @zussel 很高兴它成功了!您可以单击左侧的复选标记将其标记为解决方案。
  • +1 我会为创造力投赞成票 =P 顺便说一句,T::value_type 应该如何解决。人没有我看到的这种特征。它来自哪里?
  • @WhozCraig:这是我放在 person 周围的模板化指针类的剩余部分(如 shared_ptr)。指针类有一个 typedef value_type。此示例中未使用它。我调整了解决方案,使其适用于我的指针类。
  • @zussel 这说明了谢谢。是的,有条件的扩展非常甜蜜。在我意识到它是如何工作之前,我盯着它看了 10 分钟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-25
  • 2012-12-15
  • 1970-01-01
相关资源
最近更新 更多