Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何编写返回引用或值的函数模板?_C++_Templates_C++17 - Fatal编程技术网

C++ 如何编写返回引用或值的函数模板?

C++ 如何编写返回引用或值的函数模板?,c++,templates,c++17,C++,Templates,C++17,我想编写一个函数模板,根据编译时表达式返回引用或值。到目前为止,我尝试的是这样的: template<typename T> auto&& Func() { if constexpr (some_compile_time_expression) { return GetReferenceFromSomewhere(); } else { return GetValueFromSomewhere(); } } 模板 auto&&

我想编写一个函数模板,根据编译时表达式返回引用或值。到目前为止,我尝试的是这样的:

template<typename T>
auto&& Func()
{
  if constexpr (some_compile_time_expression)
  {
    return GetReferenceFromSomewhere();
  }
  else
  {
    return GetValueFromSomewhere();
  }
}
模板
auto&&Func()
{
if constexpr(某些编译时表达式)
{
返回getReferenceFromsomeone();
}
其他的
{
返回getvaluefromwhere();
}
}
这适用于所有类型的引用,但不适用于值。例如,如果
getvaluefromwhere
返回一个
Foo
,那么编译器将
Func
的返回类型推断为
Foo&
,并警告我正在返回一个临时文件的地址

是否有任何方法可以使这项工作正常进行,或者我是否被迫以某种方式将两个分支分开(通过函数重载或类似的方式)?

使用返回类型占位符,它将保留您在
return
语句中调用的函数的确切值类别

template<typename T>
decltype(auto) Func()
{
  if constexpr (some_compile_time_expression_dependent_on_T)
  {
    return GetReferenceFromSomewhere();
  }
  else
  {
    return GetValueFromSomewhere();
  }
}
模板
decltype(自动)Func()
{
if constexpr(某些编译时表达式依赖于)
{
返回getReferenceFromsomeone();
}
其他的
{
返回getvaluefromwhere();
}
}

Pretorian的答案是完美的,但您可能还想了解使用范围更广的
std::conditional
。例如,考虑一个<代码> DATAY类型变量:<代码> int <代码>和一个成员函数,它根据引用的编译时间条件返回<代码> DATAu。
template <bool COND>
std::conditional_t<COND, int&, int> data() { return data_; }
或者,您可以在复制/移动构造函数之间切换:

class X {
    X(std::conditional_t<some_cond, const X&, X&&>) = default;
    X(std::conditional_t<some_cond, X&&, const X&>) = delete;
    ...
};
X类{
X(std::conditional_t)=默认值;
X(std::conditional_t)=删除;
...
};

等等。

就像一个符咒。非常感谢。我确实尝试过使用
std::conditional
。这不太好。@Petrruderman您的情况不同,因为返回类型由您内部调用的函数的返回类型决定。这就是
decltype(auto)
无疑是最好的解决方案的地方。
class X {
    X(std::conditional_t<some_cond, const X&, X&&>) = default;
    X(std::conditional_t<some_cond, X&&, const X&>) = delete;
    ...
};