I am currently in the process of updating my language knowledge (to C++17). I was trying to get this code to compile using gcc and couldn't figure it out so I tried MSVC and clang and both seem okay with this code -- is there anything wrong with this bit of code?
gcc seems to be complaining about instantiating a tuple<> with no template parameters which is odd:
prog.cc: In instantiation of 'C::C(U&& ...) [with U = {const A&, const …
基于具有合理默认值的输入类型来控制函数返回类型的规范方法是什么?
例如
// by default want R = decltype(container)::value_type
template<typename R>
R func(const auto& container)
{
R result{};
// some calculations using container
return result;
}
Run Code Online (Sandbox Code Playgroud)
用法是:
std::vector<int> ct{};
func(ct); // default result -> int
func<double>(ct); // custom call -> double
Run Code Online (Sandbox Code Playgroud)
我可以放弃使用 auto 并使用另一个模板参数:
template<typename C, typename R = C::value_type>
R func(const C& container)
{
R result{};
// some calculations using container
return result;
}
Run Code Online (Sandbox Code Playgroud)
但控制案例的使用并不理想:
func<std::vector<int>, double>(ct); // custom call -> double
Run Code Online (Sandbox Code Playgroud)
我可以重新排序模板参数:
template<typename R, typename C>
R func(const …Run Code Online (Sandbox Code Playgroud)