模板非类型参数重载

时间:2013-06-01 19:04:12

标签: c++ templates

是否可以有两个具有相同名称但不同的非类型模板参数的模板类 - 因此某种非类型模板参数重载机制?

template <typename T, typename U, void (T::*F)(U)> void common() { ... }
template <typename T, typename U, void (T::*F)(const U &)> void common() { ... }

struct Foo
{
   void foo(bool) {}
}

struct Bar
{
   void bar(const bool &) {}
}

template <typename T, typename U, void (T::*F)(U)> struct Storage 
{
     Storage() { common <T, U, F>(); }
}
template <typename T, typename U, void (T::*F)(const U &)> struct Storage 
{
    Storage() { common <T, U, F>(); }
}

Storage<Foo, bool, &Foo::foo> foo;
Storage<Bar, bool, &Bar::bar> bar;

拥有这种机制的原因是两者都应该能够使用相同的宏创建。

#define STORAGE(T, U, F) Storage<T, U, F> BOOST_PP_CAT(storage, __LINE__);

STORAGE(Foo, bool, &Foo::foo)
STORAGE(Bar, bool, &Bar::bar)

感谢您的投入!

修改

可能会有一些进一步的输入是有帮助的。

我想要实现的是在初始化时运行的方法。我可以提供这样一个方法 - 或者更好地说两个重载方法,一个用const-ref,另一个用value-member-function-pointer;但是为了在初始化时执行它们,我通常会有一个存根类(如本例中的存储),它在其构造函数中调用此方法(因此在初始化时,因为STORAGE宏创建了存根类的实例)。 p>

要使用相同的STORAGE宏,我必须为我要执行的函数的存根类具有相同的模板非类型'重载'(我将不得不模板化类,而不是构造函数,我当然可以重载,因为不可能显式地声明构造函数模板参数,并且因为模板参数是非类型的,所以我也不能推断它们。)

修改

指向成员函数的指针必须是一个编译时值(非类型模板参数),因为它将被包装在非模板静态方法中,然后可以存储在std :: vector中。运行时。

1 个答案:

答案 0 :(得分:0)

您要解决的问题并不完全清楚。如果你只是试图让你的例子起作用,你可以将'bool'改为'const bool&amp;'。这实现了你想要的吗?

template <typename T, typename U, void (T::*F)(U)> void common() {  }

struct Foo
{
    void foo(bool) {}
};

struct Bar
{
    void bar(const bool &) {}
};

template <typename T, typename U, void (T::*F)(U)>
struct Storage 
{
        Storage() { common <T, U, F>(); }
};

Storage<Foo, bool, &Foo::foo> foo;
Storage<Bar, const bool&, &Bar::bar> bar;