如何编写依赖于模板参数的using(或) 声明?typedef我想实现这样的目标:
template<typename T>
class Class
{
// T can be an enum or an integral type
if constexpr (std::is_enum<T>::value) {
using Some_type = std::underlying_type_t<T>;
} else {
using Some_type = T;
}
};
Run Code Online (Sandbox Code Playgroud) GCC 不会编译此代码,而其他编译器(clang、msvc)会编译此代码
template<auto T>
struct S { };
int main() {
S<[]{int x,y; x<<y;}> s1; // compiles fine
S<[]{int x,y; x>>y;}> s2; // error
}
Run Code Online (Sandbox Code Playgroud)
错误:
error: expected ';' before '>>' token
| S<[]{int x,y; x>>y;}> s2;
| ^~
| ;
Run Code Online (Sandbox Code Playgroud)
但是,当我明确调用时operator>>,GCC 接受它
struct S2 {
void operator>>(S2 arg) { }
};
S<[]{S2 x,y; x.operator>>(y);}> s2; // compiles
Run Code Online (Sandbox Code Playgroud)
当我将 lambda 定义移到模板参数列表之外时,它也会进行编译
auto lam = []{int x,y; x>>y;};
S<lam> s; // compiles
Run Code Online (Sandbox Code Playgroud)
这是编译器错误吗?
我看到代码是这样的:
double d = GetDouble();
DoSomething(+d);
DoSomething(-d);
Run Code Online (Sandbox Code Playgroud)
我知道这有潜在的危险,并且不建议在 C++ 中使用一元+来强调该值是正数。<EDIT>“只是强调价值是积极的”是一条心理捷径。我知道它不会使负值变为正值。</EDIT>
C #语言参考并没有对此说太多:
一元 + 运算符返回其操作数的值。
SO 上有一个关于此的问题,但它被标记为 C、C++ 和 C#,并且没有一个答案明确提到 C#。