C++ 带有成员函数指针的部分模板类专门化
我有以下工作代码:C++ 带有成员函数指针的部分模板类专门化,c++,templates,c++11,typetraits,C++,Templates,C++11,Typetraits,我有以下工作代码: 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&l
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;
}
班级人员
{
私人:
国际年龄;
公众:
person():年龄(56){}
空位年龄(inta){age_ui=i;}
}
模板类持有者;
模板
阶级持有者
{
公众:
typedef typename T::value_type value_type;
公众:
显式holder():setter(FUNC){std::cout
阶级持有者
{
公众:
explicit holder(){std::cout更新:我让它使用std::conditional
:
template < class T, void (std::conditional<std::is_class<T>::value, T, struct dummy>::type::* ...FUNC)(int) > class holder;
template类持有者;
另一种可能的解决方案是使用子类:
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;
}
template
类别持有人
{
公众:
typedef typename T::value_type value_type;
公众:
显式类\u holder():setter(FUNC){std::cout Traits是一种方法-什么不适用于它们?为了测试a,我们尝试使用enable_if进行int专门化,但编译器总是提到第一个holder定义中缺少的成员函数。条件方法对我来说非常有效!非常感谢。由于使用了条件,编译器没有检查子类版本它按照我想要的方式工作。@zussel很高兴它工作了!你可以点击左边的复选标记,将其标记为解决方案。+1我将投票支持创意=P顺便说一句,T::value_类型应该如何解决。我看不出这个人有这样的特点。它来自哪里?@WhozCraig:这是我放在模板指针类中的剩余部分person(如shared_ptr)。指针类有一个typedef值_type。在本例中没有使用它。我调整了解决方案,使其与我的指针类一起工作。@zussel,谢谢。是的,条件扩展非常好。我盯着它看了10分钟才意识到它是如何工作的。