如何自动替换返回模板的类型?++

1 c++ templates metaprogramming sfinae c++17

在 C++ 中是否可以自动替换模板返回值中的数据类型,而无需在括号中指定特定类型?

我正在练习元编程并尝试执行以下代码。我收到了下面指定的编译错误。

template <typename T>
T func(int value) {
    if constexpr (std::is_floating_point_v<T>)
        return (float)value;
    if constexpr (std::is_same_v<T,std::string>)
        return std::to_string(value);
    if constexpr (std::is_integral_v<T>)
        return value;
}

int main() {
    auto o1 = func<int>(6); //Ok int 6
    std::string o2 = func(6); // CE
}
Run Code Online (Sandbox Code Playgroud)

康桓瑋*_*康桓瑋 6

您可以使用模板转换运算符返回一个类

#include <type_traits>
#include <string>

struct Impl {
  int value;
  template<class R>
  operator R() const {
    if constexpr (std::is_floating_point_v<R>)
      return (float)value;
    else if constexpr (std::is_same_v<R, std::string>)
      return std::to_string(value);
    else if constexpr (std::is_integral_v<R>)
      return value;
  };
};

auto func(int value) {
  return Impl{value};
}

int main() {
  std::string s = func(1); // "1"
  float f = func(2);       // 2.0
  int i = func(3);         // 3
}
Run Code Online (Sandbox Code Playgroud)

演示