【发布时间】:2014-12-21 23:01:14
【问题描述】:
我正在尝试在非模板类中专门化模板化方法,其中方法的返回类型包括模板化类型 - 此方法不接受任何参数。我一直在四处寻找并试图通过反复试验来编译东西,但无济于事。
如何构建此代码?这样的语法甚至可能吗? (我试图专门化的模板化方法是 cBar::getFoos,如下面的 cmets 中所标记。)
下面的精简示例代码:
#include <vector>
////////////////////////////////////////////////////////////////////////////////
// the non-templated class below contains std::vector objects of these types
// (tBuiltInType is an int, float, or bool - but hopefully that's not an
// assumption that needs to be made, as I'd like to include more complex types)
template< typename tBuiltInType >
class cFoo
{
public:
// ...
void doSomething()
{
// ... (unimportant what happens here, but stuff happens)
}
private:
std::vector< tBuiltInType > m_objects;
};
////////////////////////////////////////////////////////////////////////////////
// this contains the templated method I'm trying to specialize - getFoos
class cBar
{
public:
// ...
// this is the method I'm trying to specialize by contained type (see private area)
// getFoos< int >() would return m_intFoos, etc.
template< typename tBuiltInType >
std::vector< cFoo< tBuiltInType > > &getFoos();
// (probably unimportant) example use
template< typename tBuiltInType >
void doSomething()
{
for ( cFoo< tBuiltInType > &foo : getFoos< tBuiltInType >() )
foo.doSomething();
}
private:
std::vector< cFoo< int > > m_intFoos;
std::vector< cFoo< bool > > m_boolFoos;
std::vector< cFoo< float > > m_floatFoos;
};
////////////////////////////////////////////////////////////////////////////////
// some (also probably unimportant) example usage code
int main()
{
cBar bar;
bar.doSomething< int >();
bar.doSomething< bool >();
bar.doSomething< float >();
return 0;
}
(我正在拜访我的家人并且没有笔记本电脑,所以我通常的开发设置不可用 - 我可以在我一直在尝试的在线编译器中尝试发布错误,但我怀疑它会做得很好在这里,因为没有多少人会看到一个神秘的在线编译器错误并知道该怎么做,所以为了稍微压缩问题文本,我会跳过那一点。)
【问题讨论】:
-
请看这个related question(至少是answer)。
-
这可以工作,但我想在未来添加更复杂的类型。不过谢谢!
-
“但我想在未来添加更复杂的类型。” 我们一直在使用一些特殊的预处理器宏来扩展枚举并添加类型来解决这个问题配合验证宏和代码,在编译时检查所有这些。
标签: c++ templates template-specialization specialization