bpw*_*621 4 c++ oop templates c++11
不确定如何用短语来表达这个问题或搜索什么,如果这与其他问题相同,请关闭并重定向到相应的问题.
假设
template<typename Type, int Size> class vector
{
Type data[Size];
}
Run Code Online (Sandbox Code Playgroud)
是否可以替换一个构造函数,该构造函数在模板特化中使用大小数量的参数
template<typename Type> class vector3<Type,3>
{
Type data[3];
public:
vector3( Type, Type, Type );
}
Run Code Online (Sandbox Code Playgroud)
在非专业模板类中的东西?就像一个"varargs构造函数",它生成一个构造函数,其大小为类型为Type的参数?
涉及C++ 0x功能的解决方案很好.
在C++ 0x中,你template typedef终于可用了!
免责声明:没有编译过......
来自维基百科的文章:
template< typename second>
using TypedefName = SomeType<OtherType, second, 5>;
Run Code Online (Sandbox Code Playgroud)
在你的情况下会屈服
template <class Type>
using vector3 = vector<Type, 3>;
Run Code Online (Sandbox Code Playgroud)
我不能告诉你我有多渴望这个;)
但是它没有解决参数问题.如前所述,您可以尝试使用可变参数模板,但我不确定它们在这种情况下的应用.正常使用是使用递归方法,你需要static_assert在中间抛出一个.
编辑将评论纳入考虑范围.
template <class Type, size_t Size>
class vector
{
public:
template <class... Args>
vector(Args... args): data({args...})
{
// Necessary only if you wish to ensure that the exact number of args
// is passed, otherwise there could be less than requested
BOOST_MPL_ASSERT_RELATION(sizeof...(Args), ==, Size);
}
private:
T data[Size];
};
Run Code Online (Sandbox Code Playgroud)
已有的另一种可能性是将预处理器生成与boost::enable_if.
template <class Type, size_t Size>
class vector
{
public:
vector(Type a0, typename boost::enable_if_c< Size == 1 >::type* = 0);
vector(Type a0, Type a1, typename boost::enable_if_c< Size == 2 >::type* = 0);
// ...
};
Run Code Online (Sandbox Code Playgroud)
使用Boost.Preprocessor进行生成使这更容易.
BOOST_PP_REPEAT(MAX_COUNT, CONSTRUCTOR_MACRO, ~);
// where MAX_COUNT is defined to the maximum size you wish
// and CONSTRUCTOR_MACRO actually generates the constructor
#define CONSTRUCTOR_MACRO(z, n, data) \
vector( \
BOOST_PP_ENUM_PARAMS(n, Type a), \
typename boost::enable_if_c< Size == n >::type* = 0 \
);
Run Code Online (Sandbox Code Playgroud)
构造函数的实现留给读者练习.这是另一个电话BOOST_PP_REPEAT.
正如您所看到的,它很快变得难看,所以如果您可以使用可变参数模板版本,那么您将会变得更好.