gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:46:37 26 4
gpt4 key购买 nike

有结构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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com