C++ 模板,vector.size 用于默认参数定义

标签 c++ templates parameters default definition

有结构TA

template <typename T>
struct TA
{
    typedef std::vector <T> Type;
};

和具有 TA 类型默认参数的 test() 函数。

template <typename T>
void test ( typename TA<T>::Type a1, 
            typename TA<T>::Type a2 = typename TA<T>::Type(a1.size()) )
{}

是否可以在默认参数 a2 定义中使用 a1.size()?

int main()
{
    TA <double> ::Type a1;
    test<double>(a1);
}

最佳答案

Is it posssible to use a1.size() in default parameter a2 definition?

没有。这是标准所禁止的。您不能使用函数参数来设置其他参数的默认值。

§8.3.6/9 (C++03) 明确地说,

Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated.

所以解决方案是:使用重载:

template <typename T>
void test(typename TAs<T>::Type a)
{
    test(a, typename TA<T>::Type(a.size()));
}

关于C++ 模板,vector.size 用于默认参数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9227333/

相关文章:

c++ - 如何设置 CmakeList 标志

c++ - ACE C++ 登录多个文件

c++: - 设置大小参数 X 的默认 initializer_list 参数 Y,其中 X 和 Y 是函数参数

c++ - 如何防止非专业模板实例化?

c++ - 为什么这个C++模板代码无法编译?

sql - 参数太少。 (1) 预期

c++ - 使用 gcc 4.2 在 Mac OS X 10.6.8 上安装 lxml

json - 我在使用arm模板部署存储帐户时遇到问题

javascript - 多态参数javascript

c++ - 如何在方法中获取 int 数组(方法参数)的长度?