[英]static non-template method in template class
我想向模板类添加静态函数,而无需先传递模板参数就可以访问它。 那可能吗?
namespace foo {
template <typename T>
class bar {
public:
static void eggs();
};
}
foo::bar<some_t>::eggs(); // works
foo::bar::eggs(); // does not work
我想避免将eggs()
移到foo
命名空间或为其创建一个新的命名空间(例如foo::bar_::eggs()
,ugh)。
否。这不是模板类的工作方式。 您想做的事在C ++中是不可能的。
请记住, foo::bar
不会命名任何类型,而只能命名可用于创建其他类型的模板。
除了使用typedefs / type别名(通过using
)之外,您还可以为模板提供一个非模板基类,然后将静态成员放在那里。 如果您使用公共继承,则在任何模板化类中更改静态成员都会对其全部进行更改。
实验代码后:
我想向模板类添加静态函数,而无需先传递模板参数就可以访问它。 那可能吗?
namespace foo {
template <typename T>
class bar {
public:
static void eggs();
};
}
foo::bar<some_t>::eggs(); // works
foo::bar::eggs(); // does not work
我想避免将eggs()移到foo命名空间或为其创建新的命名空间(例如foo :: bar _ :: eggs(),ugh)。
我得出的结论是,
foo::bar<some_t>::eggs(); // works while
foo::bar::eggs(); // doesn't
原因是使用模板时,类中的任何内容都必须相对于特定对象,即使您不希望使用该函数也是如此。 我什至尝试使用函数指针,并试图将它们保存到模板类中,但是毫无用处,我什至无法编译它。 在这种情况下,我认为您没有太多选择。 也许还有其他人可能知道的窍门,但从我的眼中看不出来。
您可以将template参数设为可选,还可以定义专门的模板。 像这样:
namespace foo {
template <typename T = void> class bar {
public:
static void eggs() { cout << "First there was the egg" << endl; }
};
template <> class bar<void> {
public:
static void eggs() {
cout << "Then there was the chicken... or was it?" << endl;
}
};
}
auto main() -> int {
foo::bar<int>::eggs(); // egg
foo::bar<>::eggs(); // chicken
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.