1

在我的最后一个问题中,我在获得模板专业化工作方面获得了很大帮助。现在我需要一点扩展。我想要这些陈述的两个专业:

int main()
{
    // First specialization
    holder_ext<person> h1;
    holder_ext<person, &person::age> h2;
    holder_ext<int> h3;

    // Second specialization
    holder_ext<person, &person::age, &person::name> h4;
}

我班的人是这样的:

class person
{
private:
    std::string name_;
    int age_;
public:
    person(const std::string &name)
        : name_(name), age_(56)
    {}
    void age(int a) { age_ = i; }
    void name(const std::string &n) { name_ = n; }
};

特别的是,这两个成员函数有不同的参数类型。所以我不能对两者使用相同的可变参数模板成员函数。我尝试了两个不同的可变参数模板。但这不起作用。成员函数的默认值也不起作用。

有人对我有好的提示吗?

这是具有一个成员函数的解决方案(感谢Pubby):

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 holder<T, FUNC>
{
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"; }
};

再次提前感谢!

PS:不,我不会在两天内提出“三个、四个、五个成员函数必须做什么”?;-)

4

2 回答 2

0

对于一个完全通用的解决方案,您将遇到一个无法解决的问题:无法推断非类型模板参数的类型,因此它必须在模板声明中明确,因此无法告诉模板您想要多个指向成员参数的指针,每个参数都有一个未知的类型。

我对 C++11 的使用还不够,但您可以尝试对成员模板参数强制排序并在模板中提供所有签名:

template <typename T, 
          void (std::conditional<...>::type*)(int),
          void (std::conditional<...>::type*)(const std::string&)>

再说一次,它可能会起作用,也可能不会……

于 2012-12-07T14:07:55.703 回答
0

最后我找到了解决我的问题的方法。它是可变参数模板和模板规范的混合:

template < class T,
void (std::conditional<std::is_base_of<object, T>::value, T, struct dummy>::type::*FUNC1)(int) = nullptr,
void (std::conditional<std::is_base_of<object, T>::value, T, struct dummy>::type::* ...FUNC2)(const std::string&)
>
class holder_ext;

template < class T,
void (std::conditional<std::is_base_of<object, T>::value, T, struct dummy>::type::*FUNC1)(int),
void (std::conditional<std::is_base_of<object, T>::value, T, struct dummy>::type::*FUNC2)(const std::string&)
>
class holder_ext<T, FUNC1, FUNC2>
{
public:
    holder_ext() { std::cout << "func 2 test\n"; }
};

template < class T,
void (std::conditional<std::is_base_of<object, T>::value, T, struct dummy>::type::*FUNC1)(int)
>
class holder_ext<T, FUNC1>
{
public:
    holder_ext() { std::cout << "func 1 test\n"; }
};

I use a not implemented declaration and define two specializations. One with both member function and the other one for all other cases.

If there is a better solution dont't hesitate to tell me.

于 2012-12-11T10:00:55.847 回答