为什么我不能从 decltype 返回的 value_type 中获取 bool 值?
Why Can't I Get the bool Value from a value_type Returned by decltype?
这似乎是 visual-studio problem. This code runs fine in gcc 但无法在 Visual Studio 中编译:
#include <iostream>
#include <type_traits>
#include <typeinfo>
using namespace std;
true_type foo();
template <typename T>
struct bar{
using def = conditional_t<decltype(foo())::value, char, void>;
};
int main() {
cout << typeid(bar<int>::def).name() << endl;
cout << decltype(foo())::value << endl;
}
给出的错误是:
error C2146: syntax error: missing >
before identifier value
是否有针对此问题的错误修复或解决方法?
在您的问题中,您使用的是 decltype(foo())
:
using def = conditional_t<decltype(foo())::value, char, void>;
^^^^^
在 Ideone 上,decltype(foo)
:
using def = conditional_t<decltype(foo)::value, char, void>;
^^^^^
它们是不同的东西。在第一种情况下,您将获得 调用 foo
的结果类型。在第二个中,您将获得函数本身 的类型 .
好吧,从那时起,事情发生了翻天覆地的变化。
代码经过编辑,应该可以很好地编译,但是 Visual Studio 的编译失败了,而 clang 对这段代码非常满意,没有显示任何错误甚至警告。
因此,鉴于 clang(最新版本,使用 --std=c++14 -Wall -Wextra
)发现此代码正确,我相信这应该是 VS 中的一个错误。
我不确定它是否可以帮助你,但我可以像这样解决这个问题:
首先定义:
template <typename I> using id = I;
然后将 decltype(foo())::value
的每个实例替换为
id<decltype(foo())>::value
或者,您可以以相同的方式使用 std::common_type_t
:
std::common_type_t<foo()>::value
或者,我的灵能预测您可能只想为 decltype<foo()>
定义一个单独的类型,以方便起见:
using id = decltype(foo());
然后将 decltype(foo())::value
的所有实例替换为 id::value
。
这似乎是 visual-studio problem. This code runs fine in gcc 但无法在 Visual Studio 中编译:
#include <iostream>
#include <type_traits>
#include <typeinfo>
using namespace std;
true_type foo();
template <typename T>
struct bar{
using def = conditional_t<decltype(foo())::value, char, void>;
};
int main() {
cout << typeid(bar<int>::def).name() << endl;
cout << decltype(foo())::value << endl;
}
给出的错误是:
error C2146: syntax error: missing
>
before identifiervalue
是否有针对此问题的错误修复或解决方法?
在您的问题中,您使用的是 decltype(foo())
:
using def = conditional_t<decltype(foo())::value, char, void>;
^^^^^
在 Ideone 上,decltype(foo)
:
using def = conditional_t<decltype(foo)::value, char, void>;
^^^^^
它们是不同的东西。在第一种情况下,您将获得 调用 foo
的结果类型。在第二个中,您将获得函数本身 的类型 .
好吧,从那时起,事情发生了翻天覆地的变化。
代码经过编辑,应该可以很好地编译,但是 Visual Studio 的编译失败了,而 clang 对这段代码非常满意,没有显示任何错误甚至警告。
因此,鉴于 clang(最新版本,使用 --std=c++14 -Wall -Wextra
)发现此代码正确,我相信这应该是 VS 中的一个错误。
我不确定它是否可以帮助你,但我可以像这样解决这个问题:
首先定义:
template <typename I> using id = I;
然后将 decltype(foo())::value
的每个实例替换为
id<decltype(foo())>::value
或者,您可以以相同的方式使用 std::common_type_t
:
std::common_type_t<foo()>::value
或者,我的灵能预测您可能只想为 decltype<foo()>
定义一个单独的类型,以方便起见:
using id = decltype(foo());
然后将 decltype(foo())::value
的所有实例替换为 id::value
。