【问题标题】:Templated usings Can't be Nested in Visual Studio模板化 using 不能嵌套在 Visual Studio 中
【发布时间】:2019-07-23 18:02:20
【问题描述】:

这是尽可能简化的,我可以制作一个仍然遇到错误的玩具示例:

struct Vector3f64 {
    double x;
    double y;
    double z;
};

struct Vector3f32 {
    float x;
    float y;
    float z;
};

// I use this to select their element type in functions:
template <typename T>
using param_vector = std::conditional_t<std::is_same_v<std::remove_const_t<std::remove_reference_t<T>>, Vector3f64>, double, float>;

// This is the function I want to pull the return type from:
template <typename T>
T VectorVolume(const T x, const T y, const T z) {
    return x * x + y * y + z * z;
}

template<typename F, typename T>
using call_t = decltype(std::declval<F>()(std::declval<T>(), std::declval<T>(), std::declval<T>()));

// This function fails to compile:
template <typename T>
call_t<decltype(&VectorVolume<param_vector<T>>), param_vector<T>> func(const T& param) {
    return VectorVolume(param.x, param.y, param.z);
}

int main() {
    const Vector3f64 foo{ 10.0, 10.0, 10.0 };

    std::cout << func(foo) << std::endl;
}

call_t 来自Guillaume Racicot's answer,我想用它来查找返回类型。但我从 版本 15.6.7 收到此错误:

error C2064: term does not evaluate to a function taking 3 arguments<br>
note: see reference to alias template instantiation 'call_t<unknown-type,double>' being compiled
note: see reference to function template instantiation 'unknown-type func(const T &)' being compiled

这在 g++ 上运行良好:https://coliru.stacked-crooked.com/a/48b18b66c39486ef 如果我不将一个 using 语句传递给另一个语句,它甚至可以在 上运行良好:

template <typename T>
call_t<decltype(&VectorVolume<param_vector<T>>), double> func(const T& param) {
    return VectorVolume(param.x, param.y, param.z);
}

有什么办法可以解决这个问题吗?

【问题讨论】:

  • 你能把它拼接成一个我们可以复制和粘贴的可复制代码块吗?
  • @NathanOliver 您能否使用实时示例从以下位置复制:coliru.stacked-crooked.com/a/48b18b66c39486ef 我发现 cmets 很有帮助。如果这还不够,我想我可以返工。
  • 可能微软试图忽略这种完全不可读的代码;-)
  • 版本 15.9.5 编译成功,所以它可能是一个已修复的错误。
  • @JonathanMee 我可以找到解决方法,但我现在没有 Visual Studio 15.6。有没有办法可以使用在线编译器进行测试?编译器资源管理器没有那个特定版本。

标签: visual-studio-2017 visual-studio-2017 c++ templates visual-studio-2017 using return-type


【解决方案1】:

As mentioned by @NathanOliver 正确的解决方案是升级到已修复此问题的 15.9.5。但除非您可以使用 result_of or invoke_result 在 15.6.7 上通过将 call_t 更改为:

template<typename F, typename T>
using call_t = result_of_t<F&&(T, T, T)>;

请注意 result_of 中已弃用,因此如果您使用 "/std:c++17" 或 "/std:c++latest" 运行,这将不起作用,您需要使用更方便:

template<typename F, typename T>
using call_t = invoke_result_t<F, T, T, T>;

值得注意的是,Guillaume Racicot's answer 使用了优雅的 veradic 模板,如果您将 func 的定义更改为:

template <typename T>
call_t<decltype(&VectorVolume<param_vector<T>>), param_vector<T>, param_vector<T>, param_vector<T>> func(const T& param) {
    return VectorVolume(param.x, param.y, param.z);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2015-04-17
    • 1970-01-01
    • 2019-10-16
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多