简体   繁体   English

具有成员函数指针的部分模板类专门化

[英]Partial template class specialization with member function pointer

I have the following working code: 我有以下工作代码:

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;
}

I know that in case of int (or any other non class, struct or union type) the code does not work because of the expect member function in the second template argument. 我知道在int(或任何其他非类,结构或联合类型)的情况下,由于第二个模板参数中的expect成员函数,代码不起作用。

My question is how to change the code to make it work. 我的问题是如何更改代码以使其工作。 I need it work that way, to make the use of my holder class simple. 我需要它以这种方式工作,使我的持有人类的使用变得简单。

I've tried it with type traits and also moved the member function pointer to the constructor of the class. 我已尝试使用类型特征,并将成员函数指针移动到类的构造函数。 Without success. 没有成功。

Any suggestions? 有什么建议? Thanks in advance! 提前致谢!

Update: I got it to work with std::conditional : 更新:我让它与std::conditional一起工作:

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

Another possible solution is to use a subclass: 另一种可能的解决方案是使用子类:

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;
}

I haven't compiled this so tell me if something doesn't work. 我没有编译这个,所以告诉我,如果某些东西不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM